Import CBB refresh verify r4 stability baseline

Preserve tested Verify source, authoritative READY checks, bounded bridge retries, diagnostics and failure-only reporting. Include 336-test suite and packaging assets; exclude live Mentor samples, field logs, backups and distributions.
This commit is contained in:
阿白叔 committed 2026-09-29 15:05:20 +08:00
commit 11a2b2e46e
130 files changed
+19267

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
# 2026-09-28 r3 现场效率对比
## 本轮范围
人工同机约 12 分钟,因此不承诺软件调整能消除机器侧全部慢耗。保留直接 ReusableCircuit 启动、中心库路径修正、sAddress.adr 处理、32 位保存和最终权威状态门禁。
1. 四绿入口只强制刷新第一项。刷新后若某项真正变为 Required,则按实际状态补同步。非四绿入口保留既有四项路线。
2. 默认无进展超时统一为 600 秒。并非 CBB 总时长限制;可以在 UI 调整。已观察到第一项约 341 秒、Save 约 246 秒,600 秒覆盖这些已知阶段,但不保证未来所有调用都小于预算。
3. 去掉弹窗 IPC 连续请求/响应落盘、正常窗口重复快照和重复状态日志。仍有弹窗观察和确认,实际动作/错误以及失败现场保留。
4. 新增 performance.json 和 result.json 的 timings_seconds。总耗时用单调时钟计入清理,子阶段由 worker 原始时间与 helper 内部测量提供。未完成阶段单独标记;未执行的后续同步不会写入伪造的 0 秒。
## 现场复测
- 完整解压新包到独立本地目录,不覆盖旧包,不混入旧 data。
- 打开网络 mentor_lib.lmc,先只跑一个 Pending CBB;确认进入 PCB 后四灯均为绿色。
- 默认无进展超时为 600 秒。如果某一调用超过 600 秒且没有进展仍会 TIMEOUT;需要时调回 900 秒进行观察。
- events.jsonl 应有 backup_skipped;四绿入口的 integration_complete 应列出实际 action=['ForwardAnnotate'],policy=green_first_only。若执行之后另有 Required,则允许出现相应真实补同步动作。
- 对比 performance.json 中 forward_annotation_call、forward_annotation、save、post_save_check、close、total。父阶段与子阶段重叠,不直接累加所有键。
- 正常成功不应有 dialog-agent-requests.jsonl、dialog-agent-responses.jsonl 或连续 window_snapshots.jsonl。仅失败/超时才保存最终窗口现场。
- 回传本次 data(或至少 request.json/runtime.json/events.jsonl/save.log/performance.json/result.json 与批量报告)。
本地验证不会触碰生产中心库;冻结版代理 smoke 使用未打开任何 Mentor 工程的私有桌面。真实 Win10/网络库提速幅度需要上述现场对比,不以离线测试代替。
+64
View File
@@ -0,0 +1,64 @@
# 2026-09-29 r4 稳定性修复与现场复测
## 判定规则
正常执行、保存和关闭完成之后,只以 x86 状态桥的 `IsVerifiedReuseBlock` 返回 READY/raw=1 确认 PASS/GREEN。
- Cert 不参与成功判定。成功路径只记录预期的 Cert 路径,不访问 Cert 文件,避免 SMB stat 再次拖住退出阶段。
- 四灯全绿不是最终成功;只有最终桥接 READY 才确认成功。
- 旧 tuple/图标读数、桥缺失/错误/矛盾响应不能冒充 READY。
- 本次执行已经报错时,不会用之前遗留的 READY 覆盖错误。
- 初次 PENDING/不可用时,只读重查:立即查询、等 3 秒、再等 5 秒,最多三次;每次正式桥查询仍有既有 10 秒预算。不重复 Verify,也不重做保存。
- 三次 PENDING:FAIL/NOT_GREEN、分类 MENTOR_VERIFY_NOT_COMMITTED;桥不能可信读取:FAIL/UNKNOWN,明确区分未提交与无法确认。
## 日志中确认的工具问题
旧批次 68 项中 51 项 PASS/GREEN,17 项失败;下列分类来自归档现场,不代表 r4 已在该机验证。
| 旧日志现象 | r4 处理 | 尚需确认 |
| --- | --- | --- |
| 6 项 UNKNOWN_DIALOG: TF_FloatingLangBar_WndTitle | 仅忽略标题、CiceroUIWndFrame 类名且无子控件三者同时满足的 IME 语言栏;继续处理真正弹窗 | 这 6 项需重跑确认没有其他 Mentor 错误 |
| TUNER_ATBM253 被 Cert 成果检查拦截 | 移除 Cert 成功门禁和成功路径的 Cert 文件访问 | 只有本次正常完成且桥接 READY 才会通过 |
| TUNER_R836 Save/Close 后桥返回 PENDING | 有界只读复查并保留每次状态、来源、raw、实际查询耗时 | 若三次仍 PENDING,保留失败;不假设一定是延迟 |
| TUNER_R836_A 原生数据库打开失败被记为 UNKNOWN_DIALOG | 记录 MENTOR_DATABASE_LOAD_FAILED,只点 IDNO=7,不打开日志查看器 | 原生数据库失败本身未自动修复 |
| 5 项 Project Integration 符号错误,仅有符号头信息 | 按 Mentor 同步错误分类,留存原生日志尾部和多行说明 | 需根据原生日志修复符号/封装/映射等具体工程问题 |
| 3 项 JobPrefs/本地 Cell Library 失败 | 轻量目录/JobPrefs 诊断、独立原生日志留存 | 不凭临时目录缺失推断损坏,不自动重建数据库 |
## 新增证据与效率边界
每个已启动 worker 的证据目录内:
- `diagnostics/preflight.json`:PCB 目录、三处已知 JobPrefs 路径的存在性、大小/mtime、单字节可读性,以及 PCB 目录的一次创建/关闭写入探测。
- 写入探测使用唯一临时文件、独占创建并自动关闭删除,只针对本次创建的空文件;在 Mentor 启动前结束,不修改任何已有数据库/锁文件。
- `Work\PCB\Layout_Temp` 和 `Work\PCB\Work\Layout_Temp` 可能由 Mentor 创建,缺失仅为诊断警告,不阻断 Verify。
- `diagnostics/native-logs/`:失败时留存已知路径中的 PCBLogFile.txt、ForwardAnnotation.txt、PartPkg.log、MsgBoxResponse.log、ReusableBlock.txt。按源位置区分同名文件。
- 单个原生日志只取最后 128 KiB,保留原始字节编码;`native-logs.json` 记录原路径、大小、mtime、截断/复制错误。文件尾部截断可能省略更早内容,并非整份数据库备份。
- worker 失败清理前先尝试采集;父级清理完成后由独立只读 helper 再尝试一次。helper 最多 8 秒,超时终止、记录 `native-log-capture.json`,不把采集失败变成新的 Verify 原因。
- 正常成功不采集原生日志;不递归遍历网络库,不恢复高频窗口/请求响应 JSONL。
- `bridge-status.json` 保存最终桥接查询尝试;`result.json` 新增 error_category/error_stage/bridge_attempts;失败采集耗时单列 failure_diagnostics,计入 total。
保留 r3:默认 600 秒连续无进展预算(不是整项总时长限制);初始四绿只点第一项,随后仅补 Required;网络盘不做递归备份;弹窗代理使用本机认证内存 IPC;保留真实阶段计时。
## 只包含失败项的批次日志
每次批次结束,在同一 reports 目录生成共享批次标识的两份报告:
- `batch-<时间>-<标识>.log`:完整批次。
- `failures-<时间>-<标识>.log`:仅失败/超时/阻断/无法确认等失败项;PASS、SKIPPED、QUEUE_STOP 不列为失败。
失败报告包括 CBB、状态、错误分类、失败阶段、桥状态、原始错误摘要、证据路径和实测耗时。多行错误转义成可见的 `\r/\n/\t` 保证一行一项;原始多行文本在 native-logs 和 result.json 中。没有失败时保留“本批次没有失败项。”,不是少生成一个文件。界面结束摘要和 CLI application.log 都指向失败报告。
## 上机测试
1. 完整解压到新的本地目录,保留整个 CbbRefreshVerify-Background 文件夹,不覆盖旧 r3,不混入旧 data。
2. 打开 CbbRefreshVerify.exe,选现场网络盘 mentor_lib.lmc,保持默认 600 秒;真实阶段若连续无进展超过 600 秒,仍需按现场情况提高预算。
3. 优先重跑旧的 6 个 IME 误判项:DCDC_R82060_B、DCDC_R62140_2V5_A、DCDC_R62140_2V5、DCDC_R82060_1V8_A、DCDC_R82060_1V2、DCDC_R62140_5V。
4. 随后重跑 TUNER_ATBM253 与 TUNER_R836,查看 bridge-status.json 是否真正返回 READY,而不是仅看 worker 的 complete/PASS。
5. 对仍有原生报错的项,回传失败清单及对应整个 verify-* 证据目录,尤其 diagnostics/native-logs、native-logs.json、preflight.json、events.jsonl、save.log、performance.json、result.json。
6. 再跑长批次;关注错误分类、是否正常继续下一项、实际耗时,而非只比较总成功率。
## 安全与验证限制
不删除或抢占既有锁文件,不改 SMB/oplock 设置,不自动修复/重建 JobPrefs 或其他工程数据库。不将这些原生错误的根因预先归咎于 SMB。
本机 336 项自动化测试及 compileall 已通过,测试外部 COM/进程/桥接边界使用模拟;具体冻结版检查以 BUILD-MANIFEST.json 的 qa 记录为准。本轮本地验证不启动真实 Mentor 工程、不修改生产 CBB;真实 Win10 网络盘的稳定性/性能仍由现场复测确认。
@@ -0,0 +1,32 @@
# 2026-09-24 Verify 触发链审计
## 结论
当前现场失败发生在 Library Manager 的 Verify 命令派发阶段。事件顺序是:
```text
verify_invoke
verify_invoke_returned
verify_menu_fallback
lm_session_ready
```
之后没有观察到目标 `ExpeditionPCB.exe`、`pcb_worker_started` 或 COM 文档。因此菜单调用返回和菜单关闭都不能视为 Verify 成功。
本次失败现在会分类为 `VERIFY_DISPATCH_FAILED`,而不是笼统的 `TIMEOUT`;现场的进程、窗口和派发前后观察仍会保留在证据目录。
## 与 2026-09-17 备份的对比
备份中的生产路径同样是私有桌面上的 Library Manager:定位 LMC 树节点、选中 Logical-Physical CBB、打开原生右键菜单,再通过 UI Automation `InvokePattern` 调用 `Verify`。它没有调用已确认的后台 Verify API,也没有证明菜单调用后一定会进入 MFC 命令路由。
备份里的 `runs/verify-report-1GPHY_RTL8211F_A.json` 明确记录为 `BLOCKED`,原因是没有完成对话框或可读取的最终状态;`evidence/cloned-verify-run.json` 只有 `verify_sent` 和 Library Manager 窗口,没有 PCB 启动证据。因此不能把备份代码直接恢复并声称它已经稳定成功。
## 当前实现与风险边界
当前私有桌面路线仍保留旧实现的右键消息和 UIA 菜单调用,并增加了菜单坐标回退。现场已经证明回退只说明弹出菜单处理发生,不能说明 Library Manager 执行了 Verify。没有拿到 `VerifyReuseBlock` 私有 ABI 的安全参数定义前,不能把导出函数或猜测的 `WM_COMMAND` 当作生产触发接口。
## 后续可验证方向
1. 在不触碰生产中心库的前提下,继续使用状态桥和只读进程观察确认菜单派发的真实结果。
2. 如果需要恢复前台兼容触发,只能做成显式测试模式,不能混入默认后台批处理。
3. 只有取得可靠的原生命令路由或已重建的私有 ABI,并用 PCB、Project Integration、保存关闭、进程退出和 READY 状态全部复核后,才能把触发路线升级为生产默认。
@@ -0,0 +1,122 @@
# 2026-09-29 r4 现场日志核查
## 结论
r4 的判定、串行执行、效率优化和诊断留存行为符合本批次预期;但并非所有失败项都已修复。这次是上一批 17 个失败项的针对性复测,9 项 PASS/GREEN、8 项 FAIL、0 项 TIMEOUT、0 项跳过。不能拿 9/17 与上一轮全批次 51/68 当作全库成功率的直接对比。
- 先前 6 个语言栏误判项全部 PASS,未再出现 UNKNOWN_DIALOG/TF_FloatingLangBar_WndTitle 失败。
- 先前 3 个 JobPrefs/本地 Cell Library 失败项本次 PASS:DCDC_R82060_1V5_A、USB_2_ADJ_DOUBLE_ESD_B、USB_2_DOUBLE_ESD_A。工具没有重建这些数据库,所以只能确认本次恢复,不能宣称间歇问题的根因已经被永久修复。
- 9 个 PASS 都有正式 IsVerifiedReuseBlock READY/raw=1;初次扫描时这 17 项均为 PENDING。不是拿原有 READY 或四绿冒充本轮成功。
- 2 个保存关闭后 PENDING 的项都严格进行了三次只读查询,仍为 raw=0 后记录 FAIL/NOT_GREEN;无重复 Verify/Save。
## 逐条验收
| 预期 | 现场证据 | 结论 |
| --- | --- | --- |
| 正常完成后只以桥接 READY 确认成功 | 9 个 PASS 各一次权威读取 READY/raw=1 | 符合 |
| Cert 不参与门禁且成功路径不访问 Cert | 11 个执行完成项 cert_diagnostics 均 non_blocking=true、probed=false | 符合 |
| 初始四绿只点第一项 | 16 个进入同步的项初始四项均为 2,各仅一次 ForwardAnnotate;11 个完成项 policy=green_first_only | 符合 |
| 网络盘不递归备份 | 17 项 backup_skipped,reason=network_source | 符合 |
| PENDING 有界只读重查 | 两项三次均 PENDING;library_flag 总耗时 8.797/8.844 秒,单次桥读取约 0.27 秒 | 符合 |
| 原生 DB 打开失败准确分类且拒绝额外查看器 | TUNER_R836_A:MENTOR_DATABASE_LOAD_FAILED,win32_button_click,accepted_control=[7] | 符合 |
| 失败日志只包含失败 | failures-20260929-133101-e696e2.log 8 行失败项,与 17 个 result.json 精确对应,UTF-8 BOM 正常 | 符合 |
| 诊断不拖慢正常流程 | 每项仅一次 preflight_diagnostics;失败补采集约 0.704–0.875 秒 | 符合 |
| 不恢复高频调试抓取 | 无请求/响应 JSONL;仅数据库弹窗失败项有最终 window_snapshots.jsonl | 符合 |
| 串行失败后继续 | 17 项跑完;每项 PCB 启动一次、Save helper 最多一次;每次 pcb_baseline 为空 | 本批符合 |
现场环境由 runtime.json 确认:Windows 10 Pro,build 19042.1706,Python 3.12.10/64-bit;所有 request 的 timeout=600。当前使用 reusable_circuit_direct 路线,native_lm_verify=false。
## 剩余 8 项的原因
### 五项明确的封装/Part Number 对应关系错误
当前 PartPkg.log 有错误头之后的完整说明;这是本轮诊断留存的实际收益,不再只能看到 Symbol ID。
| CBB | Part Number | 被 Mentor 拒绝的 Cell Name |
| --- | --- | --- |
| CBB_MXL608 | 5700-G45320-0S00 | LEDC450X320 |
| TUNER_MXL608_Shield | 5700-G45320-0S00 | LEDC450X320 |
| TUNER+DEMOD_DVB-C_M88RC6800 | 5700-G45320-0S00 | LEDC450X320 |
| RTL8197x | 474Z-R81970-1280 | DRQFN50P1000X1000X90-129N-1 |
| TUNER_R836_H_CBB | 47FZ-R83600-0240 | QFN50P400X400X80-25CN |
共同原生错误为 `Cell Name ... is not a valid cell for Part Number ...`,并明确 `Design has NOT been packaged`。需核对中心库 PartsDB 允许的 cell 与工程符号/封装属性;工具不应自行猜测正确 cell、盲目改名或删除数据库。TUNER_R836_H_CBB 还记录了 Symbol/PartsDB 的 Part Name 不一致(CN/DN),只是核对线索,不意味着可直接批量替换。
### TUNER_ATBM253:保存 Reusable Block 时缺少 DXF cell
当前 ReusableBlock.txt 的日期为 2026-09-29、12:56 PM,报:
```
Error saving the reusable block. The following cells are missing from the Central Library:
DXF
```
save.log 同时有 SAVE_OK、IS_SAVED、CLOSE_OK、QUIT_OK;但正式桥三次均 PENDING/raw=0。因此 PCB 文档保存的返回值不足以证明 Reusable Block 认证提交成功,最终桥接门禁在这里正确阻止了误报成功。
这项现在有明确的原生保存错误,不能继续归因于“Cert 文件晚生成”或单纯等待不够。需要核查实际被引用的 DXF cell 和中心库缺失关系,而不是把 DXF 当无用内容直接删除。
诊断可读性仍有不足:失败清单目前只写 MENTOR_VERIFY_NOT_COMMITTED,没有自动把该原生缺 cell 原因提炼出来。后续可增强失败摘要,不改变 READY 金标准。
### TUNER_R836_A:旧服务器会话失联导致数据库打开失败
当前 PCBLogFile.txt 明确写:
```
The last server session on different server machine lost the connection to the database.
Please use iCDB Project Backup 'Repair project' functionality to fix this issue.
Machine: EDA03
Path: S:\ReusableBlocksLP\TUNER_R836_A\Work\database
Session: 2025-01-21 14.44.46-2323356
```
目录写入探测通过,已有 JobPrefs 可读,所以不能据此当作简单目录缺失/通用写权限失败。应把这是 Mentor 报告的旧会话/工程数据库一致性问题与“程序当前是否持有 SMB 锁”分开处理;日志不能直接证明后者。原生日志建议使用其 Repair project 功能;工程修复需要人工确认和完整备份,不自动删锁/改数据库。
特别注意:此项 PartPkg.log 是 2025-01-21 的历史日志,ReusableBlock.txt 是 2023-08-22 的历史日志;不能拿里面的旧封装错误替代本次启动失败原因。
### TUNER_R836:仍未定位最终认证没有提交的原因
- Save/IsSaved/Close/Quit 全部有成功标记。
- ReusableBlock.txt 本次只写 `A certified reusable block will be created.`,不是实际提交成功证明。
- 初次状态及结束后三次权威状态均 PENDING/raw=0。
- PCBLogFile.txt 有 `Cannot Stop the Cross Probe Daemon`,但现有证据不足以认定它就是根因,也不足以推断 SMB 文件锁。
后续优先对照这一项的人工原生 Verify 与当前 direct ReusableCircuit 的目标身份及提交过程。它的 PCB 文件是 Board1.pcb,这是核对目标关联的线索,不是认定名称错误的证据。不要因一个文件名不同就改名,也不要单纯继续增大等待预算后假装 READY。
## 性能结论
本批实际执行区间为 2026-09-29 11:28:41–13:31:01,累计单项 total 约 122.36 分钟。
9 个成功项:
| 指标 | 范围 | 平均 |
| --- | --- | --- |
| 单项 total | 446.156–999.844 秒(7.44–16.66 分钟) | 646.713 秒(10.78 分钟) |
| preflight | 0.172–0.812 秒 | 0.283 秒 |
| worker_setup | 1.313–2.844 秒 | 1.825 秒 |
| PCB 启动/附着 | 53.375–108.172 秒 | 72.899 秒 |
| ForwardAnnotate COM 调用 | 223.547–510.516 秒 | 315.335 秒 |
| doc.Save 调用 | 143.625–370.305 秒 | 228.652 秒 |
| 最终 bridge | 0.265–0.328 秒 | 0.285 秒 |
ForwardAnnotate COM 调用加 Save 占成功项总耗时约 84.1%。最慢的 DCDC_R82060_1V2:Forward COM 510.516 秒,Save 370.305 秒,total 999.844 秒。不存在反复点四项或长时间 Cert/桥接轮询的证据。
可确认慢主要发生在这些 Mentor 调用返回之前;无法仅凭调用耗时进一步区分内部运算、机器性能和网络 I/O。600 秒是连续无进展预算,不是整项总时长上限;本批最长的单个 Forward COM 和 Save 都小于 600 秒,超过 10 分钟的整项仍正常完成符合设计。
## 后续优先级
1. 诊断摘要改进:对最终 PENDING 项自动附加本轮原生 ReusableBlock 错误;给 TUNER_ATBM253 明确显示缺 DXF,而不只显示 PENDING。已知数据库旧会话错误也可提炼入失败摘要。
2. 工程侧核对三个 Part Number/cell 对应组,检查 DXF 缺失关系;数据库修复按 Mentor 原生提示另行人工确认。
3. TUNER_R836 单项对照人工 Verify 的目标和认证写回流程。保持权威 READY 判定,不再用四绿、SAVE_OK 或 Cert 替代。
4. 这次是旧失败项回归,不等同于全库多轮稳定性验证;JobPrefs 三项恢复尚需长批次重跑确认。
本次只做日志和代码路径核查,没有改生产代码,没有运行 Mentor 或修改任何现场工程。
## 本地证据
- 原始归档:F:\Sync Tool Skyworth\Work Maps\cbb-refresh-verify-795\Data temp\data.rar
- SHA256:cd5498911eba09615205f1215ecab76d1969bcda25857ec016c85ae8f5af4f3a
- 解压目录:F:\Sync Tool Skyworth\Work Maps\cbb-refresh-verify-795\Data temp\extracted-20260929-r4\data
- 原始失败清单:F:\Sync Tool Skyworth\Work Maps\cbb-refresh-verify-795\Data temp\extracted-20260929-r4\data\reports\failures-20260929-133101-e696e2.log
- TUNER_ATBM253 原生错误:F:\Sync Tool Skyworth\Work Maps\cbb-refresh-verify-795\Data temp\extracted-20260929-r4\data\evidence\verify-121087f0c1b5\diagnostics\native-logs\pcb-logfiles-ReusableBlock.txt
- TUNER_R836_A 当前错误:F:\Sync Tool Skyworth\Work Maps\cbb-refresh-verify-795\Data temp\extracted-20260929-r4\data\evidence\verify-4c80efa55d79\diagnostics\native-logs\pcb-logfiles-PCBLogFile.txt
- TUNER_R836 当前状态:F:\Sync Tool Skyworth\Work Maps\cbb-refresh-verify-795\Data temp\extracted-20260929-r4\data\evidence\verify-e2ca67e894e5\bridge-status.json
@@ -0,0 +1,49 @@
{
"build": "2026-09-29-r4-stability",
"default_inactivity_timeout_seconds": 600,
"green_entry_policy": "forward_once_then_only_required",
"network_preverify_backup": false,
"dialog_ipc": "authenticated_loopback_memory",
"gold_standard": "IsVerifiedReuseBlock READY/raw=1 after execution success",
"cert_success_gate": false,
"cert_success_path_file_io": false,
"post_verify_bridge_attempts": 3,
"bridge_retry_delays_seconds": [
0,
3,
5
],
"failure_report": "reports/failures-<same-batch-id>.log",
"native_log_tail_max_bytes": 131072,
"post_cleanup_log_capture_timeout_seconds": 8,
"no_database_or_lock_auto_repair": true,
"tests_passed": 336,
"compileall": "PASS",
"build_host": "Windows-11-10.0.26200-SP0",
"target_validation": "Windows 10 field test required; no real Mentor jobs launched locally",
"qa": {
"frozen_failure_log_helper": "PASS (bounded tail, multiline bytes, originals unchanged, no Mentor launch)",
"frozen_private_desktop_agent": "PASS (40 observes, authenticated memory IPC, gate absent)",
"no_high_frequency_jsonl": "PASS",
"frozen_ui_smoke": "PASS (packaging build lifecycle check)"
},
"source_sha256": {
"defaults.py": "45ab8430c9a146cf86694a3092e6aaf53b4a441a064ec540416ca64389876649",
"integration.py": "73171c1ab0f980f4c991c1962da847a98044bf23a62723fecc7258f153f3328a",
"runtime_timing.py": "3e630c470b419cd1c34297e4fd69d62c9c4fa997ae81cddda8ef3e62cf6f079e",
"dialog_agent.py": "352b5249f0a50ab5bb1a563321c2855e8a86b50a7f12c465a530a5c64bc58b72",
"verify_runner.py": "f06f14848e96265a7528a9d34a44673365c22857bdca5687d2d7b0f2c67ee1a6",
"mentor_adapter.py": "aca6343889807c88b2a761f480236eef2199777ab7b7997185f5219d67396b84",
"dialog_rules.py": "8a0796e469ea8776882f67761871298c91edcb5b40065eb2842cd70449547830",
"dialog_supervisor.py": "17a491d749f414b9629b854260bd9075217b89ad31d0fb31799cd14c41c7b2ed",
"verify_diagnostics.py": "578aa5e0dded29048d0f1bea701bfa8724ba3c8a0f78bfe349119e7f855000c7",
"application.py": "3711f58a874e860106739cde04f19dfa34f1d4713284fc33c076404ff999f238",
"save_verified_block.vbs": "7736023de2bae41832c7a11672f49bea5443e125b55236e0d784212fdbd385a7",
"ui/main_window.py": "3ab7a271afa204dd9f90f59872d5322071c3128dd002298878bc2dbb7e5a33d7"
},
"bridges_x86_sha256": {
"CbbStatusBridge32.exe": "d6e430b899eb8b7b029f67bc3006453287ab7751509b865f89bfd96a0c51acd7",
"VerifyProbe32.exe": "5b2bbec3b4cbab3e94992abcf64f67f9d88c710c89e5bf2a1e8ca7f7a527890d"
},
"exe_sha256": "b6bdc94961f92992f934dada8c717fb2c6833e6aa69bf873b13e22d5b3a71b7b"
}
@@ -0,0 +1,33 @@
CBB Verify — Win10 上机测试包(2026-09-29 r4 稳定性版)
运行:完整解压到新的本地目录,打开 CbbRefreshVerify-Background\CbbRefreshVerify.exe。
不要只拷贝 EXE;不要覆盖旧 r3;不要把旧 data 混进新包。
需要现场已有 Mentor EE7.9.5EE 环境,选择网络盘 mentor_lib.lmc。
本版:
1. 正常执行、Save/IsSaved/Close 完成后,只认状态桥 IsVerifiedReuseBlock 的 READY/raw=1。
2. Cert 不再阻断成功,正常完成后不再读取 Cert 的文件状态。
3. 最终 PENDING/暂时不可用只读重查:立即、等 3 秒、再等 5 秒,最多 3 次;不重做 Verify。
4. 严格忽略无控件 IME 语言栏;原生数据库打开失败准确分类、点 No,保留错误。
5. 轻量 JobPrefs/目录诊断;临时目录缺失不阻断;不删除锁/数据库、不自动重建数据库。
6. 失败时保存已知 Mentor 日志尾部及多行说明;单文件最多 128 KiB;清理后补采集 helper 最多 8 秒。
7. 同时生成完整 batch-*.log 和仅失败 failures-*.log;界面结束摘要给出两个路径。
8. 保留默认 600 秒无进展超时、四绿仅第一项刷新、网络盘不递归备份、内存 IPC、真实阶段计时。
优先复测:
- 旧的 6 个 TF_FloatingLangBar_WndTitle 误判项。
- TUNER_ATBM253:不再由 Cert 门禁阻断,但必须最终桥接 READY。
- TUNER_R836:观察桥是否在三次读取内从 PENDING 到 READY;一直 PENDING 必须仍报失败。
- 原生数据库/Project Integration/JobPrefs 失败项:查看新的 diagnostics,而不是盲删锁文件。
回传:
- data\reports\failures-*.log(只失败清单)和匹配的 batch-*.log。
- 对应 data\evidence\verify-* 的整个文件夹,尤其:
result.json、performance.json、events.jsonl、save.log、bridge-status.json
diagnostics\preflight.json、native-logs.json、native-log-capture.json、native-logs\*
- 若方便,仍建议压缩整个新 data。
本地验证:336 项自动化测试通过;compileall 通过;冻结版 UI 与私有桌面弹窗代理通信通过;
冻结版失败日志采集入口通过(本地模拟文件,不启动 Mentor)。详细记录见 BUILD-MANIFEST.json。
本版修复工具误判和证据不足,不承诺原生工程数据库/符号问题已修复。
真实 Win10 网络盘的稳定性/性能仍需现场测试;600 秒是连续无进展预算,不是单项总时长上限。
@@ -0,0 +1,335 @@
# CBB Refresh Verify Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Build and package a directly usable Windows CBB contents-verification tool that follows the DxDesigner replacement tool's application and release standards.
**Architecture:** Reuse the replacement tool's PySide6 bootstrap, logging, worker, and onedir PyInstaller conventions while keeping CBB-specific logic in focused library-reader, verify-runner, and evidence modules. COM library enumeration and the official `ReuseBlockImporter.exe -chkContents` process are isolated behind Qt-free interfaces so they can be tested with fakes.
**Tech Stack:** Python 3.12, PySide6, pywin32 COM, pytest, PyInstaller 6.x, PowerShell build scripts.
**Spec:** `docs/superpowers/specs/2026-09-16-cbb-refresh-verify-design.md`
## Global Constraints
- Windows desktop target.
- Python `>=3.12,<3.13`.
- Dependencies remain limited to PySide6 and pywin32 plus existing build/test tools.
- Final release is `dist\\CbbRefreshVerify\\CbbRefreshVerify.exe` in onedir layout.
- No fixed-coordinate UI automation, SendKeys, or production-library writes.
- DMS-unavailable runs must classify as `BLOCKED` or `UNKNOWN`, never fabricated PASS.
- Runtime classification must not consume historical screenshots or old run JSON files.
---
### Task 1: Align Project Metadata and Runtime Layout
**Files:**
- Modify: `pyproject.toml`
- Create: `src/cbb_refresh_verify/__init__.py`
- Create: `src/cbb_refresh_verify/application.py`
- Modify: `src/cbb_refresh_verify/__main__.py`
- Test: `tests/test_application.py`
**Interfaces:**
- Produces `cbb_refresh_verify.application.main(argv: Sequence[str] | None) -> int`.
- Produces `resolve_data_root(cli_value: Path | None) -> Path`.
- Supports `--smoke-test --data-root <path>` and logs `application_start` plus `application_clean_shutdown`.
- [ ] **Step 1: Write failing bootstrap tests**
```python
def test_smoke_arguments_exit_zero_and_write_lifecycle_log(tmp_path):
from cbb_refresh_verify.application import main
assert main(["--smoke-test", "--data-root", str(tmp_path)]) == 0
text = (tmp_path / "logs" / "application.log").read_text(encoding="utf-8")
assert "application_start" in text
assert "application_clean_shutdown" in text
```
- [ ] **Step 2: Run the focused test and verify it fails**
Run: `python -m pytest tests/test_application.py -q`
Expected: FAIL because the lifecycle bootstrap and logging context do not exist.
- [ ] **Step 3: Port only the replacement tool's bootstrap patterns**
Implement `application.py` with argument parsing, product-specific data root, logging setup, exception hooks, QApplication creation, and a smoke-test timer. Keep the CBB window import lazy. Use an absolute import in `__main__.py`.
- [ ] **Step 4: Run the focused test and verify it passes**
Run: `python -m pytest tests/test_application.py -q`
Expected: PASS with zero failures.
- [ ] **Step 5: Commit the bootstrap slice**
```text
git add pyproject.toml src/cbb_refresh_verify tests/test_application.py
git commit -m "feat: align cbb application bootstrap"
```
### Task 2: Implement Typed Central-Library Reader
**Files:**
- Create: `src/cbb_refresh_verify/models.py`
- Modify: `src/cbb_refresh_verify/library_reader.py`
- Test: `tests/test_library_reader.py`
**Interfaces:**
- `CbbRecord(name: str, partition_name: str, logical_type: str)`.
- `LibraryReadResult(records: tuple[CbbRecord, ...], error: str | None)`.
- `read_library(path: Path, *, dispatch: Callable | None = None) -> LibraryReadResult`.
- [ ] **Step 1: Write failing reader tests with COM fakes**
```python
def test_reader_filters_reusable_block_partition_and_returns_sorted_records():
result = read_library(Path("fixture.lmc"), dispatch=fake_dispatch)
assert [item.name for item in result.records] == ["A_CBB", "Z_CBB"]
assert result.error is None
def test_reader_surfaces_com_error_instead_of_returning_empty_success():
result = read_library(Path("fixture.lmc"), dispatch=lambda _: (_ for _ in ()).throw(RuntimeError("DMS")))
assert result.records == ()
assert "DMS" in result.error
```
- [ ] **Step 2: Run reader tests and verify they fail**
Run: `python -m pytest tests/test_library_reader.py -q`
Expected: FAIL because typed records and structured errors are not implemented.
- [ ] **Step 3: Implement COM reader and test seam**
Dispatch `LibraryManager.Application`, open the `.lmc`, inspect partition type `7`, enumerate reusable-block entries, and return sorted unique CBB records. Preserve exception text in `LibraryReadResult.error`; do not swallow exceptions into `[]`.
- [ ] **Step 4: Run reader tests and verify they pass**
Run: `python -m pytest tests/test_library_reader.py -q`
Expected: PASS with zero failures.
- [ ] **Step 5: Commit the reader slice**
```text
git add src/cbb_refresh_verify/models.py src/cbb_refresh_verify/library_reader.py tests/test_library_reader.py
git commit -m "feat: read reusable blocks from central libraries"
```
### Task 3: Implement Verify Runner and Evidence
**Files:**
- Create: `src/cbb_refresh_verify/verify_runner.py`
- Create: `src/cbb_refresh_verify/evidence.py`
- Test: `tests/test_verify_runner.py`
**Interfaces:**
- `VerifyRequest(lmc_file: Path, block_name: str, libspec: Path, dms_login_config: Path, mentor_bin: Path | None, evidence_dir: Path, timeout_seconds: int)`.
- `VerifyResult(status: Literal["PASS", "FAIL", "TIMEOUT", "BLOCKED", "UNKNOWN"], exit_code: int | None, stdout: str, stderr: str, report_path: Path | None, evidence_path: Path | None, command: tuple[str, ...])`.
- `build_verify_command(request: VerifyRequest, executable: Path) -> tuple[str, ...]`.
- `run_verify(request: VerifyRequest, *, process_factory=...) -> VerifyResult`.
- [ ] **Step 1: Write failing command and classification tests**
```python
def test_command_uses_official_logical_physical_contents_check():
command = build_verify_command(request, Path("ReuseBlockImporter.exe"))
assert command == ("ReuseBlockImporter.exe", "-lmcFile", "lib.lmc", "-blockName", "CBB1", "-logicalType", "LP", "-chkContents", "-libSpec", "parts", "-dmsLoginConfig", "login")
def test_missing_executable_is_blocked():
assert run_verify(request_with_missing_executable()).status == "BLOCKED"
def test_success_requires_success_text_and_no_error_marker(fake_success_process):
assert run_verify(request, process_factory=fake_success_process).status == "PASS"
```
- [ ] **Step 2: Run runner tests and verify they fail**
Run: `python -m pytest tests/test_verify_runner.py -q`
Expected: FAIL because the request/result types and runner are absent.
- [ ] **Step 3: Implement validation, process execution, classification, and evidence**
Resolve the configured Mentor bin first and the known EE7.9.5 fallback second. Validate all required files before launching. Capture stdout/stderr, enforce timeout, terminate on stop, write a text report and JSON evidence, and classify only from current process output.
- [ ] **Step 4: Run runner tests and verify they pass**
Run: `python -m pytest tests/test_verify_runner.py -q`
Expected: PASS with zero failures.
- [ ] **Step 5: Commit the runner slice**
```text
git add src/cbb_refresh_verify/verify_runner.py src/cbb_refresh_verify/evidence.py tests/test_verify_runner.py
git commit -m "feat: run cbb contents verification with evidence"
```
### Task 4: Build the PySide6 UI With Background Workers
**Files:**
- Create: `src/cbb_refresh_verify/ui/main_window.py`
- Create: `src/cbb_refresh_verify/ui/workers.py`
- Modify: `src/cbb_refresh_verify/application.py`
- Test: `tests/test_ui.py`
**Interfaces:**
- `MainWindow(reader=read_library, verifier=run_verify)`.
- UI fields expose central-library path, CBB selection, LibSpec, DMS config, Mentor bin, evidence directory, Verify, Stop, status, output, report, and evidence path.
- [ ] **Step 1: Write failing UI behavior tests**
```python
def test_verify_disabled_until_required_fields_are_present(qtbot):
window = MainWindow(reader=fake_reader, verifier=fake_verifier)
qtbot.addWidget(window)
assert not window.verify_button.isEnabled()
window.lmc_edit.setText("lib.lmc")
window.libspec_edit.setText("parts")
window.dms_edit.setText("login")
assert window.verify_button.isEnabled()
def test_reader_error_is_visible_and_does_not_create_cbb_selection(qtbot):
window = MainWindow(reader=failing_reader, verifier=fake_verifier)
qtbot.addWidget(window)
window.load_library()
assert window.cbb_combo.count() == 0
assert "DMS" in window.status_label.text()
```
- [ ] **Step 2: Run UI tests and verify they fail**
Run: `python -m pytest tests/test_ui.py -q`
Expected: FAIL because the new window and worker classes are absent.
- [ ] **Step 3: Implement the UI and worker signals**
Use `QThread`/worker objects or the same worker pattern as the replacement tool. Load the central library asynchronously, populate the CBB list, disable controls while running, stream output, support Stop, and render the separate contents result and Library Manager green-state note.
- [ ] **Step 4: Run UI tests and verify they pass**
Run: `python -m pytest tests/test_ui.py -q`
Expected: PASS with zero failures.
- [ ] **Step 5: Commit the UI slice**
```text
git add src/cbb_refresh_verify/ui src/cbb_refresh_verify/application.py tests/test_ui.py
git commit -m "feat: add cbb verify desktop interface"
```
### Task 5: Align PyInstaller Onedir Packaging and Smoke Test
**Files:**
- Modify: `packaging/CbbRefreshVerify.spec`
- Modify: `packaging/Build-CbbRefreshVerify.ps1`
- Create: `tests/test_packaging.py`
- Modify: `README.md`
**Interfaces:**
- Build output: `dist/CbbRefreshVerify/CbbRefreshVerify.exe`.
- Smoke invocation: `CbbRefreshVerify.exe --smoke-test --data-root <temporary-directory>`.
- [ ] **Step 1: Write failing packaging checks**
```python
def test_spec_uses_onedir_collect_and_product_name():
text = Path("packaging/CbbRefreshVerify.spec").read_text(encoding="utf-8")
assert "COLLECT(" in text
assert "CbbRefreshVerify" in text
def test_build_script_validates_executable():
text = Path("packaging/Build-CbbRefreshVerify.ps1").read_text(encoding="utf-8")
assert "CbbRefreshVerify.exe" in text
```
- [ ] **Step 2: Run packaging checks and verify they fail**
Run: `python -m pytest tests/test_packaging.py -q`
Expected: FAIL because the current spec is one-file style and the build script lacks replacement-tool cleanup and smoke validation.
- [ ] **Step 3: Port the replacement tool's safe build flow**
Use project-root resolution, `.venv` preference, guarded cleanup of `build/CbbRefreshVerify` and `dist/CbbRefreshVerify`, `Analysis -> PYZ -> EXE -> COLLECT`, Qt binary exclusions, executable existence validation, and a hidden smoke run that checks startup and clean-shutdown log entries.
- [ ] **Step 4: Run packaging checks and build**
Run: `python -m pytest tests/test_packaging.py -q`
Run: `./packaging/Build-CbbRefreshVerify.ps1`
Expected: tests PASS, build exits 0, and `dist/CbbRefreshVerify/CbbRefreshVerify.exe` exists.
- [ ] **Step 5: Smoke-test the frozen executable**
Run: `dist/CbbRefreshVerify/CbbRefreshVerify.exe --smoke-test --data-root <temporary-directory>`
Expected: exit code 0; `<temporary-directory>/logs/application.log` contains `application_start` and `application_clean_shutdown`.
- [ ] **Step 6: Commit packaging and documentation**
```text
git add packaging tests/test_packaging.py README.md
git commit -m "build: package cbb refresh verify onedir release"
```
### Task 6: End-to-End Fixture Verification and Release Checklist
**Files:**
- Create: `tests/test_fixture_flow.py`
- Modify: `README.md`
- Create: `RELEASE-CHECKLIST.md`
**Interfaces:**
- Fixture flow verifies CBB discovery without modifying `fixtures` or the production library.
- Release checklist records build command, executable path, smoke output, fixture reader result, and DMS-dependent limitations.
- [ ] **Step 1: Write the fixture-flow test**
```python
def test_fixture_library_reader_finds_expected_cbb_names(fake_fixture_dispatch):
result = read_library(Path("fixtures/cloned-library/mentor_lib.lmc"), dispatch=fake_fixture_dispatch)
assert "1GPHY_RTL8211F_A" in {item.name for item in result.records}
```
- [ ] **Step 2: Run the fixture test and verify it fails**
Run: `python -m pytest tests/test_fixture_flow.py -q`
Expected: FAIL until the fixture dispatch adapter and typed result path are connected.
- [ ] **Step 3: Connect fixture adapter and document environment-dependent DMS behavior**
Keep the adapter read-only. Document that a missing DMS returns `BLOCKED`/`UNKNOWN`; only a real work-machine run can establish an actual Verify PASS.
- [ ] **Step 4: Run the full test suite**
Run: `python -m pytest -q`
Expected: PASS with zero failures.
- [ ] **Step 5: Rebuild and repeat frozen smoke test**
Run: `./packaging/Build-CbbRefreshVerify.ps1`
Expected: exit 0 and the executable plus lifecycle logs are present.
- [ ] **Step 6: Review release checklist and commit final state**
```text
git add tests/test_fixture_flow.py README.md RELEASE-CHECKLIST.md
git commit -m "test: validate cbb fixture flow and release criteria"
```
## Plan Self-Review
- Spec coverage: bootstrap/reuse, COM reader, Verify runner, UI, evidence, error handling, packaging, fixture testing, and DMS limitations each have a dedicated task.
- Placeholder scan: no `TBD`, `TODO`, or unspecified implementation steps remain.
- Type consistency: `CbbRecord`, `LibraryReadResult`, `VerifyRequest`, and `VerifyResult` are defined before UI and fixture tasks consume them.
- Scope: the plan does not copy replacement-tool business logic or add PCB synchronization/upload behavior.
@@ -0,0 +1,14 @@
# Real Library Manager Verify implementation
Goal: execute the demonstrated Verify / Project Integration / save-cell / close workflow serially. The older contents-check plan is superseded. Batch upload and parallel PCB editing are excluded from this release.
Evidence: Audio_D2128_ESD opened through its real Verify menu; ForwardAnnotation moved 1 -> 2; all four statuses reached 2; official 32-bit licensing helper authenticated Save; reusable-cell Yes confirmation was required; Save, IsSaved, Close returned true; LM returned Ready.
- [x] Test integration state transitions and late-bound COM invocation in tests/test_integration.py; implement integration.py.
- [ ] Replace verify_runner.py with preflight, isolated timed worker, serial queue, per-item evidence and failure report. Missing PCB must be BLOCKED without launching. Stop queue after timeout or unresolved PCB session.
- [ ] Implement mentor_adapter.py: exact library/tree identity; UIA physical bounds (native TVM rectangles are logical pixels at 125% scaling); real Verify menu; confirm actual project identity before editing. Use official 32-bit save helper and scope confirmation to launched PCB PID.
- [ ] Reuse replacement ServiceWorker and logging for asynchronous UI. Remove LibSpec/DMS inputs and unsupported concurrency. Expose library, CBB, timeout, single/batch, stop-after-current, logs.
- [ ] Test guards, UI responsiveness and library-path invalidation; run latest Audio and completed 2GPHY serially, with per-block backup. Skip two missing-PCB records.
- [ ] Package VBS resource and pywinauto, run frozen UI smoke and real frozen batch, document actual results. No PASS without statuses=2, Save/IsSaved/Close success, PCB exit and LM Ready.
This is a standalone non-git project. Preserve existing work and output a separate batch build so the old distribution remains recoverable.
@@ -0,0 +1,247 @@
# CBB Batch Status Bridge Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Read 180 to 3000 CBB Verify states through one resilient x86 Mentor bridge session with checkpoint recovery and authoritative `READY/PENDING` results.
**Architecture:** Extend the existing C++ bridge with a `--server` JSONL mode that loads `LMCDLL70.dll` once and serializes requests. Add a Python batch session that supervises the process, writes one checkpoint record per CBB, rotates the bridge periodically, resumes incomplete entries, and invalidates results when the LMC fingerprint changes. Keep the existing single-query API and default worker count at one.
**Tech Stack:** C++17, Win32/MFC/ATL, CMake, Python 3.12, JSONL, pytest.
**Spec:** `docs/superpowers/specs/2026-09-18-batch-status-bridge-design.md`
## Global Constraints
- `RULP/LP` maps to `eReuseBlockType = 0`.
- Mentor private DLL calls are read-only; no Verify/Unverify and no production-library writes.
- One active bridge session per LMC; requests are serialized.
- `UNKNOWN`, timeout, malformed response, bridge crash, and unavailable bridge never become `READY`.
- Do not call `FreeLibrary` after entering Mentor private MFC code; let the one-shot or server process exit reclaim the module.
- Default batch worker count is 1; concurrency is not enabled by this plan.
---
### Task 1: Define Batch Protocol and Checkpoint Models
**Files:**
- Create: `src/cbb_refresh_verify/batch_status.py`
- Test: `tests/test_batch_status.py`
**Interfaces:**
- Consumes: `BridgeResult`, `StatusBridgeClient`, and the existing `default_bridge_path()` from `status_bridge.py`.
- Produces: `LmcFingerprint`, `BatchStatusRequest`, `BatchStatusRecord`, `BatchCheckpoint`, and `fingerprint_library()`.
- [x] **Step 1: Write failing model and fingerprint tests**
```python
def test_fingerprint_changes_when_lmc_changes(tmp_path):
lmc = tmp_path / "mentor_lib.lmc"
lmc.write_bytes(b"one")
first = fingerprint_library(lmc)
lmc.write_bytes(b"two")
second = fingerprint_library(lmc)
assert first.sha256 != second.sha256
def test_checkpoint_ignores_truncated_json_line(tmp_path):
path = tmp_path / "scan.jsonl"
path.write_text('{"block_name":"A","status":"READY"}\n{"block_name":"B"', encoding="utf-8")
checkpoint = BatchCheckpoint.load(path)
assert checkpoint.completed_names == {"A"}
```
- [x] **Step 2: Run the focused tests and confirm collection failure**
Run: `pytest -q tests/test_batch_status.py`
Expected: FAIL because the new models and loader do not exist.
- [x] **Step 3: Implement the models and fingerprinting**
Implement `fingerprint_library(lmc: Path) -> LmcFingerprint` with file size, nanosecond mtime, SHA-256, and a deterministic recursive `ReusableBlocksLP` directory fingerprint. Implement `BatchCheckpoint.load(path)` by parsing only complete JSON objects and accepting only records whose `status` is `READY`, `PENDING`, or a terminal error.
- [x] **Step 4: Run the focused tests**
Run: `pytest -q tests/test_batch_status.py`
Expected: PASS.
- [x] **Step 5: Record the task result**
Save the test command and result in `runs/batch-status-implementation-checkpoints.md`; this repository is not a Git worktree, so use this artifact instead of a commit.
### Task 2: Add Persistent JSONL Server Mode to the x86 Bridge
**Files:**
- Modify: `tools/status_bridge/CbbStatusBridge32.cpp`
- Modify: `tools/status_bridge/README.md`
- Test: `tests/test_status_bridge_server.py`
**Interfaces:**
- Consumes: one JSON request per stdin line with `op=is_verified`, `lmc_file`, `block_name`, and `block_type`.
- Produces: one JSON response per request; `--server` exits nonzero only for startup failure, while an individual request returns an error object and the server continues.
- [x] **Step 1: Write protocol tests using a fake executable**
```python
def test_server_response_is_one_line_per_request(fake_server):
result = run_server_client(fake_server, ["A", "B"])
assert [item["block_name"] for item in result] == ["A", "B"]
def test_one_bad_request_does_not_stop_following_request(fake_server):
result = run_server_client(fake_server, ["BAD", "GOOD"])
assert result[0]["ok"] is False
assert result[1]["ok"] is True
```
- [x] **Step 2: Run the protocol tests and confirm failure**
Run: `pytest -q tests/test_status_bridge_server.py`
Expected: FAIL because `--server` and the client helper do not exist.
- [x] **Step 3: Implement the server loop**
Refactor the current private query into `queryOne(request)` and add `runServer()`. Load the DLL and resolve `IsVerifiedReuseBlock` once before the loop. For each line, validate fields, call the function inside the existing CString lifetime scope, emit a flushed JSON response, and continue after request-level errors. Do not call `FreeLibrary` in server mode.
- [ ] **Step 4: Build and run the real read-only smoke test**
Run from `tools/status_bridge`:
```powershell
cmake --build build-x86-final2 --config Release --parallel 2
$env:CBB_STATUS_BRIDGE_ALLOW_PRIVATE = '1'
$env:LMCDLL70_PATH = 'D:\Mentor\7.9.5EE\SDD_HOME\common\win32\lib\LMCDLL70.dll'
```
Send two requests to `CbbStatusBridge32.exe --server` and verify two responses, then terminate the server process. Do not send Verify or Unverify operations.
- [x] **Step 5: Update the bridge README and checkpoint**
Document `--server`, one-line request/response behavior, serialized processing, and the no-`FreeLibrary` rule. Copy the verified executable to `tools/status_bridge/bin/CbbStatusBridge32.exe` and record the build output in `runs/batch-status-implementation-checkpoints.md`.
### Task 3: Implement Supervised Batch Session and Checkpoint Resume
**Files:**
- Modify: `src/cbb_refresh_verify/status_bridge.py`
- Modify: `src/cbb_refresh_verify/batch_status.py`
- Test: `tests/test_batch_status.py`
**Interfaces:**
- Consumes: bridge `--server` JSONL protocol and `BatchCheckpoint`.
- Produces: `BatchStatusSession.scan(names, lmc_file, checkpoint_path, block_type="RULP") -> list[BatchStatusRecord]`.
- [x] **Step 1: Write failing supervisor tests**
```python
def test_scan_reuses_checkpoint_and_queries_only_missing(fake_server, tmp_path):
checkpoint = tmp_path / "scan.jsonl"
checkpoint.write_text('{"block_name":"A","status":"READY"}\n', encoding="utf-8")
records = BatchStatusSession(bridge=fake_server).scan(["A", "B"], lmc, checkpoint)
assert fake_server.requests == ["B"]
assert {record.block_name for record in records} == {"A", "B"}
def test_timeout_restarts_bridge_and_continues(fake_server, tmp_path):
records = BatchStatusSession(bridge=fake_server, timeout_seconds=0.1).scan(["A", "B"], lmc, tmp_path / "scan.jsonl")
assert records[0].status == "TIMEOUT"
assert records[1].status in {"READY", "PENDING"}
```
- [x] **Step 2: Run the focused supervisor tests and confirm failure**
Run: `pytest -q tests/test_batch_status.py -k 'scan or timeout'`
Expected: FAIL because `BatchStatusSession` is not implemented.
- [x] **Step 3: Implement one persistent subprocess session**
Add `StatusBridgeServer` to `status_bridge.py` with `start()`, `query(request)`, `restart()`, and `close()`. Use `Popen(..., stdin=PIPE, stdout=PIPE, stderr=PIPE, CREATE_NO_WINDOW)`, flush each request, read exactly one response line, and enforce a per-request deadline. On timeout or malformed response, terminate the process, record the failure, and restart before the next item.
- [x] **Step 4: Implement checkpoint writes and rotation**
`BatchStatusSession` must write a complete JSON record immediately after every response, skip names already completed under the same LMC fingerprint, and restart the bridge after 500 requests. Preserve terminal errors for resume, but never treat `ERROR`, `TIMEOUT`, or `UNAVAILABLE` as READY cache hits.
- [x] **Step 5: Run supervisor tests**
Run: `pytest -q tests/test_batch_status.py`
Expected: PASS.
### Task 4: Add Batch Fault Injection and Throughput Benchmarks
**Files:**
- Create: `tests/test_batch_status_faults.py`
- Create: `tools/benchmark_status_bridge.py`
- Modify: `README.md`
**Interfaces:**
- Consumes: `BatchStatusSession` and its JSONL checkpoint output.
- Produces: deterministic fault-injection coverage and a benchmark report for 180 and 3000 entries.
- [x] **Step 1: Add failure-isolation tests**
Test a malformed response, bridge exit between requests, a timeout on item 17, a truncated final checkpoint line, and an LMC fingerprint change. Assert that later items continue and no error record becomes READY.
- [x] **Step 2: Run fault tests and confirm they fail before benchmark wiring**
Run: `pytest -q tests/test_batch_status_faults.py`
Expected: FAIL only for missing fault fixtures or unimplemented supervisor behavior.
- [x] **Step 3: Implement the deterministic fake bridge fixtures**
Use a Python child process that reads JSONL, returns configured responses, sleeps for configured names, and exits at a configured request count. Do not use Mentor or UI automation in these tests.
- [x] **Step 4: Add the benchmark command**
`tools/benchmark_status_bridge.py` must accept `--count`, `--rotate-every`, and `--output`, generate deterministic names, run the batch session, and write total time, completed count, error count, mean latency, p95 latency, and bridge restart count.
- [x] **Step 5: Run the benchmark and document the baseline**
Run:
```powershell
$env:PYTHONPATH = 'src'
python tools/benchmark_status_bridge.py --count 180 --output runs/benchmark-180.json
python tools/benchmark_status_bridge.py --count 3000 --output runs/benchmark-3000.json
```
Document measured results in `README.md`; do not promise a fixed wall-clock time until the real Mentor bridge benchmark is available.
### Task 5: Package the Bridge and Prepare UI Integration Boundary
**Files:**
- Modify: `packaging/CbbRefreshVerify.spec`
- Modify: `packaging/Build-CbbRefreshVerify.ps1`
- Modify: `src/cbb_refresh_verify/ui/main_window.py`
- Test: `tests/test_packaging_status_bridge.py`
**Interfaces:**
- Consumes: `tools/status_bridge/bin/CbbStatusBridge32.exe` and `BatchStatusSession`.
- Produces: packaged bridge asset and an authoritative batch status hook enabled after acceptance.
- [x] **Step 1: Write packaging tests**
Assert that the packaged layout contains `tools/status_bridge/bin/CbbStatusBridge32.exe`, that the UI reports bridge unavailable instead of READY, and that the default worker count is 1.
- [x] **Step 2: Add the EXE as a PyInstaller data/binary asset**
Copy the x86 bridge into the frozen distribution under `tools/status_bridge/bin`, and make `default_bridge_path()` prefer the packaged asset.
- [x] **Step 3: Add the authoritative batch status boundary**
Expose the batch session to the application layer as the default UI status source. If the bridge is unavailable, show `UNAVAILABLE`; never infer READY from file or icon evidence. Keep the old reader only behind `CBB_STATUS_BRIDGE_MODE=legacy`.
- [x] **Step 4: Run packaging and targeted regression tests**
Run:
```powershell
$env:PYTHONPATH = 'src'
pytest -q tests/test_status_bridge.py tests/test_batch_status.py tests/test_batch_status_faults.py tests/test_packaging_status_bridge.py
```
Expected: PASS; the UI includes a local worker fallback when the optional replacement-tool package is absent.
- [x] **Step 5: Record final artifact and smoke output**
Record the distribution path, bridge SHA-256, benchmark paths, and test summary in `runs/batch-status-implementation-checkpoints.md`.
@@ -0,0 +1,577 @@
# Adaptive Dialog Supervision Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Make CBB Verify discover, classify, and safely handle Mentor dialogs across machines without touching the user's foreground desktop, while preserving authoritative Project Integration and READY validation.
**Architecture:** A private-desktop dialog agent captures Win32 and UI Automation metadata and serves versioned JSONL requests. The parent `DialogSupervisor` applies phase-aware declarative rules, dispatches interface/UIA/Win32 actions in a fixed order, and writes complete evidence before failing an unknown item. Existing PCB COM, dynamic timeout, Job Object cleanup, and status bridge remain authoritative.
**Tech Stack:** Python 3.12, pywin32, pywinauto 0.6.x UIA backend, JSONL IPC, pytest, PyInstaller onedir
**Spec:** `docs/superpowers/specs/2026-09-20-adaptive-dialog-supervision-design.md`
## Global Constraints
- Windows desktop target; Python `>=3.12,<3.13`.
- Do not move the real cursor, inject keyboard input, activate foreground windows, or call `SwitchDesktop`. The only mouse-like fallback allowed is a private-desktop `WM_LBUTTONDOWN/WM_LBUTTONUP` message for the explicitly identified EE7.9.5 license selector HWND.
- Do not use screen coordinates, colors, OCR, timestamps, or dialog disappearance as final success evidence.
- Unknown dialogs are evidence-first failures for the current CBB and never receive a guessed default action.
- A PASS still requires PCB/PRJ identity, four Project Integration `InSynch` values, Validate/Save/IsSaved/Close success, no fatal dialog, and final status bridge `READY`.
- Do not call private Library Manager write exports and do not run concurrent Verify writes against one LMC.
- The project directory is not a Git repository as of 2026-09-20. Do not initialize Git implicitly; each task ends with a test checkpoint instead of a commit.
## File Map
- Create `src/cbb_refresh_verify/dialog_models.py`: immutable phases, control/window snapshots, fingerprints, decisions, and JSON conversion.
- Create `src/cbb_refresh_verify/dialog_rules.py`: schema validation, semantic normalization, rule matching, conflict detection, and packaged rule loading.
- Create `src/cbb_refresh_verify/assets/dialog_rules.v1.json`: default known-dialog rules only.
- Create `src/cbb_refresh_verify/dialog_probe.py`: unrestricted private-desktop Win32 discovery plus UIA enrichment; no policy.
- Create `src/cbb_refresh_verify/dialog_agent.py`: JSONL IPC loop on the private desktop and action-channel execution.
- Modify `src/cbb_refresh_verify/desktop_worker.py`: launch the agent on the same desktop and bind it to the same Job Object.
- Modify `src/cbb_refresh_verify/application.py`: hidden `--dialog-agent` entry point for source and frozen execution.
- Modify `src/cbb_refresh_verify/dialog_supervisor.py`: consume agent snapshots, run rules, verify postconditions, and expose structured outcomes.
- Modify `src/cbb_refresh_verify/verify_runner.py`: maintain phase, synchronize the agent, preserve evidence, and stop only the current item.
- Modify `src/cbb_refresh_verify/mentor_adapter.py`: emit explicit phase events and remove legacy dialog handling from real Verify paths.
- Modify `packaging/CbbRefreshVerify.spec`: package the rule file and UIA dependencies.
- Create `tests/test_dialog_models.py`, `tests/test_dialog_rules.py`, `tests/test_dialog_probe.py`, and `tests/test_dialog_agent.py`.
- Modify `tests/test_dialog_supervisor.py`, `tests/test_verify_runner.py`, `tests/test_safety.py`, and `tests/test_packaging.py`.
---
### Task 1: Stable Window Model and Rule Engine (Complete)
**Files:**
- Create: `src/cbb_refresh_verify/dialog_models.py`
- Create: `src/cbb_refresh_verify/dialog_rules.py`
- Create: `src/cbb_refresh_verify/assets/dialog_rules.v1.json`
- Create: `tests/test_dialog_models.py`
- Create: `tests/test_dialog_rules.py`
**Interfaces:**
- Produces: `DialogPhase`, `ControlSnapshot`, `WindowSnapshot`, `DialogRule`, `RuleDecision`.
- Produces: `normalize_text(value: str) -> str`, `stable_fingerprint(snapshot: WindowSnapshot) -> str`.
- Produces: `load_rules(default_path: Path, override_path: Path | None) -> tuple[DialogRule, ...]`.
- Produces: `decide(snapshot: WindowSnapshot, rules: Sequence[DialogRule]) -> RuleDecision`.
- [x] **Step 1: Write model tests for stable fingerprints**
```python
def test_fingerprint_ignores_handle_pid_paths_and_elapsed_numbers():
first = snapshot(hwnd=10, pid=20, text=r"Elapsed time 11 C:\A\x.pcb")
second = snapshot(hwnd=99, pid=77, text=r"Elapsed time 42 D:\B\y.pcb")
assert stable_fingerprint(first) == stable_fingerprint(second)
def test_fingerprint_changes_for_control_shape():
assert stable_fingerprint(snapshot(control_types=("Button",))) != stable_fingerprint(
snapshot(control_types=("Button", "List")))
```
- [x] **Step 2: Run the model tests and confirm the missing-module failure**
Run: `python -m pytest tests/test_dialog_models.py -q`
Expected: FAIL because `cbb_refresh_verify.dialog_models` does not exist.
- [x] **Step 3: Implement immutable models and normalization**
Define exactly these public fields:
```python
class DialogPhase(str, Enum):
PCB_STARTING = "PCB_STARTING"
LICENSE_ACQUISITION = "LICENSE_ACQUISITION"
DATABASE_RECOVERY = "DATABASE_RECOVERY"
DOCUMENT_ATTACH = "DOCUMENT_ATTACH"
IDENTITY_CHECK = "IDENTITY_CHECK"
PROJECT_INTEGRATION = "PROJECT_INTEGRATION"
VALIDATE = "VALIDATE"
SAVE = "SAVE"
CLOSE = "CLOSE"
POST_VERIFY_STATUS = "POST_VERIFY_STATUS"
@dataclass(frozen=True)
class ControlSnapshot:
handle: int
control_id: int
class_name: str
name: str
automation_id: str = ""
control_type: str = ""
enabled: bool = True
selected: bool = False
checked: bool = False
patterns: tuple[str, ...] = ()
@dataclass(frozen=True)
class WindowSnapshot:
hwnd: int
pid: int
process_name: str
process_role: str
window_class: str
title: str
phase: DialogPhase
controls: tuple[ControlSnapshot, ...]
```
Normalize case, whitespace, elapsed numbers, GUIDs, drive/UNC paths and numeric handles before hashing. Keep original values in `to_record()`.
- [x] **Step 4: Write rule tests for phase, conflict, negative evidence, and override merging**
```python
def test_save_rule_does_not_match_during_license_phase(default_rules):
decision = decide(save_prompt(phase=DialogPhase.LICENSE_ACQUISITION), default_rules)
assert decision.error_code == "DIALOG_OUT_OF_PHASE"
def test_equal_priority_matches_are_rejected():
decision = decide(progress_prompt(), (matching_rule("a", 10), matching_rule("b", 10)))
assert decision.error_code == "DIALOG_RULE_CONFLICT"
def test_override_replaces_rule_by_id(tmp_path, default_path):
override = write_rules(tmp_path, [{"rule_id": "tip-of-day", "enabled": False}])
assert rule_by_id(load_rules(default_path, override), "tip-of-day").enabled is False
```
- [x] **Step 5: Implement strict rule parsing and matching**
Reject unknown schema versions, duplicate rule IDs, missing phases, unknown action channels, and malformed control predicates with `RULE_CONFIG_ERROR`. Merge overrides by `rule_id`; do not permit arbitrary Python expressions or executable commands.
- [x] **Step 6: Add initial packaged rules**
The JSON file must contain phase-scoped rules for `license-selector`, `database-restoration`, `open-lock-confirm`, `reusable-block-save`, `integration-progress`, `integration-error`, `save-error`, `design-server-error`, `database-load-error`, and `tip-of-day`. Each action rule must define a postcondition such as `window_gone`, `control_selected`, or `next_phase`.
- [x] **Step 7: Run the task tests**
Run: `python -m pytest tests/test_dialog_models.py tests/test_dialog_rules.py -q`
Expected: PASS.
- [x] **Step 8: Record the checkpoint**
Record the passing command and changed files in `docs/superpowers/plans/2026-09-20-adaptive-dialog-supervision.md` under a dated execution note. Do not initialize Git.
Execution note 2026-09-20: `python -m pytest tests/test_dialog_models.py tests/test_dialog_rules.py -q` -> `8 passed`.
### Task 2: Complete Win32 and UIA Discovery (Complete)
**Files:**
- Create: `src/cbb_refresh_verify/dialog_probe.py`
- Create: `tests/test_dialog_probe.py`
- Modify: `tests/test_safety.py`
**Interfaces:**
- Consumes: `ControlSnapshot`, `WindowSnapshot`, `DialogPhase`.
- Produces: `WindowProbe.capture(phase: DialogPhase) -> tuple[WindowSnapshot, ...]`.
- Produces: `WindowProbe.capture_one(hwnd: int, phase: DialogPhase) -> WindowSnapshot | None`.
- [x] **Step 1: Write discovery tests**
```python
def test_probe_keeps_visible_non_dialog_classes(fake_windows):
fake_windows.add(hwnd=10, class_name="GXWND", visible=True)
assert [item.window_class for item in make_probe(fake_windows).capture(PHASE)] == ["GXWND"]
def test_disappearing_window_is_skipped_without_hiding_other_windows(fake_windows):
fake_windows.raise_on_title(10)
fake_windows.add(hwnd=20, class_name="#32770", visible=True)
assert [item.hwnd for item in make_probe(fake_windows).capture(PHASE)] == [20]
def test_uia_enrichment_records_patterns(fake_windows, fake_uia):
fake_uia.element(10, automation_id="licenseList", patterns=("SelectionItem",))
control = make_probe(fake_windows, fake_uia).capture(PHASE)[0].controls[0]
assert control.automation_id == "licenseList"
assert control.patterns == ("SelectionItem",)
```
- [x] **Step 2: Run the probe tests and confirm failure**
Run: `python -m pytest tests/test_dialog_probe.py -q`
Expected: FAIL because `WindowProbe` is not implemented.
- [x] **Step 3: Implement class-agnostic Win32 capture**
Enumerate all visible top-level windows from the supplied private desktop. Preserve the current WinError `0/2` empty-desktop behavior, explicitly return `True` from every enumeration callback, and surface other errors as `WINDOW_ENUM_ERROR`. Record process executable name with `OpenProcess/QueryFullProcessImageName`; failure to read a process name must leave it empty rather than discard the window.
- [x] **Step 4: Add bounded UIA enrichment**
Use pywinauto's UIA backend only around already discovered HWND values. Each UIA lookup gets a bounded call wrapper; on timeout or unsupported Pattern, keep the Win32 snapshot and append a probe diagnostic instead of dropping the window. Capture `Invoke`, `SelectionItem`, `Toggle`, `Value`, and `Window` availability.
- [x] **Step 5: Tighten safety tests**
Keep all existing forbidden APIs. Permit UIA wrapper methods `invoke`, `select`, and `toggle`; continue forbidding `click_input`, `type_keys`, `set_focus`, foreground activation, cursor APIs, keyboard APIs, and absolute-coordinate code. The only exception is the explicit private-desktop license-selector `WM_LBUTTONDOWN/WM_LBUTTONUP` fallback, which must remain target-scoped and tested.
- [x] **Step 6: Run tests**
Run: `python -m pytest tests/test_dialog_probe.py tests/test_safety.py -q`
Expected: PASS.
- [x] **Step 7: Record the checkpoint**
Append the passing command and files to the execution note; do not initialize Git.
Execution note 2026-09-20: `python -m pytest tests/test_dialog_probe.py tests/test_dialog_models.py tests/test_dialog_rules.py tests/test_safety.py -q` -> `16 passed`.
### Task 3: Private-Desktop Dialog Agent and JSONL Protocol (Complete)
**Files:**
- Create: `src/cbb_refresh_verify/dialog_agent.py`
- Create: `tests/test_dialog_agent.py`
- Modify: `src/cbb_refresh_verify/desktop_worker.py`
- Modify: `src/cbb_refresh_verify/application.py`
- Modify: `tests/test_application.py`
**Interfaces:**
- Consumes: `WindowProbe` and snapshot JSON conversion.
- Produces: `dialog_agent_main(config_path: Path) -> int`.
- Produces: `DialogAgentClient.start(worker: DesktopWorker, root: Path) -> DialogAgentClient`.
- Produces: `DialogAgentClient.observe(phase: DialogPhase) -> tuple[WindowSnapshot, ...]`.
- Produces: `DialogAgentClient.perform(hwnd: int, fingerprint: str, action: dict) -> ActionResult`.
- [x] **Step 1: Write protocol tests**
```python
def test_agent_correlates_observe_response_by_request_id(tmp_path, fake_probe):
client, server = in_process_protocol(tmp_path, fake_probe)
reply = client.observe(DialogPhase.PCB_STARTING)
assert reply[0].window_class == "GXWND"
assert server.requests[0]["request_id"] == server.responses[0]["request_id"]
def test_agent_rejects_stale_action_fingerprint(tmp_path, changing_probe):
result = agent(tmp_path, changing_probe).perform(10, "old", invoke_action())
assert result.error_code == "STALE_DIALOG"
```
- [x] **Step 2: Run protocol tests and confirm failure**
Run: `python -m pytest tests/test_dialog_agent.py tests/test_application.py -q`
Expected: FAIL for missing agent entry point and protocol classes.
- [x] **Step 3: Implement versioned JSONL envelopes**
Every request contains `schema_version=1`, `request_id`, `op`, `phase`, and `sent_at`. Every response echoes `request_id`, has a monotonic `sequence`, and contains either `result` or structured `error_code/detail`. Parse only complete newline-terminated JSON records and reject mismatched IDs with `DIALOG_PROTOCOL_ERROR`.
- [x] **Step 4: Implement safe actions in the agent**
Support only these declarative operations: `uia_invoke`, `uia_select`, `uia_toggle`, `win32_button_click`, and `observe`. Re-capture the target HWND and compare its stable fingerprint before acting. `win32_button_click` may only target a discovered enabled `Button`; it sends `BM_CLICK` and never cursor input.
- [x] **Step 5: Launch the agent on the same desktop and Job Object**
Add `DesktopWorker.start_companion(command)` using `CreateProcess` with the same `startup.lpDesktop` and `AssignProcessToJobObject`. The agent receives its IPC directory through a config file. Closing or terminating `DesktopWorker` must reap worker, PCB, helper, and agent.
- [x] **Step 6: Add the hidden application route**
Parse `--dialog-agent <config-path>` before Qt creation and call `dialog_agent_main`. Source mode uses `python -m cbb_refresh_verify --dialog-agent ...`; frozen mode uses `CbbRefreshVerify.exe --dialog-agent ...`.
- [x] **Step 7: Run tests**
Run: `python -m pytest tests/test_dialog_agent.py tests/test_application.py -q`
Expected: PASS, including companion cleanup and frozen command construction fakes.
- [x] **Step 8: Record the checkpoint**
Append test evidence to the execution note; do not initialize Git.
Execution note 2026-09-20: `python -m pytest tests/test_dialog_agent.py tests/test_application.py -q` -> `7 passed`.
### Task 4: Phase-Aware Supervisor and Postconditions (Complete)
**Files:**
- Modify: `src/cbb_refresh_verify/dialog_supervisor.py`
- Modify: `tests/test_dialog_supervisor.py`
**Interfaces:**
- Consumes: `DialogAgentClient`, `load_rules`, `decide`, and `DialogPhase`.
- Produces: `DialogSupervisor.poll(phase: DialogPhase) -> DialogPollResult`.
- Produces error codes: `UNKNOWN_DIALOG`, `DIALOG_OUT_OF_PHASE`, `DIALOG_RULE_CONFLICT`, `DIALOG_ACTION_STUCK`, `DIALOG_PROTOCOL_ERROR`.
- [x] **Step 1: Replace text-only classification tests with phase-aware rule tests**
```python
def test_unknown_dialog_fails_without_action(supervisor, backend):
backend.observe_result = (unknown_gxwnd(),)
result = supervisor.poll(DialogPhase.PCB_STARTING)
assert result.error_code == "UNKNOWN_DIALOG"
assert backend.actions == []
def test_sent_action_is_pending_until_postcondition(supervisor, backend):
backend.observe_result = (restore_prompt(selected=False),)
assert supervisor.poll(DialogPhase.DATABASE_RECOVERY).action_sent
backend.observe_result = (restore_prompt(selected=True),)
assert supervisor.poll(DialogPhase.DATABASE_RECOVERY).activity
```
- [x] **Step 2: Run the supervisor tests and confirm failure**
Run: `python -m pytest tests/test_dialog_supervisor.py -q`
Expected: FAIL because the existing supervisor accepts no phase and hardcodes text rules.
- [x] **Step 3: Rebuild supervisor state around rule IDs and postconditions**
Key pending actions by `(fingerprint, rule_id)` rather than HWND alone. Mark resolution only when `window_gone`, `control_selected`, `control_enabled`, `signature_changed`, or `next_phase` is observed. Reused HWND with a new fingerprint is a new window state.
- [x] **Step 4: Preserve fatal-result precedence**
For `FATAL_ACK`, perform the configured acknowledgement only to unblock cleanup, return the rule's fatal error immediately, and never allow later Save/Close events to overwrite it. For `OBSERVE_PROGRESS`, state changes count as activity but the Cancel control is never invoked.
- [x] **Step 5: Run tests**
Run: `python -m pytest tests/test_dialog_supervisor.py -q`
Expected: PASS for standard dialogs, GXWND, progress, fatal, unknown, phase mismatch, rule conflict, delayed initialization, reused handles, and bounded retries.
- [x] **Step 6: Record the checkpoint**
Append test evidence to the execution note; do not initialize Git.
Execution note 2026-09-20: `python -m pytest tests/test_dialog_supervisor.py tests/test_dialog_agent.py tests/test_dialog_rules.py -q` -> `27 passed`.
### Task 5: Verify Runner Integration and Evidence Closure (Complete)
**Files:**
- Modify: `src/cbb_refresh_verify/verify_runner.py`
- Modify: `src/cbb_refresh_verify/mentor_adapter.py`
- Modify: `tests/test_verify_runner.py`
- Modify: `tests/test_integration.py`
**Interfaces:**
- Consumes: `DialogAgentClient`, phase-aware `DialogSupervisor`.
- Produces evidence: `window_snapshots.jsonl`, `dialogs.jsonl`, `process_tree.json`, `events.jsonl`, `worker.log`, `save.log`, `result.json`.
- Preserves: `run_verify(request, ...) -> VerifyResult` and batch skip-on-failure behavior.
- [x] **Step 1: Write integration tests for phase mapping and evidence**
```python
def test_worker_stage_advances_dialog_phase():
assert phase_for_event({"stage": "pcb_launch"}) is DialogPhase.PCB_STARTING
assert phase_for_event({"stage": "integration_status"}) is DialogPhase.PROJECT_INTEGRATION
assert phase_for_event({"stage": "save_start"}) is DialogPhase.SAVE
def test_unknown_dialog_writes_snapshot_before_current_item_fails(tmp_path, fake_worker):
result = run_verify(request(tmp_path), dialog_supervisor_factory=unknown_supervisor)
assert result.status == "FAIL"
assert "UNKNOWN_DIALOG" in result.stderr
assert (result.evidence_path.parent / "window_snapshots.jsonl").is_file()
```
- [x] **Step 2: Run focused integration tests and confirm failure**
Run: `python -m pytest tests/test_verify_runner.py tests/test_integration.py -q`
Expected: FAIL for missing phase mapping and evidence writer behavior.
- [x] **Step 3: Add deterministic worker-stage to dialog-phase mapping**
Map startup and `pcb_started` to `PCB_STARTING`, license evidence to `LICENSE_ACQUISITION`, attach polling to `DOCUMENT_ATTACH`, identity completion to `IDENTITY_CHECK`, integration events to `PROJECT_INTEGRATION`, `save_start/save_helper` to `SAVE`, `saved_and_closed` to `CLOSE`, and authoritative flag reread to `POST_VERIFY_STATUS`. Unknown worker stages retain the last phase and are logged.
- [x] **Step 4: Start and supervise the dialog agent**
Start the companion immediately after `DesktopWorker`, before PCB launch can create a modal. Poll the agent every existing 200 ms loop iteration. Write every new or changed snapshot to `window_snapshots.jsonl`; write decisions/actions/errors to `dialogs.jsonl`.
- [x] **Step 5: Make unknown/fatal handling fail only the current item**
On a dialog error, flush evidence, terminate the job tree, write a FAIL `result.json` with `safe_to_continue=true`, and let `run_batch` proceed. Do not wait for the inactivity timeout once an unknown snapshot has been saved.
- [x] **Step 6: Remove legacy Verify dialog handling**
Delete real Verify calls to `handle_known_dialogs()` and `choose_dialog_action()`. Retain any compatibility functions needed by historical read-only probes under explicit `legacy_` names, add deprecation comments, and assert in tests that `execute_job()` does not reference them.
- [x] **Step 7: Preserve the authoritative PASS gate**
Add regression coverage proving that dialog resolution cannot create PASS, a fatal dialog overrides later save markers, and final status bridge `PENDING/UNKNOWN` converts an otherwise successful run to FAIL.
- [x] **Step 8: Run focused tests**
Run: `python -m pytest tests/test_verify_runner.py tests/test_integration.py tests/test_pcb_bridge.py -q`
Expected: PASS.
- [x] **Step 9: Record the checkpoint**
Append test evidence to the execution note; do not initialize Git.
Execution note 2026-09-20: `python -m pytest tests/test_verify_runner.py tests/test_integration.py tests/test_pcb_bridge.py -q` -> `52 passed`.
### Task 6: License Interface First, UIA Fallback Second (Complete)
**Files:**
- Modify: `src/cbb_refresh_verify/mentor_adapter.py`
- Modify: `src/cbb_refresh_verify/pcb_bridge.py`
- Modify: `src/cbb_refresh_verify/assets/dialog_rules.v1.json`
- Create: `tests/test_automation_license.py`
**Interfaces:**
- Produces: `validate_document(doc, license_factory, emit) -> None`.
- Uses official sequence: `key = doc.Validate(0)`, `token = license_factory().GetToken(key)`, `doc.Validate(token)`.
- Falls back to rule `license-selector` only for known COM unavailability HRESULTs.
- [x] **Step 1: Write official licensing tests**
```python
def test_validate_uses_official_automation_token():
doc = FakeDocument(validate_results=(1234, True))
license_app = FakeLicenseApp(token=5678)
validate_document(doc, lambda: license_app, emit=lambda **event: None)
assert doc.validate_calls == [0, 5678]
assert license_app.keys == [1234]
def test_validation_business_error_does_not_fall_back_to_ui():
with pytest.raises(AutomationLicenseError) as error:
validate_document(BusinessErrorDocument(), factory, emit=noop)
assert error.value.fallback_allowed is False
```
- [x] **Step 2: Run the licensing tests and confirm failure**
Run: `python -m pytest tests/test_automation_license.py -q`
Expected: FAIL because `validate_document` does not implement the official token flow.
- [x] **Step 3: Implement the official token flow**
Create `MGCPCBAutomationLicensing.Application` only after the target document identity is confirmed. Emit `license_key_requested`, `license_token_received` without logging the token value, and `document_validated`. Classify COM registration/server-unavailable errors as fallback-eligible; classify rejected token and document validation errors as fatal.
- [x] **Step 4: Restrict the UIA fallback**
Allow `license-selector` only during `LICENSE_ACQUISITION`, only when the window contains the known selector structure, and only after the COM event explicitly reports fallback eligibility. Require unique selectable license evidence, selected state, enabled OK, and window disappearance.
- [x] **Step 5: Run tests**
Run: `python -m pytest tests/test_automation_license.py tests/test_dialog_rules.py tests/test_dialog_supervisor.py -q`
Expected: PASS.
- [x] **Step 6: Record the checkpoint**
Append test evidence to the execution note; do not initialize Git.
Execution note 2026-09-20: `python -m pytest tests/test_automation_license.py tests/test_dialog_agent.py tests/test_pcb_bridge.py -q` -> `14 passed`.
### Task 7: Packaging, Safety, and Full Automated Regression
**Files:**
- Modify: `packaging/CbbRefreshVerify.spec`
- Modify: `tests/test_packaging.py`
- Modify: `tests/test_safety.py`
- Modify: `tests/test_application.py`
**Interfaces:**
- Packages: `cbb_refresh_verify/assets/dialog_rules.v1.json`, pywinauto UIA backend imports, and dialog-agent modules.
- Preserves executable name: `CbbRefreshVerify-Background/CbbRefreshVerify.exe`.
- [ ] **Step 1: Write packaging assertions**
```python
def test_spec_packages_dialog_rules_and_uia_backend():
text = Path("packaging/CbbRefreshVerify.spec").read_text(encoding="utf-8")
assert "dialog_rules.v1.json" in text
assert "pywinauto" in text
def test_frozen_dialog_agent_route_does_not_create_qt(monkeypatch, tmp_path):
assert application.main(["--dialog-agent", str(agent_config(tmp_path))]) == 0
assert not qt_was_imported()
```
- [ ] **Step 2: Run packaging and safety tests and confirm failure**
Run: `python -m pytest tests/test_packaging.py tests/test_safety.py tests/test_application.py -q`
Expected: FAIL until the spec and hidden route are complete.
- [ ] **Step 3: Update the PyInstaller spec**
Add the JSON rule file to `datas`; add only the pywinauto UIA modules required by the probe to hidden imports. Do not copy test evidence, historical screenshots, data archives, or build directories into the release.
- [ ] **Step 4: Run the entire automated suite**
Run: `python -m pip install -e .`
Run: `python -m pytest -q`
Expected: all tests PASS. The previous subprocess `ModuleNotFoundError: cbb_refresh_verify` must no longer occur after editable installation.
- [ ] **Step 5: Build into a new validation directory**
Run: `powershell -ExecutionPolicy Bypass -File packaging/Build-CbbRefreshVerify.ps1 -OutputDirectory dist-dialog-validation`
Expected: exit code 0, frozen smoke test PASS, and `dist-dialog-validation/CbbRefreshVerify-Background/CbbRefreshVerify.exe` exists. Do not overwrite `dist-optimized` yet.
- [ ] **Step 6: Inspect release contents**
Run: `Get-ChildItem -Recurse -LiteralPath dist-dialog-validation/CbbRefreshVerify-Background | Measure-Object -Property Length -Sum`
Expected: one application directory containing the executable, runtime dependencies, the green-check icon assets, status bridge, save script, and dialog rule file; no `data`, `evidence`, `build`, `.zip`, or `.rar` payloads.
- [ ] **Step 7: Record the checkpoint**
Append the full test count, build path, executable size, and directory size to the execution note; do not initialize Git.
### Task 8: Local Single-CBB Acceptance Before Release
**Files:**
- Runtime output only: `build/acceptance-dialog-<timestamp>/`
- Promote only after PASS: `dist-optimized/CbbRefreshVerify-Background/`
**Interfaces:**
- Uses LMC: `F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\Mentor_lib_EE7.9\mentor_lib.lmc`.
- Uses block: `2GPHY_ZX5201`.
- Uses Mentor root: `D:\Mentor\7.9.5EE\SDD_HOME`.
- [ ] **Step 1: Confirm the pre-run authoritative state and input files**
Run the authoritative read-only status bridge:
```powershell
$env:CBB_STATUS_BRIDGE_ALLOW_PRIVATE = '1'
python -c "from pathlib import Path; from cbb_refresh_verify.status_bridge import StatusBridgeClient; print(StatusBridgeClient().query(Path(r'F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\Mentor_lib_EE7.9\mentor_lib.lmc'), '2GPHY_ZX5201'))"
```
Then require all three inputs:
```powershell
$block = 'F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\Mentor_lib_EE7.9\ReusableBlocksLP\2GPHY_ZX5201\Work'
@(
"$block\2GPHY_ZX5201.prj",
"$block\PCB\2GPHY_ZX5201.pcb",
"$block\PCB\Layout\LayoutDB.lyt"
) | ForEach-Object { if (-not (Test-Path -LiteralPath $_)) { throw "Missing acceptance input: $_" } }
```
Record the pre-run status and paths in the acceptance directory. Do not alter the CBB when prerequisites are missing.
- [ ] **Step 2: Run exactly one CBB from the validation build**
Run:
```powershell
& 'dist-dialog-validation\CbbRefreshVerify-Background\CbbRefreshVerify.exe' `
--batch-lmc 'F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\Mentor_lib_EE7.9\mentor_lib.lmc' `
--block '2GPHY_ZX5201' `
--mentor-bin 'D:\Mentor\7.9.5EE\SDD_HOME'
```
Expected: the foreground desktop does not switch, cursor and keyboard remain untouched, and only one PCB job exists.
- [ ] **Step 3: Inspect the evidence before claiming success**
Require nonempty `events.jsonl`, `window_snapshots.jsonl`, `worker.log`, `save.log`, and `result.json`. `dialogs.jsonl` may be absent only when no dialog appeared; if present, every action must name its `rule_id`, phase, channel, target, and satisfied postcondition.
- [ ] **Step 4: Apply the acceptance gate**
PASS requires the exact target PCB/PRJ identity, all four Project Integration statuses `InSynch`, official validation completion, Save/IsSaved/Close completion, no fatal/unknown/conflict/out-of-phase dialog, process-tree cleanup, and post-run status bridge `READY`. Any missing condition is a failed acceptance, even if the GUI appears green.
- [ ] **Step 5: Test one controlled unknown window only after the normal run**
Use a test fixture window on a disposable private-desktop run, not a production Mentor prompt. Confirm `UNKNOWN_DIALOG`, zero actions, immediate current-item failure, complete snapshot/UIA evidence, and no effect on the foreground desktop.
- [ ] **Step 6: Promote the build only after acceptance**
Preserve the previous `dist-optimized` release as the one retained rollback artifact, copy the accepted validation build into the release location, and remove only superseded project-generated validation builds after verifying their resolved paths remain under the project directory. Never delete user-provided `data.zip`, `data.rar`, logs, or evidence.
- [ ] **Step 7: Record the final checkpoint**
Write the exact executable path, build timestamp, test count, single-CBB result, status-bridge before/after values, and evidence directory into the execution note. Because the directory has no Git metadata, explicitly state that no commit hash exists.
@@ -0,0 +1,243 @@
# CBB Bridge Execution and UNC Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Replace fragile popup/title/timestamp decisions with a confirmed dialog state machine, structured PCB COM execution bridge, authoritative post-Verify status check, and bounded UNC path handling.
**Architecture:** A pure Python dialog state machine decides and confirms popup transitions while a Win32 adapter performs scoped window actions. A separate PCB bridge process owns Expedition COM and emits JSONL events; the parent owns the only inactivity deadline. `LibraryPathLease` maps UNC shares temporarily and supplies a stable Mentor path without recursively fingerprinting the network tree.
**Tech Stack:** Python 3.12, pytest, pywin32, ctypes/WNet, 32-bit Mentor COM/VBScript licensing helper, PyInstaller.
**Spec:** `docs/superpowers/specs/2026-09-20-bridge-execution-and-unc-design.md`
## Global Constraints
- Never inject mouse/keyboard input or switch the user's desktop.
- Never click an unknown dialog automatically.
- Never call private `VerifyReuseBlock` or `UnVerifyReuseBlock` mutation exports.
- A failed CBB is logged and skipped; it does not abort the batch.
- PASS requires a post-close `IsVerifiedReuseBlock == READY` response.
- Temporary network mappings never store credentials or remove user mappings.
---
### Task 1: Confirmed Dialog State Machine
**Files:**
- Create: `src/cbb_refresh_verify/dialog_supervisor.py`
- Modify: `src/cbb_refresh_verify/mentor_adapter.py`
- Test: `tests/test_dialog_supervisor.py`
**Interfaces:**
- Produces: `DialogSnapshot`, `DialogDecision`, `DialogPollResult`, `DialogSupervisor.poll()`.
- Consumes: Win32 observations supplied by an adapter; no Win32 calls in the pure state machine.
- [ ] **Step 1: Write failing tests for popup confirmation and safety**
```python
def test_click_is_not_resolved_until_dialog_disappears():
backend = FakeDialogs([license_dialog(), license_dialog(), []])
supervisor = DialogSupervisor(backend, retry_seconds=0, max_attempts=3)
assert supervisor.poll().action_sent
assert not supervisor.poll().resolved
assert supervisor.poll().resolved
def test_stuck_dialog_fails_after_bounded_retries():
backend = FakeDialogs([license_dialog()] * 4)
supervisor = DialogSupervisor(backend, retry_seconds=0, max_attempts=2)
supervisor.poll(); supervisor.poll()
assert supervisor.poll().error_code == "DIALOG_STUCK"
def test_unknown_dialog_is_recorded_but_not_clicked():
backend = FakeDialogs([[dialog(text="Unrecognized destructive prompt")]])
result = DialogSupervisor(backend).poll()
assert result.error_code == "UNKNOWN_DIALOG"
assert backend.actions == []
def test_save_error_is_fatal_even_with_ok_button():
result = DialogSupervisor(FakeDialogs([[save_error_dialog()]])).poll()
assert result.error_code == "SAVE_REUSABLE_BLOCK_FAILED"
```
- [ ] **Step 2: Run the tests and verify RED**
Run: `python -m pytest -q tests/test_dialog_supervisor.py`
Expected: collection/import failure because `dialog_supervisor` does not exist.
- [ ] **Step 3: Implement the minimal state machine and Win32 adapter**
Implement immutable snapshots with window/PID/control state, fatal classification before generic affirmative classification, pending-action tracking by `(hwnd, signature)`, disappearance confirmation, finite retries, and structured error codes. Win32 enumeration callbacks append observations and explicitly return `True`; the adapter scopes enumeration to the private desktop and supplied process IDs.
- [ ] **Step 4: Integrate compatibility wrapper and verify GREEN**
Keep `handle_known_dialogs()` as a thin compatibility wrapper while `run_verify()` uses the persistent supervisor instance. Run the targeted test plus existing integration tests.
Run: `python -m pytest -q tests/test_dialog_supervisor.py tests/test_integration.py`
Expected: all pass.
### Task 2: PCB COM Execution Bridge and Single Deadline
**Files:**
- Create: `src/cbb_refresh_verify/pcb_bridge.py`
- Modify: `src/cbb_refresh_verify/application.py`
- Modify: `src/cbb_refresh_verify/mentor_adapter.py`
- Modify: `src/cbb_refresh_verify/verify_runner.py`
- Test: `tests/test_pcb_bridge.py`
- Test: `tests/test_verify_runner.py`
**Interfaces:**
- Produces: `PcbBridge.run(job, emit, com_provider, save_runner)` and hidden CLI `--pcb-bridge <request.json>`.
- Consumes: documented `MGCPCB.Application`, `IMGCPCBProjectIntegration`, document save/close APIs, and existing 32-bit licensing helper.
- [ ] **Step 1: Write failing bridge state-machine tests**
```python
def test_bridge_rejects_wrong_document_before_actions():
result = run_bridge(job(), com_provider=wrong_document_provider())
assert result["status"] == "FAIL"
assert result["error_code"] == "PCB_IDENTITY_MISMATCH"
assert no_integration_actions(result)
def test_bridge_runs_required_actions_and_requires_post_save_sync():
provider = staged_provider([required_states(), synchronized_states()])
result = run_bridge(job(), com_provider=provider, save_runner=successful_save)
assert result["status"] == "PASS"
assert provider.actions == ["ForwardAnnotate"]
def test_fatal_dialog_overrides_save_markers():
assert finalize_result(save_markers=SUCCESS_MARKERS,
fatal_dialog="SAVE_REUSABLE_BLOCK_FAILED")["status"] == "FAIL"
```
- [ ] **Step 2: Run targeted tests and verify RED**
Run: `python -m pytest -q tests/test_pcb_bridge.py tests/test_verify_runner.py`
Expected: missing bridge API and missing fatal-result precedence failures.
- [ ] **Step 3: Move COM workflow behind the bridge protocol**
Remove the exact Expedition title gate. The bridge polls COM directly, verifies document/project identity before action, emits only changed snapshots, performs one allowed Required action at a time, validates/saves/closes, and writes a structured outcome. The worker has no independent inactivity deadline.
- [ ] **Step 4: Make the parent the sole deadline owner**
`run_verify()` refreshes its deadline for new bridge events and confirmed dialog transitions. Repeated snapshots do not refresh. Timeout kills the Job Object and returns a safe per-item TIMEOUT.
- [ ] **Step 5: Verify targeted tests GREEN**
Run: `python -m pytest -q tests/test_pcb_bridge.py tests/test_verify_runner.py tests/test_integration.py`
Expected: all pass.
### Task 3: Authoritative Post-Verify Decision
**Files:**
- Modify: `src/cbb_refresh_verify/status_bridge.py`
- Modify: `src/cbb_refresh_verify/verify_runner.py`
- Modify: `src/cbb_refresh_verify/ui/main_window.py`
- Test: `tests/test_status_bridge.py`
- Test: `tests/test_verify_runner.py`
- Test: `tests/test_ui.py`
**Interfaces:**
- Produces: correlated bridge responses containing request ID, block name, resolved LMC path, and source.
- Consumes: existing `StatusBridgeClient/Server` and post-close CBB identity.
- [ ] **Step 1: Write failing correlation and final-state tests**
```python
def test_bridge_rejects_mismatched_response_identity():
with pytest.raises(BridgeResponseError):
parse_bridge_response(response_for("OTHER"), expected_block="TARGET")
def test_save_success_with_pending_post_status_is_fail():
result = finalize_verify(execution_pass(), BridgeResult("PENDING", "IsVerifiedReuseBlock"))
assert result.status == "FAIL"
```
- [ ] **Step 2: Verify RED, implement correlation and post-check, verify GREEN**
Run RED then GREEN: `python -m pytest -q tests/test_status_bridge.py tests/test_verify_runner.py tests/test_ui.py`
The UI marks a row Ready only after the final bridge response is READY. A bridge error remains visible and selectable for a later retry; it is never promoted from Cert files.
### Task 4: UNC Path Lease and Bounded Network Scan
**Files:**
- Create: `src/cbb_refresh_verify/network_path.py`
- Modify: `src/cbb_refresh_verify/batch_status.py`
- Modify: `src/cbb_refresh_verify/library_reader.py`
- Modify: `src/cbb_refresh_verify/ui/main_window.py`
- Test: `tests/test_network_path.py`
- Test: `tests/test_batch_status.py`
- Test: `tests/test_library_reader.py`
**Interfaces:**
- Produces: `LibraryPathLease.acquire(path)`, `.mentor_path`, `.display_path`, `.close()`.
- Consumes: injected WNet backend in tests and Windows WNet API in production.
- [ ] **Step 1: Write failing lease and no-recursion tests**
```python
def test_unc_uses_existing_mapping_without_releasing_it():
backend = FakeWNet(existing={"Y:": r"\\server\share"})
with LibraryPathLease.acquire(r"\\server\share\lib\mentor_lib.lmc", backend=backend) as lease:
assert lease.mentor_path == Path(r"Y:\lib\mentor_lib.lmc")
assert backend.cancelled == []
def test_created_mapping_is_released():
backend = FakeWNet()
lease = LibraryPathLease.acquire(r"\\server\share\lib\mentor_lib.lmc", backend=backend)
lease.close()
assert backend.cancelled == [lease.drive]
def test_fingerprint_does_not_walk_cbb_descendants(tmp_path, monkeypatch):
# A descendant scandir raises; the lightweight snapshot must still finish.
assert fingerprint_library(make_library(tmp_path)).sha256
```
- [ ] **Step 2: Verify RED, implement lease and lightweight fingerprint, verify GREEN**
Replace recursive `_fingerprint_tree()` with LMC metadata plus sorted top-level CBB names and top-level metadata. Pass the leased `mentor_path` consistently to listing, bridge status, preflight and Verify.
Run: `python -m pytest -q tests/test_network_path.py tests/test_batch_status.py tests/test_library_reader.py tests/test_ui.py`
Expected: all pass and no descendant traversal.
### Task 5: Packaging, Regression, and Static Safety Verification
**Files:**
- Modify: `packaging/CbbRefreshVerify.spec`
- Modify: `README.md`
- Modify: `tools/status_bridge/README.md`
- Test: `tests/test_packaging.py`
- Test: `tests/test_packaging_status_bridge.py`
- Test: `tests/test_safety.py`
**Interfaces:**
- Consumes: all new modules and bridge entry points.
- Produces: one updated `dist-optimized/CbbRefreshVerify-Background` and archive.
- [ ] **Step 1: Add packaging and safety tests, verify RED**
Assert the frozen app contains the status bridge, PCB bridge entry point, VBS helper and icon; assert production source has no fixed Expedition title gate and no callback whose return value is `list.append()`.
- [ ] **Step 2: Update packaging and documentation, verify GREEN**
Run: `python -m pytest -q`
Expected: complete suite passes with zero failures.
- [ ] **Step 3: Build and smoke-test without running Mentor Verify**
Run: `powershell -ExecutionPolicy Bypass -File packaging/Build-CbbRefreshVerify.ps1 -OutputDirectory dist-optimized`
Run: `dist-optimized/CbbRefreshVerify-Background/CbbRefreshVerify.exe --smoke-test`
Expected: build exit 0, smoke exit 0, no Mentor/PCB process started.
- [ ] **Step 4: Retain only the latest package and report limitations**
Keep the latest application directory, archive, and user-supplied diagnostic archives/logs. Do not delete user evidence. Report that real Mentor validation remains a one-CBB acceptance step on the work machine.
@@ -0,0 +1,43 @@
# CBB Verify 系统审计与原生触发修复计划
> 适用于当前 `dist-repaired-20260922-win10-native-menu-fallback-r1` 现场数据。
## 已确认的根因
现场 `events.jsonl` 依次出现 `verify_invoke`、`verify_invoke_returned` 和 `verify_menu_fallback`,但没有任何 `pcb_launch` 或 `pcb_worker_started`。`post_verify_observations.jsonl` 显示 UIA 调用后原生 `#32768` 菜单仍存在,坐标消息后菜单消失,进程列表始终只有 `LibraryManager.exe`。因此当前失败点是 LMC 原生 MFC 菜单命令没有进入 LMC 的命令路由。此前旧数据中的 `pcb_launch` 来自直接启动 `common\\ExpeditionPCB.exe`,不能作为 LMC Verify 成功证据。
## 目标链路
```text
定位唯一 CBB
-> 打开该节点原生菜单
-> UIA InvokePattern
-> 若菜单仍在:私有 popup 坐标消息兜底(仅关闭菜单,不等同于成功)
-> 观察菜单消失 + 新的 ReusableCircuit PCB
-> 绑定 PCB COM
-> Project Integration
-> 保存/关闭
-> 状态桥复核 IsVerifiedReuseBlock
```
## 修改边界
1. `WM_COMMAND` 曾作为实验路径,但已由 `API-FINDINGS.md` 的 Win32 实测否定:广播无效,`SendMessage` 还可能阻塞 LMC 线程;它只保留在历史记录,不进入生产代码。
2. UIA Verify 调用没有启动迹象且菜单仍可见时,只允许向该私有 popup 投递相对坐标消息;菜单消失本身不再视为 Verify 成功。
3. `post_verify_diagnostics.py` 和 `verify_runner.py` 记录 `verify_invoke`、`verify_invoke_returned`、`pcb_worker_started`,必须观察到新的 PCB 后才能进入 COM 链路。
4. LMC 阶段持续观察属于本次私有桌面的模态框;未知窗口原样记录,已知安全确认框才自动处理。
5. PCB 绑定只在出现新的、命令行包含目标 `.pcb` 与 `-ReusableCircuit` 的进程后进行,防止绑定残留 PCB。
6. 备份继续作为旁路证据,网络盘超时不能阻塞 Verify;备份失败不能改变 Verify 触发状态。
7. worker 被外层超时/弹窗错误终止后,由 supervisor 根据本次 CBB 的命令行和基线 PID 再做一次定向清理,避免 `common/wg/LibraryManager` 孤儿化。
## 验收门槛
- 离线回归测试覆盖 `RECT`、命令 ID、菜单状态和重复触发保护。
- 全量 Python 测试通过,冻结包 smoke test 通过。
- Win10 现场单项测试必须出现:
`verify_command_posted` → `verify_dispatch_result=menu_closed` → `pcb_start_observed` → `integration_status` → `saved_and_closed` → `complete`
- 若命令发送后菜单消失但没有 PCB,结果必须明确为 `VERIFY_DISPATCH_FAILED`,不再笼统报告 60 秒超时。
- 无论 PASS、FAIL 还是 TIMEOUT,`events.jsonl` 都必须出现 `source=supervisor_cleanup` 的 `process_cleanup` 记录;现场复测后进程列表中不得留下本次目标 PCB/LMC。
- 未通过单项现场验收前,不启用批量或并发。
@@ -0,0 +1,97 @@
# Native CBB Verify Probe Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task with verification checkpoints.
**Goal:** Determine whether the EE7.9 native `CLibServer::VerifyRCCells(int)` path can verify one CBB safely on an isolated `.lmc` copy and persist a `READY` state.
**Architecture:** Keep production Python/UI code unchanged. Use static analysis to recover the caller sequence and ABI, then build a separate x86 C++ probe with Mentor's runtime DLLs. The probe will operate only on a copied library, emit JSONL evidence, and be accepted only when the existing read-only status bridge reports `READY` after the probe process exits.
**Tech Stack:** Windows PowerShell, MSVC x86, `LibManagerDBPI.dll`, `LMCDLL70.dll`, existing `CbbStatusBridge32.exe`, `objdump`/`dumpbin`, JSONL evidence.
**Spec:** `docs/superpowers/specs/2026-09-20-bridge-execution-and-unc-design.md`
## Global Constraints
- Never call write exports against the production center library.
- Use `diagnostics/Mentor_lib_EE7.9-clean` or a newly-created copy as the only write target.
- Do not use physical mouse, keyboard injection, `SendInput`, or foreground switching.
- Do not claim success unless the post-exit status bridge returns `READY` for the same CBB and `.lmc`.
- Preserve raw return codes, DLL paths, process architecture, and before/after status in JSONL.
---
### Task 1: Establish a clean isolated fixture and baseline
**Files:**
- Create: `diagnostics/native-verify-probe-20260925/README.md`
- Create: `diagnostics/native-verify-probe-20260925/baseline.json`
**Interfaces:**
- Consumes: the existing clean EE7.9 center-library copy and `CbbStatusBridge32.exe`.
- Produces: an immutable fixture path, target CBB identity, and a recorded pre-probe status.
- [ ] **Step 1: Resolve the clean fixture and target CBB without opening production files.**
- [ ] **Step 2: Run the existing status bridge in read-only mode for exactly one target.**
- [ ] **Step 3: Record the response, file hashes, and process/DLL architecture in `baseline.json`.**
- [ ] **Step 4: Stop if the target is already `READY` or if the fixture identity cannot be proven.**
### Task 2: Recover the native call sequence
**Files:**
- Create: `diagnostics/native-verify-probe-20260925/static-analysis.md`
- Create: `diagnostics/native-verify-probe-20260925/call-sites.txt`
**Interfaces:**
- Consumes: `LibManagerDBPI.dll`, Mentor executables/DLLs, and existing exported-symbol records.
- Produces: disassembly evidence for constructor, `Load`, `Init`, `SetVerifyRCCellsFlag`, `VerifyRCCells`, `Save`, and `Close` call sites.
- [ ] **Step 1: Enumerate x86 exports and decorated names with `objdump` or `dumpbin`.**
- [ ] **Step 2: Search Mentor binaries for references to the decorated `VerifyRCCells` symbol and nearby string/resource references.**
- [ ] **Step 3: Disassemble each caller and record register/stack argument setup and return-code checks.**
- [ ] **Step 4: Identify whether the caller opens a partition, sets a flag, saves, or requires an application context.**
### Task 3: Build a read-only ABI sanity probe
**Files:**
- Create: `tools/native_verify_probe/NativeVerifyProbe32.cpp`
- Create: `tools/native_verify_probe/CMakeLists.txt`
- Create: `tools/native_verify_probe/README.md`
**Interfaces:**
- Consumes: the recovered constructor/load signatures and a fixture `.lmc` path.
- Produces: JSONL describing object creation, load/init results, and no-write dry-run checks.
- [ ] **Step 1: Write a probe that loads Mentor DLLs but does not call Verify/Save.**
- [ ] **Step 2: Compile it as Win32 with the available MSVC toolchain.**
- [ ] **Step 3: Run it against the fixture and verify clean process exit with no production file changes.**
### Task 4: Run one isolated native verify experiment
**Files:**
- Create: `diagnostics/native-verify-probe-20260925/experiment.jsonl`
- Modify: `tools/native_verify_probe/NativeVerifyProbe32.cpp` only if Task 3 and static evidence agree.
**Interfaces:**
- Consumes: one isolated fixture and one target CBB.
- Produces: a single experiment record with before status, call sequence, return codes, save result, process exit, and after status.
- [ ] **Step 1: Add an explicit `--write-isolated-copy` guard; refuse any path outside the fixture directory.**
- [ ] **Step 2: Execute only one parameter combination inferred from static evidence.**
- [ ] **Step 3: Save/close the isolated library and allow the probe process to exit naturally.**
- [ ] **Step 4: Re-read the target using `CbbStatusBridge32.exe` after process exit.**
- [ ] **Step 5: Classify the result as `READY`, `PENDING`, `ERROR`, or `ABI_UNSAFE`; do not retry with guessed parameters.**
### Task 5: Document the decision and keep production unchanged
**Files:**
- Create: `diagnostics/native-verify-probe-20260925/conclusion.md`
- Modify: `API-FINDINGS.md` only with evidence-backed results.
**Interfaces:**
- Consumes: static-analysis and experiment JSONL.
- Produces: a go/no-go decision for production integration.
- [ ] **Step 1: Require a post-exit `READY` status before calling the native path viable.**
- [ ] **Step 2: If viable, document exact ABI and guard requirements without wiring production yet.**
- [ ] **Step 3: If not viable, document the blocking evidence and retain the existing safe status-only bridge.**
- [ ] **Step 4: Run repository tests that do not launch Mentor and verify no production source changes were introduced.**
@@ -0,0 +1,120 @@
# CBB Refresh Verify Design
**Date:** 2026-09-16
**Status:** Approved for planning
## Goal
Deliver an independent Windows desktop tool that loads a Mentor central library, lists its uploaded Logical-Physical CBB reusable blocks, invokes the official contents verification command, and produces an auditable result without confusing contents PASS with Library Manager's final green state.
## Scope
In scope:
- Select and open a `.lmc` central library.
- Read and list CBBs from the Reusable Blocks / Logical-Physical partition.
- Accept the required `LibSpec` and DMS login configuration paths.
- Run `ReuseBlockImporter.exe -chkContents` for a selected CBB.
- Display live output, exit code, timeout/stop state, report path, and JSON evidence.
- Package and release an onedir executable using the established DxDesigner replacement-tool standard.
Out of scope:
- Part replacement.
- PCB synchronization.
- Uploading CBBs to the central library.
- Simulating or fabricating DMS connectivity.
- Claiming Library Manager's green indicator from a contents-check PASS alone.
## Reuse From DxDesigner Replacement Tool
The project will follow the existing replacement tool's conventions instead of reimplementing equivalent infrastructure:
- Python 3.12 project metadata and setuptools layout.
- PySide6 application bootstrap and an onedir PyInstaller distribution.
- `Analysis -> PYZ -> EXE -> COLLECT` packaging structure.
- A `packaging` PowerShell build script that resolves the project interpreter, cleans only verified project-local build targets, invokes PyInstaller, and validates the produced executable.
- Application data/log root resolution, startup/clean-shutdown logging, exception hook installation, and hidden smoke-test arguments, adapted to the CBB product name.
- UI worker/thread patterns for long-running operations and cancellation.
The replacement tool's part-replacement domain state machine, project scanner, native replacement scripts, and database schema are not copied because they do not apply to CBB verification.
## Architecture
### Application Bootstrap
`cbb_refresh_verify.application` owns command-line parsing, data-root resolution, logging setup, Qt application creation, exception hooks, smoke-test shutdown, and construction of the main window. `__main__.py` calls the absolute package import `cbb_refresh_verify.application.main` so it works both from source and as a frozen PyInstaller script.
### Library Reader
`library_reader.py` exposes a Qt-free function that receives a `.lmc` path and returns typed CBB records. On Windows it uses `win32com.client.Dispatch("LibraryManager.Application")`, opens the library, selects partition type 7 (Reusable Blocks), and enumerates Logical-Physical entries. COM failures are returned as structured errors and are visible in the UI; they are never silently converted into an empty list.
The reader is isolated behind an interface so fixture data and a fake reader can be used in tests without opening production libraries.
### Verify Runner
`verify_runner.py` exposes a Qt-free runner that validates required paths, resolves `ReuseBlockImporter.exe` from the configured Mentor bin or known installation fallback, builds the exact official argument list, and executes it in a cancellable worker process. stdout and stderr are captured separately. The runner writes a text report and JSON evidence containing command, inputs, timestamps, exit code, output, and classified result.
Classification rules:
- `PASS`: process completed and official success text is present without an error marker.
- `FAIL`: process completed with a verification failure or non-zero exit code.
- `TIMEOUT`: configured timeout elapsed.
- `BLOCKED`: prerequisite such as missing executable, missing DMS configuration, or unavailable environment prevents a meaningful attempt.
- `UNKNOWN`: process ended but output cannot be classified safely.
No result class is mapped to Library Manager's green indicator. The UI reports that final state separately as `not-read / manual-confirmation-required`.
### UI
The main window contains:
- central-library path with browse action;
- read-only CBB table or combo populated after library load;
- required `LibSpec` and DMS login configuration fields;
- optional Mentor bin and evidence-directory fields with defaults;
- Verify and Stop actions;
- status indicator, live output panel, final classification, and evidence/report links.
Loading a library and running Verify happen off the GUI thread. Verify is disabled until a library, CBB, LibSpec, and DMS configuration are present. Empty libraries and reader errors are explicit states.
### Evidence and Data
Application logs live below the same product-specific data root pattern used by the replacement tool. Each run receives a unique evidence directory or timestamped report, and evidence is never read back as a substitute for live command output. Existing historical screenshots and run JSON files are not inputs to runtime classification.
## Error Handling
- Invalid or missing `.lmc`, `LibSpec`, DMS config, or executable: `BLOCKED` with an actionable message.
- COM initialization/open/enumeration errors: visible reader error with exception text and no CBB selection.
- Process launch errors: `BLOCKED` with resolved executable and working-directory details.
- Timeout: terminate the child process, preserve partial output, classify `TIMEOUT`.
- User stop: terminate the child process and classify `UNKNOWN` unless the runner has a definitive failure code.
- Unexpected exceptions: log full traceback and present a concise UI error.
## Testing and Acceptance
Unit tests cover:
- CBB record conversion and partition filtering;
- COM reader success, empty library, and COM exception paths using fakes;
- exact command construction;
- PASS/FAIL/UNKNOWN classification from representative output;
- missing prerequisite, timeout, stop, and evidence writing.
Packaging acceptance requires:
1. The build script exits with code 0.
2. `dist\\CbbRefreshVerify\\CbbRefreshVerify.exe` exists.
3. The frozen executable accepts `--smoke-test --data-root <temp>` and exits 0.
4. Smoke logs contain startup and clean-shutdown events.
5. A fixture `.lmc` can be loaded through the reader test seam without modifying the production central library.
Real DMS verification is an environment-dependent acceptance step for the user's work machine. On a machine without DMS, the correct observed result is `BLOCKED` or `UNKNOWN`, never a fabricated PASS.
## Constraints
- Windows desktop target.
- Python `>=3.12,<3.13`.
- Dependencies remain limited to PySide6 and pywin32 plus the existing build/test tools.
- No fixed-coordinate UI automation, SendKeys, or production-library writes.
- Output is independent from `dxdesigner-part-replacement` and does not modify that project.
@@ -0,0 +1,74 @@
# CBB 批量状态桥设计
## 目标
支持对 180 到 3000 个 CBB 进行 Mentor authoritative Verify 状态读取,要求单条失败隔离、过程可恢复、结果可审计,并避免现有“一条 CBB 启动一个桥进程”的启动开销。
本阶段只读取 `IsVerifiedReuseBlock` 返回的 `READY/PENDING`,不触发 Verify、Unverify,也不修改中心库。
## 范围与约束
- 目标平台为 Windows x86 Mentor EE 7.9/7.9.5 环境。
- `RULP/LP` 映射为 `eReuseBlockType = 0`。
- Mentor 私有 DLL 按非线程安全处理;同一个 LMC 默认只有一个活动桥会话。
- `UNKNOWN`、桥异常、超时和非法响应都不能转换成 `READY`。
- LMC 或其 ReusableBlocks 内容变化后,旧缓存必须失效。
## 架构
### 常驻 JSONL 桥
`CbbStatusBridge32.exe --server` 启动后加载一次 `LMCDLL70.dll`,从标准输入逐行读取 JSON 请求,并为每行输出一行 JSON 响应。请求包含 `op`、`lmc_file`、`block_name` 和 `block_type`;响应包含 `status`、`source`、`raw_status`、耗时和错误信息。
桥内部串行处理请求,不创建线程池,不主动卸载 Mentor DLL。进程退出时由操作系统回收 DLL,避免 Mentor 模块级析构导致堆异常。
### Python 批量客户端
新增批量会话客户端,负责:
1. 启动桥并记录 PID、桥版本和 DLL 路径;
2. 逐条写入请求并读取对应响应;
3. 对每条请求设置超时,超时后终止桥并重启;
4. 每 300 到 500 条主动轮换桥进程;
5. 将每条结果立即追加到 JSONL 检查点日志;
6. 重启后跳过已有成功检查点,继续未完成条目。
### 缓存与失效
扫描开始时计算 LMC 文件的大小、修改时间和 SHA-256,并记录 ReusableBlocksLP 根目录的目录指纹。缓存键为:中心库指纹、CBB 名称、类型。单次扫描内相同键直接复用结果;Verify 成功后删除对应 CBB 缓存并重新读取。任一指纹变化则废弃本批缓存。
## 并发策略
第一版只实现单桥串行批处理。原因是 Mentor 私有 MFC 状态接口和 LMC 文件锁尚未证明可并发访问。
代码保留 worker 数配置,但默认值为 1;只有完成两个独立桥进程读取同一 LMC 的稳定性、状态一致性和锁冲突测试后,才开放 worker 大于 1。并发测试失败时必须自动回退到 1,而不是把异常结果标成 READY。
## 错误处理
- 单条返回 `PENDING` 是有效结果,继续下一条。
- 单条超时、非零退出码、非法 JSON、桥崩溃记录为 `ERROR/TIMEOUT/UNAVAILABLE`,继续下一条。
- 桥连续崩溃达到阈值时停止本批并弹窗,保留已完成检查点。
- 任何状态来源不是 `IsVerifiedReuseBlock` 时,不更新 UI 的 authoritative 状态。
## 日志格式
每条记录至少包含:`timestamp`、`scan_id`、`lmc_file`、`lmc_fingerprint`、`block_name`、`block_type`、`status`、`source`、`raw_status`、`elapsed_ms`、`bridge_pid`、`exit_code`、`error`。
日志采用追加写入和 UTF-8 JSONL;程序启动时扫描最后一个完整 JSON 行,忽略截断行并从未完成条目继续。
## 验收指标
- 180 条连续扫描无桥泄漏、无错误状态升级,失败条目不阻塞后续条目。
- 3000 条模拟批处理可中断并恢复,恢复不重复已完成条目。
- 常驻桥的平均单条耗时和每 500 条轮换耗时有统计输出。
- 在已知样本中,`1GPHY_8212/2GPHY_ZX5201` 返回 READY,`1GPHY_8211/IP101GR/PEF7071_PHY` 返回 PENDING。
- 核心 Python 测试、桥协议测试和批处理故障注入测试全部通过。
- 不执行真实 Verify/Unverify,不修改生产中心库。
## 不在本阶段
- 批处理验收完成后,主 UI 默认使用状态桥的 Ready/Pending 判定;旧证据链仅通过
`CBB_STATUS_BRIDGE_MODE=legacy` 显式启用。
- 不实现 2 到 10 并发窗口。
- 不通过鼠标、键盘、坐标或图标颜色触发或判断 Verify。
- 不把 Docker 作为 Mentor DLL 的运行环境。
@@ -0,0 +1,233 @@
# CBB 自适应弹窗监督设计
**日期:** 2026-09-20
**状态:** 已确认方向,待实施计划
## 目标
为 CBB 批量 Verify 建立一套可跨 Mentor EE 7.9/7.9.5、不同 Windows 主题、语言和现场机器使用的弹窗监督机制。该机制必须在后台私有桌面运行,不移动用户鼠标、不发送真实键盘输入、不切换前台桌面;已知安全弹窗自动处理,进度弹窗持续观察,致命弹窗立即记录并跳过当前 CBB,完全未知的弹窗保留完整证据后跳过当前 CBB。
本设计扩展 `2026-09-20-bridge-execution-and-unc-design.md`,不替换其中已经确认的中心库状态桥、PCB COM 执行桥、UNC 路径租约和结果判定规则。
## 当前问题
现有实现有以下结构性限制:
- `dialog_supervisor.py` 只接受窗口类名为 `#32770` 的标准对话框,无法完整发现 `GXWND`、TaskDialog 和 Mentor 自绘窗口。
- 动作主要依赖按钮文案和 `BM_CLICK`,对于自绘列表、延迟初始化控件以及需要 UI Automation Selection/Invoke 的窗口无效。
- `dialog_supervisor.py` 与 `mentor_adapter.handle_known_dialogs()` 各自维护一套分类和点击逻辑,可能对同一弹窗作出不同决定。
- 规则缺少明确的执行阶段约束。同名的 OK、Yes 或 Continue 在启动、恢复、保存和错误阶段具有不同含义。
- 未识别的非标准窗口可能完全不进入证据日志,最终只表现为超时。
## 设计原则
1. Mentor/PCB 官方接口优先于界面自动化。
2. UI Automation 模式优先于 Win32 控件消息。
3. 不以坐标、颜色、窗口句柄或固定 PID 作为稳定身份。
4. 不对未知弹窗执行猜测性确认。
5. 弹窗消失只表示动作已响应,不表示 Verify 成功。
6. 每个动作必须受执行阶段、窗口指纹和后置条件共同约束。
7. 新现场弹窗通过数据化规则适配,不在主程序中继续堆叠分支。
## 总体架构
### 1. 单一监督入口
保留 `DialogSupervisor` 作为父进程唯一入口,删除生产流程对 `mentor_adapter.handle_known_dialogs()` 和 `choose_dialog_action()` 的调用。兼容函数可以短期保留给旧测试,但不得再参与真实 Verify。
监督入口接收:
- 当前 Job Object 的进程树;
- 当前私有桌面句柄;
- PCB 执行状态机阶段;
- 当前目标 CBB、PCB 和 PRJ 身份;
- 默认规则包与可选的现场规则包。
它输出统一的 `DialogEvent`,不直接决定最终 Verify 结果。
### 2. 私有桌面观察代理
新增一个随校验 worker 启动、位于同一私有桌面的观察代理。父进程继续负责超时和结果裁决,观察代理负责窗口发现和控件操作,二者通过带 `request_id` 和单调序号的 JSONL 通道通信。
将观察代理放在私有桌面内部,避免 UI Automation 从输入桌面跨桌面访问时出现元素不可见、COM apartment 不一致或句柄可枚举但 Pattern 不可调用的问题。
观察代理按两层采集窗口:
- Win32 层:所有可见顶层窗口,不限制 `#32770`,记录 HWND、PID、进程程序名、窗口类、标题、owner、父子窗口及控件 ID。
- UI Automation 层:记录 AutomationId、ControlType、Name、IsEnabled,以及 Invoke、SelectionItem、Toggle、Value、Window 等可用 Pattern。
私有桌面本身是隔离边界。代理仍记录进程树归属,但不会因为许可证或设计服务器使用辅助 PID 而漏掉窗口。用户输入桌面的窗口永远不在观察范围内。
### 3. 规范化窗口模型与动态指纹
所有观察结果先转换为 `WindowSnapshot`:
- `stage`
- `process_name`、`process_role`
- `window_class`、`title`
- 标准化后的可见文本集合
- 控件树结构摘要
- 控件 ID、AutomationId、ControlType 和可用 Pattern
- enabled、selected、checked、visible 状态
窗口指纹由稳定字段组合得到:
`stage + process_role + window_class + normalized semantics + control-shape`
动态 HWND、PID、坐标、主题色、控件创建顺序和文本中的路径/耗时数字只写入证据,不进入稳定指纹。中英文同义词经过语义标签归一化,例如 `恢复数据库/Restore Database` 都映射为 `RESTORE_DATABASE`。
### 4. 数据化规则引擎
默认规则以版本化 JSON 文件发布,用户现场规则放在数据目录,两者都只允许声明式匹配和预定义动作,禁止执行任意脚本。规则包括:
- `rule_id`、`schema_version`、适用 Mentor 版本;
- 允许的执行阶段;
- 进程角色、窗口类和控件结构条件;
- 必须存在和必须不存在的语义证据;
- 动作类型、目标控件条件和后置条件;
- 重试次数、退避时间和失败分类。
同一窗口可以匹配多个证据,但只有唯一最高优先级规则满足全部条件时才执行。规则冲突返回 `DIALOG_RULE_CONFLICT`,不得任选一条。
规则分类:
- `OBSERVE_PROGRESS`:只观察状态变化,不点击 Cancel,并刷新活动超时。
- `SAFE_RECOVERY`:数据库恢复、许可证选择、打开锁确认等可恢复动作。
- `SAFE_CONFIRM`:保存 Reusable Block 等与当前阶段一致的确认动作。
- `FATAL_ACK`:保存失败、设计服务器失败、Project Integration 错误;允许关闭提示以便清理,但当前项结果锁定为 FAIL。
- `UNKNOWN`:不执行动作,保存现场后结束当前项。
### 5. 分层动作适配器
每条规则声明允许使用的动作通道,按以下顺序尝试:
1. 已确认的 Mentor/PCB COM 或桥接接口;
2. UI Automation `InvokePattern`;
3. UI Automation `SelectionItemPattern`、`TogglePattern` 或 `ValuePattern`;
4. 标准 Win32 `WM_COMMAND` 或 `BM_CLICK`;
5. 默认禁用的窗口内相对点击。
窗口消息降级仅能在后续明确验证某个自绘控件没有任何接口、UIA Pattern 或标准控件消息可用时,为单独规则显式开启;当前仅允许 EE7.9.5 许可证选择器规则使用 `WM_LBUTTONDOWN/WM_LBUTTONUP` 目标句柄消息。它仍不得移动真实鼠标或注入真实键盘。屏幕绝对坐标永远禁用。
动作发出后必须满足规则定义的后置条件,例如:
- 目标控件变为 selected;
- OK 从 disabled 变为 enabled;
- 当前窗口消失;
- 下一阶段窗口出现;
- PCB COM/执行桥返回对应状态变化。
未满足后置条件时不记录为已处理,而是在有限次数内重试;达到上限返回 `DIALOG_ACTION_STUCK`。
### 6. 阶段状态机
父进程维护以下阶段:
1. `PCB_STARTING`
2. `LICENSE_ACQUISITION`
3. `DATABASE_RECOVERY`
4. `DOCUMENT_ATTACH`
5. `IDENTITY_CHECK`
6. `PROJECT_INTEGRATION`
7. `VALIDATE`
8. `SAVE`
9. `CLOSE`
10. `POST_VERIFY_STATUS`
阶段由 PCB 执行桥事件推进,不能仅靠窗口标题推进。规则只在声明的阶段生效。例如恢复选择只能出现在启动或文档附加前,保存确认只能出现在 `SAVE/CLOSE`,Project Integration 进度窗口只能在 `PROJECT_INTEGRATION` 被当作正常活动。
阶段不匹配的已知弹窗按 `DIALOG_OUT_OF_PHASE` 留证并失败,防止残留窗口被误确认。
### 7. 未知弹窗证据包
发现未知、冲突、阶段错误或无法操作的窗口时,当前项立即生成结构化证据:
- `window_snapshot.json`
- `uia_tree.json`
- `dialogs.jsonl`
- `events.jsonl`
- `process_tree.json`
- 当前阶段、目标 CBB/PCB/PRJ 和已匹配规则候选
- 仅截取私有桌面中该窗口的诊断截图(如果系统允许)
截图只为未知窗口诊断生成,不参与自动判定,也不批量截取正常流程。证据写入采用追加和原子落盘;证据失败不能遮蔽原始错误码。
现场确认该窗口的安全动作后,可新增一条现场 JSON 规则。规则先在 `observe_only` 模式验证指纹命中和目标唯一性,再允许执行动作。程序不根据一次人工选择自动学习,避免错误行为被永久固化。
### 8. 超时与恢复
沿用父进程唯一的动态 inactivity deadline:
- 新窗口、控件状态变化、桥阶段变化和动作后置条件满足都属于活动;
- 重复的相同窗口快照和重复投递动作不刷新超时;
- 未知弹窗无需等待 30 秒,证据保存完成后立即结束当前项;
- 正常 Project Integration 状态持续变化时不会误触发超时;
- 总时长上限仍然存在,避免异常窗口不断变化导致永不结束。
当前项结束时通过 Job Object 回收观察代理、PCB、执行桥和辅助进程。清理失败写入 `cleanup_error`,但不阻塞队列中的下一项。
## 已知弹窗首批规则
第一版至少覆盖:
- EE7.9/7.9.5 产品许可证选择;
- Database Restoration 与 Last User Saved Database;
- 设计正在被其他用户打开时的读写确认;
- Reusable Block 保存确认;
- Project Integration 正常进度窗口;
- Project Integration 错误汇总;
- Error saving the Reusable Block;
- Could not run server / Could not bring it alive;
- Database load is being terminated;
- Tip of the Day。
许可证规则优先尝试 Automation Licensing COM。只有 COM 取 token 不可用且 UIA 能确认唯一许可证项、选中状态和 OK 可用状态时,才走 UIA 界面通道。
## 最终结果判定
弹窗监督器只能产生过程事件或失败锁,不能单独产生 PASS。Verify PASS 仍必须满足既有五项条件:
1. PCB/PRJ 身份一致;
2. 四项 Project Integration 均为 `InSynch`;
3. Validate、Save、IsSaved 和 Close 成功;
4. 本次没有 fatal、unknown、规则冲突或阶段错误;
5. PCB 退出后状态桥返回该 CBB 为 `READY`。
## 测试策略
### 单元与契约测试
- 标准 `#32770`、TaskDialog、GXWND 和无子控件窗口均能进入 `WindowSnapshot`。
- 中英文、动态路径和耗时数字归一化后得到稳定指纹。
- 规则优先级、冲突、阶段限制和必须不存在条件正确。
- UIA Pattern、Win32 消息和接口通道按顺序降级。
- 动作已发送但窗口未变化时不会判定成功。
- 未知窗口立即输出完整证据,不执行任何按钮。
- 两套旧弹窗处理入口不再被生产代码调用。
### 故障注入测试
- 窗口延迟初始化、控件延迟 enabled、句柄复用、窗口瞬间消失。
- 辅助进程创建弹窗、进程 PID 变化、UIA 调用超时。
- 恢复窗口文案变化、中文/英文版本切换、按钮顺序变化。
- 正常 Project Integration 长时间运行但状态持续变化。
- 证据目录不可写、规则 JSON 损坏、现场规则与默认规则冲突。
### 本机真实验收
1. 先对一个可恢复副本上的单个 CBB 运行,不进行批量。
2. 分别验证许可证、文件恢复、Project Integration、保存和关闭路径。
3. 人为保留一个未知测试弹窗,确认它不会被点击且证据完整。
4. 确认全程不切换前台、不移动鼠标、不注入键盘。
5. 确认最终状态桥由 `PENDING` 变为 `READY`。
6. 再用三个条目测试“成功、业务错误、缺文件”各自隔离。
7. 最后才使用冻结包执行小批量回归。
## 明确不做
- 不自动点击完全未知弹窗的默认按钮。
- 不使用真实键盘、鼠标、前台焦点或 `SwitchDesktop`。
- 不依赖屏幕绝对坐标、颜色或截图 OCR 判断成功。
- 不把弹窗消失、日志出现成功字样或 Cert 时间戳单独当作 PASS。
- 不让观察器修改中心库状态;中心库最终状态仍由权威状态桥读取。
- 不在同一个中心库上并发执行多个写入 Verify。
@@ -0,0 +1,169 @@
# CBB 桥接执行与 UNC 网络库设计
## 目标
把中心库状态读取、PCB 文档身份、Project Integration、保存关闭和最终 Verify 状态收敛到结构化桥接接口,消除固定窗口标题、图标、Cert 时间戳和跨进程独立超时造成的误判。同时支持直接选择 UNC 中心库,在不保存凭据、不覆盖用户盘符的前提下自动建立并释放临时网络盘符。
## 已确认接口
### Library Manager 状态接口
- `LMCDLL70.dll::IsVerifiedReuseBlock(CStringT, eReuseBlockType, const CStringT&)` 已在本机 x86/MFC ABI 桥中验证,可返回权威 `READY/PENDING`。
- `LMCDLL70.dll` 同时导出 `GetStatusRBInContextOfCL`、`VerifyReuseBlock` 和 `UnVerifyReuseBlock`。
- `LibManagerDBPI.dll` 导出 `GetReusableCircuitVerificationStatus(const CStringT&, const CStringT&, int, int&)`。
- `VerifyReuseBlock/UnVerifyReuseBlock` 是私有写接口,本设计不调用。原始状态接口只允许在只读探针中验证参数语义,未通过已知样本一致性测试前不参与生产判定。
### Expedition PCB 公开自动化接口
注册表和 Mentor 自带类型库确认:
- `MGCPCB.Application`:CLSID `{EDEDED02-D5F6-4B04-8FE7-EDEDEDEDED00}`,本地服务器为 `XtremeDesignSessionWG.exe`。
- `IMGCPCBApplication.ActiveDocument`、`Quit()`。
- `IMGCPCBDocument.Name`、`FullName`、`ProjectIntegration`、`Validate()`、`Save()`、`IsSaved()`、`Close(Boolean)`。
- `MGCPCBAutomationLicensing.Application.GetToken(Long)`。
- `IMGCPCBProjectIntegration.ProjectFile`。
- `ForwardAnnotationStatus`、`SynchCESStatus`、`LoadCESStatus`、`BackAnnotationStatus`。
- `IsForwardAnnotationAllowed()`、`IsSynchCESAllowed()`、`IsLoadCESAllowed()`、`IsBackAnnotationAllowed()`。
- `ForwardAnnotate()`、`SynchCES()`、`LoadCES()`、`BackAnnotate()`。
`ProjectIntegration.dll` 中的 `EPrjIntStatus` 枚举值为:
- `1`: `Required`
- `2`: `InSynch`
- `3`: `NoCES`
因此执行桥不需要通过 GUI 打开 Setup/Project Integration,也不需要用窗口颜色判断进度。
## 架构
### 1. 中心库路径租约
新增 `LibraryPathLease`,为一次读取或 Verify 会话提供两个路径:
- `display_path`: 用户选择的原始路径,仅用于 UI 和日志。
- `mentor_path`: 传给 Mentor DLL、PCB 和中心库文件访问的稳定路径。
本地盘符路径直接使用。UNC 路径先检查是否已有指向同一共享根的用户映射;存在时复用但绝不释放。不存在时通过 Windows WNet API 从空闲高位盘符创建 `CONNECT_TEMPORARY` 映射,使用当前登录会话已有的 SMB 凭据,不接受也不保存账号密码。租约结束时只释放工具自己创建且仍指向同一共享根的映射。
映射、文件存在性、目录枚举和释放都必须记录原始 UNC、盘符路径、是否复用、Win32 错误码和耗时。网络不可达或映射失败返回 `NETWORK_UNAVAILABLE`,不能转换成空列表或全 `PENDING`。
### 2. 权威状态桥
保留 x86/MFC `CbbStatusBridge32.exe --server`,但每个请求必须回显:
- `request_id`
- `block_name`
- `display_lmc_file`
- `mentor_lmc_file`
- `path_kind`
- `status`
- `source`
- `raw_status`
- `elapsed_ms`
Python 客户端必须核对 `request_id`、条目名和解析后库路径。缺字段、错序响应或路径不一致一律视为桥协议错误。
状态读取仍以经过验证的 `IsVerifiedReuseBlock` 为生产权威源。`GetReusableCircuitVerificationStatus` 作为隔离只读探针,通过已知 READY/PENDING 样本确认参数顺序和枚举语义;只有样本全部一致后才加入响应作为第二证据。两接口不一致时返回 `STATUS_CONFLICT`,UI 不允许勾选为已完成,也不自动 Verify。
### 3. PCB 启动与弹窗监督桥
现场失败证据表明,六个启动超时任务的最后一个共同事件都是 `Select the desired product license`,之后没有产生 `identity_verified`。现有实现向按钮异步投递 `BM_CLICK` 后立即把 `(hwnd, texts)` 放入 `handled`;它没有确认点击被应用接受或窗口已经关闭。若点击发生在弹窗尚未完成初始化时,窗口会继续存在,但后续轮询会永久跳过它。
弹窗监督必须改为显式状态机,并先于 PCB COM 执行桥:
1. 在私有桌面枚举本次 Job Object 的完整进程树窗口,不只匹配最初的 PCB PID;许可、数据库和辅助进程创建的弹窗都纳入同一作用域。
2. 记录窗口句柄、所属 PID、类名、标题、正文、全部按钮/列表/单选控件的 ID、enabled/checked/selected 状态。
3. 对已知弹窗选择确定动作后,用有时限的按钮调用发起操作。
4. 点击后必须等待窗口销毁、隐藏或内容进入下一已知状态,才能记录 `dialog_resolved` 并刷新活动超时。
5. 弹窗仍存在时不得写入“已处理”缓存;按有限次数和退避间隔重试。达到上限后以 `DIALOG_STUCK` 结束当前项并保留控件现场。
6. 同一窗口句柄被复用但正文变化时视为新状态,不沿用旧结论。
许可弹窗不能只根据存在一个 `OK` 按钮就判定成功。桥需要确认许可列表已有有效选择、`OK` 处于 enabled 状态,并在点击后确认弹窗消失。打开锁和 Database Restoration 同样必须确认选择状态及窗口消失。
窗口枚举回调必须显式返回 `True`。`EnumWindows` 或 `EnumChildWindows` 自身失败返回 `WINDOW_ENUM_ERROR`,不能伪装成等待超时。
### 4. PCB 执行桥
新增独立的 32 位 PCB 自动化桥。它与状态桥共享 JSONL 信封格式,但不把 Library Manager 私有 DLL 和 Expedition COM 放入同一进程。每个 CBB 使用独立桥进程,避免 Mentor COM 状态跨条目泄漏。
弹窗监督确认启动阻塞已清除后,执行桥按状态机运行:
1. `attach`: 轮询 `MGCPCB.Application`,取得 `ActiveDocument`。
2. `identify`: 同时核对 `Document.Name/FullName` 和 `ProjectIntegration.ProjectFile` 与请求中的 PCB/PRJ;任何一项不符都不得执行动作。
3. `integration_snapshot`: 返回四项状态及四项 Allowed 标志。
4. `integration_step`: 每次只执行一个 `Required` 且 Allowed 的动作,随后重新读取完整快照。状态变化才算活动。
5. `validate`: 通过 Automation Licensing 获取 token 并调用 `Document.Validate`。
6. `save`: 要求 `Save()` 返回真,随后 `IsSaved()` 返回真。
7. `post_save_snapshot`: 四项必须仍为 `InSynch`。
8. `close`: 调用 `Close(True)`;仅在文档关闭后调用 `Application.Quit()`。
桥按事件输出 `attached/identity/integration/action/validated/saved/closed/error`,每条包含单调递增序号和 HRESULT。Python 不再直接持有 PCB COM 对象,也不再等待固定标题。
### 5. 弹窗与失败优先级
窗口监督由独立适配层运行,只枚举本次私有桌面和 Job Object 进程树,不接触用户前台窗口。
弹窗规则分为三类:
- 可恢复:许可选择、打开锁确认、Database Restoration。处理后产生结构化活动事件。
- 进度:Project Integration 正在运行,仅观察,不点击 Cancel。
- 致命:`Error saving the Reusable Block`、数据库加载终止、无法运行设计服务器等。可以点击确认以便清理,但结果必须锁定为 FAIL,后续 `Save/Close` 标记不能覆盖。
不认识的弹窗不盲点默认按钮,记录标题、正文、控件 ID 后让当前项失败并继续队列。
### 6. 单一超时所有者
父进程是唯一的活动超时所有者。PCB 启动、已处理弹窗、桥状态变化、执行动作、保存标记和关闭事件都会刷新同一个 30 秒 inactivity deadline。重复的相同快照不刷新。
执行桥内部不再维护另一份 30 秒截止时间,只响应父进程终止;父进程超时时通过 Job Object 结束执行桥、PCB 和辅助进程。另设总时长上限,防止不断变化但永不完成的异常流程。
### 7. 网络库性能
删除每次读取时对整个 `ReusableBlocksLP` 的递归元数据指纹。桥读取 383 条实际只需数秒,跨次缓存带来的收益不足以抵消 UNC 全树扫描和陈旧状态风险。
每次用户点击“读取 CBB”都重新请求桥状态。检查点只用于同一次扫描被中断后的恢复,使用以下轻量快照:
- 解析后的 LMC 路径
- LMC 大小和最后修改时间
- `ReusableBlocksLP` 顶层目录的最后修改时间
- 本次已枚举的 CBB 名称集合摘要
目录枚举放到可终止的子进程,单次网络操作有硬超时。超时返回网络错误,不让 UI 工作线程无限等待。Verify 的证据备份继续采用三秒 best-effort,但网络路径默认只备份当前 CBB 的稳定小文件;备份失败不阻塞执行。
## 结果判定
一次 PASS 必须同时满足:
1. 执行桥确认目标 PCB/PRJ 身份;
2. 四项 Project Integration 为 `InSynch`;
3. `Validate`、`Save`、`IsSaved`、`Close(True)` 均成功;
4. 本次没有任何致命弹窗或新产生的 Project Integration 错误;
5. PCB 退出后,状态桥重新读取该 CBB 为 `READY`。
Cert 文件存在或时间戳变化仅写入诊断日志,不单独构成 PASS。最终状态桥仍为 `PENDING`、发生桥冲突或桥不可用时,结果为 FAIL/UNAVAILABLE,不伪报成功。
## 故障隔离
- 单个 CBB 的网络、桥、COM、Project Integration、保存或状态确认错误只影响当前项。
- 每项结束都关闭执行桥并回收其 Job Object。
- 状态桥崩溃时重启后处理下一项;连续启动失败时将剩余项标为环境不可用,避免重复等待。
- 临时盘符租约贯穿整批任务,批次结束或异常退出时释放;释放失败写日志但不改写 Verify 结果。
## 测试与验收
- TDD 覆盖临时映射创建、复用、冲突、释放和 UNC 超时。
- 协议测试覆盖请求关联、错序响应、路径不一致、桥崩溃和状态冲突。
- 弹窗状态机测试覆盖异步点击未生效、窗口未关闭不记成功、控件延迟初始化、句柄复用、子进程弹窗和有限重试。
- 使用假 COM 对象验证四项状态机、身份不符拒绝执行、Fatal 弹窗优先于保存标记。
- 回归测试证明 `EnumWindows`/`EnumChildWindows` 回调始终返回真。
- 383 条 UNC 模拟库读取不递归访问 CBB 子目录。
- 180/3000 条状态扫描保持单桥串行、单条失败隔离和可恢复。
- 冻结包必须包含两个桥及其脚本/类型库依赖,并通过无窗口启动 smoke test。
- 真实 Mentor 验收先用一个可恢复副本和一个 CBB;确认状态桥由 PENDING 变 READY 后,才允许生产中心库批量测试。
## 明确不做
- 不调用 `VerifyReuseBlock` 或 `UnVerifyReuseBlock` 私有写接口。
- 不依赖 TreeView 图标、颜色、右键菜单、鼠标、键盘或固定窗口标题。
- 不并发修改同一个中心库。
- 不保存网络凭据,不覆盖或删除用户已有映射。