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 2814bdb1fb
130 files changed
+19267

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
# Keep the verified Windows source and binary assets byte-for-byte.
# Do not normalize the r4 baseline's line endings during add/checkout.
* -text
+57
View File
@@ -0,0 +1,57 @@
# Generated Python, IDE and test artifacts
__pycache__/
*.py[cod]
.pytest_cache/
.mypy_cache/
.ruff_cache/
.coverage
htmlcov/
*.egg-info/
.venv/
venv/
.vs/
.vscode/
.idea/
# Field evidence, actual Mentor libraries/projects, and local runtime data
/Data temp/
/fixtures/
/runs/
/evidence/
/diagnostics/
/data/
/.cbb-preflight-evidence/
# PyInstaller outputs, source backups and previously packaged distributions
/build/
/build-*/
/dist/
/dist-*/
/*.zip
/*.rar
# Native compiler intermediates; retain the two verified x86 runtime bridges
/tools/**/build*/
**/CMakeFiles/
**/CMakeCache.txt
**/cmake_install.cmake
*.obj
*.pdb
*.ilk
*.exp
*.lib
*.pch
*.idb
*.tlog/
*.exe
*.dll
!tools/status_bridge/bin/CbbStatusBridge32.exe
!tools/status_bridge/bin/VerifyProbe32.exe
# Machine-local configuration and credentials
.env
.env.*
*.local.json
config.local.json
*.pem
*.key
+208
View File
@@ -0,0 +1,208 @@
# Library Manager 接口与树节点结论
## 1. 中心库激活
`LibraryManager.Application` 需要在 STA PowerShell 进程中创建。当前工作站的实测结果:
```powershell
$app = New-Object -ComObject 'LibraryManager.Application'
$lib = $app.OpenLibrary('F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\Mentor_lib_EE7.9\mentor_lib.lmc')
$parts = $lib.Partitions(7)
```
可以读取库名称、完整路径、Reusable Blocks 分区和条目名称;不需要打开 DxDesigner 工程。若 `.lmc` 不存在、被锁定或 Library Manager 未完成初始化,COM 激活可能返回 `0x80004005 (E_FAIL)`,必须记录 HRESULT 并停止。
## 2. 树节点操作
Library Navigator 使用原生 `ATL:SysTreeView32`(AutomationId `1022`)。
- `Reusable Blocks` 和 `Logical-Physical` 未展开时,UI Automation 不会返回其子 `TreeItem`;直接等待 `Logical-Physical` 会超时。
- 可靠流程是先定位并展开 `Reusable Blocks`,再展开 `Logical-Physical`,然后重新枚举子项。
- 当前控件的跨进程 `TVM_GETITEM`/`TVM_EXPAND` 不能作为唯一生产路径:`TVM_GETITEM` 需要目标进程内存,部分 `TVM_EXPAND` 调用会阻塞。生产实现应优先使用 UI Automation 的 `ExpandCollapsePattern`;若模式不可用,报告 `unknown`,不要盲点坐标。
## 3. Verify 接口
对 EE 7.9.5 Library Manager 类型库(`LibraryManager.tlb`)和已记录的 COM 接口进行检查:
- `ILibraryManagerApp`:有 `OpenLibrary`、`ActiveLibrary`、`LMCModify` 等方法,没有 `Verify` 或 reusable-block 校验方法。
- `IMGCLMLibrary`:有 `Partitions(type)`、`Close`、编辑器属性,没有 `Verify`。
- `IMGCLMReuseBlock`:只有 `type`、`Name`、`PartitionName` 属性,没有校验方法。
- `VerifyAutomation.dll` 中的 `IVerifyControl` 是 SI/PI 仿真 Verify 控制接口,不是 Library Manager CBB 条目 Verify,不能拿来替代。
因此 `LibraryManager.Application` 没有公开的 CBB `Verify()` COM 方法。正式的内容检查入口存在于安装包自带的 Tcl 脚本 `D:\Mentor\7.9.5EE\SDD_HOME\lm\win32\lib\upc_utils.tcl`:
补充检查 `LMCDLL70.dll` 和 `LibManagerDBPI.dll` 的导出表后,确认了真实的内部状态链:
- `LMCDLL70.dll` 导出 `IsVerifiedReuseBlock`、`GetStatusRBInContextOfCL`、`VerifyReuseBlock`、`UnVerifyReuseBlock`;
- `LibManagerDBPI.dll` 导出 `GetReusableCircuitVerificationStatus`;
- 反汇编确认 `IsVerifiedReuseBlock` 会调用 `GetReusableCircuitVerificationStatus`,并根据输出状态返回布尔值。
这不是猜测的图标映射,而是 Mentor 自己用于判断 Verify 状态的实现链。但是函数使用 32 位 MFC/C++ ABI(装饰名、`CStringT`、内部数据库对象),不能从当前 64 位 Python 进程直接安全调用。一次隔离桥接实验也证明,手工伪造 `CStringT` 内存布局会在 DLL 内部异常,因此不能用 ctypes 拼结构体绕过 ABI。正确接入方式是使用与 Mentor 同位数、同 MFC ABI 的 C++ 只读桥接进程,先封装 `GetReusableCircuitVerificationStatus`,再替换当前图标/文件回退判断;在桥接完成前,生产工具不调用这些导出函数。
```tcl
proc runReuseBlockChkContents { rbType rbName lmcFile libspec dmsloginconf } {
# RULP (Logical-Physical) maps to LP
ReuseBlockImporter.exe \
-lmcFile $lmcFile -blockName $rbName -logicalType LP \
-chkContents -libSpec $libspec -dmsLoginConfig $dmsloginconf
}
```
该过程由 `processReuseBlockChunk` 在需要更新/验证的 RULP 条目上调用。它会把标准输出和错误输出重定向到:
`LogFiles\restorerb_RULP_<名称>_contents.log`(`safeName` 会把键名中的冒号等非法字符替换为下划线)。成功文本是 `Reuse Block's content checking completed successfully!`,失败文本是 `Reuse Block's content checking failed!`。实测缺少 DMS 登录配置时返回进程码 1,并输出 `Login config switch is empty!`,所以不能只看进程启动或窗口关闭来判定成功。
本工具的 `Invoke-CbbVerify.ps1` 已封装这条接口:COM 只负责确认 `.lmc` 和条目身份,`ReuseBlockImporter.exe -chkContents` 负责实际检查,结果必须同时满足成功文本且无错误文本才标记 `pass`;否则为 `fail`、`timeout` 或 `unknown`。当前证据尚不能证明脱离 Library Manager 的 CLI 调用会单独更新树节点颜色;最终红/黄到绿仍需在有 DMS 的工作站读取 Library Manager 状态确认。UI Automation 仅作为状态读取补充,不再作为 Verify 的触发机制。
## 4. 本地样本验证结果
- `CreateLibrary(path, 4)`(`kFLOW_NONE`)生成的空库打开时报 `Unable to determine flow type`。
- `CreateLibrary(path, 1)`(`kFLOW_DX`)生成的 `sample_verify_dx.lmc` 可以正常打开,但没有 CBB 条目,无法执行条目 Verify。
- 将生产库文件和 `ReusableBlocksLP` 复制到 `fixtures\cloned-library` 后,副本可打开并显示生产条目;对副本发送树导航和 `Verify` 菜单动作没有出现可读完成窗口。Library Manager 会重写副本 `.lmc`,因此样本操作必须始终使用副本,不能用于生产库。
## 5. 2026-09-15 重启复测
重启后不预先打开 Library Manager,COM 仍可成功激活并执行 `OpenLibrary()`:返回 `mentor_lib`,Reusable Blocks 分区数量为 2,条目包含 `1GPHY_8211` 和 `1GPHY_RTL8211F_A`。随后直接启动 `.lmc` 也能得到主窗口,状态栏为 `Ready`,树控件 `ATL:SysTreeView32` 存在且可用。结论:当前问题不是中心库文件缺失,而是树展开/Verify 完成信号的自动化契约尚未建立。
## 6. 后台菜单触发探针结果
Library Manager 的 CBB 右键菜单可通过目标树控件的消息路径后台触发:先向 `ATL:SysTreeView32` 投递 `WM_MOUSEMOVE`,再投递 `WM_RBUTTONDOWN/WM_RBUTTONUP`,最后通过 UI Automation `InvokePattern` 调用菜单项 `Verify`(AutomationId `194`)。只投递右键按下/抬起会被路由到停靠面板菜单;只发送 `VK_APPS` 键盘消息不会打开 CBB 菜单。
生产实现只向本次启动的目标树窗口发送定向消息,不监听、不注入用户真实键盘,也不调用 `SendInput` 或切换用户前台桌面。命中点使用 UI Automation 的屏幕矩形;发送后必须同时找到唯一且启用的 `Verify` 菜单项。若 Win10 的 UIA `InvokePattern` 只返回成功但未关闭原生弹出菜单,则向该私有菜单窗口投递相对坐标的鼠标消息作为兜底,并记录 `verify_menu_fallback`,不执行其它菜单命令。
## 7. 2026-09-17 触发机制复测(结论修正)
第 6 节的结论**不成立**:在 7.9.5 的实际 Library Manager 上,消息路径无法打开 CBB 菜单。复测方式与证据:
| 触发方式 | 结果 |
| --- | --- |
| 投递鼠标消息(客户区坐标,含 `ScreenToClient` 换算) | 打开**停靠面板**菜单(Allow Docking / Hide / Properties…,AutomationId 43040/43041/12001) |
| 用 `AttachThreadInput` 真正把焦点设到树后再投递 | 同上,仍是停靠面板菜单 |
| `WM_CONTEXTMENU` + 屏幕坐标(树 / 框架窗口) | 停靠面板菜单 / 无菜单 |
| `WM_CONTEXTMENU` + `lParam=-1`(键盘调用标记) | 停靠面板菜单 / 无菜单 |
| `VK_APPS` 键盘消息 | 无菜单 |
| `WM_COMMAND 194` 广播到 LM 全部窗口(含 AfxWnd90 / AtlAxWin90 / 树) | 无任何反应 |
| `SendMessage` 同步变体 | **LM 线程不处理,调用方阻塞挂起**(已用看门狗确认堆栈) |
| 真实输入(pywinauto `click_input`)+ 输入桌面切换 | ✅ 成功打开 CBB 菜单并执行 Verify(12:13 的 `private-click-result.json`,连带拉起 ExpeditionPCB) |
| 键盘激活:`VK_APPS` 投递到树 / AtlAxWin90 / 停靠面板 / 框架窗口 | 无菜单(2026-09-17 23:43 复测,`build/keyboard-menu.json`) |
| 键盘激活:`Shift+F10`(`WM_SYSKEYDOWN VK_F10` + 上下文位)同四个目标 | 无菜单 |
| 键盘激活:`WM_CONTEXTMENU(-1)` 投递到树 / ATL 宿主 | 仍是**停靠面板**菜单(与鼠标路径同一根因:回退到物理光标 (0,0)) |
| 键盘激活:`WM_CONTEXTMENU(-1)` 投递到停靠面板 / 框架窗口 | 无菜单 |
根因:LM 的导航器用**物理光标位置**(`GetCursorPos`)决定右键菜单归属,不读消息 lparam。在私有桌面上:
- `SetCursorPos` 返回 `False`,光标恒为 `(0,0)`(`GetCursorPos` 实测),因此消息路径永远命中 (0,0) 处的停靠面板;
- 要让真实输入生效,必须先把私有桌面切换为输入桌面(`SwitchDesktop`)。
本机 2026-09-17 实测 `SwitchDesktop` 到新建桌面在多种进程上下文下均返回 `False`(agent 进程、非沙箱 shell、计划任务进程;`GetLastError=0`),因此生产代码不保留真实输入兜底。当前实现只在私有桌面内发送定向树消息,并要求唯一启用的 `Verify` 菜单项通过 UI Automation 调用;若菜单未出现,当前 CBB 失败并保留完整窗口/菜单证据,不会误点其它命令。
结论:**鼠标与键盘两条 UI 触发路线都无法在用户输入桌面上安全复现**。历史上曾验证过直接启动 ReusableCircuit PCB,但它只能完成 PCB 保存,不能把 LMC 的 Verify 状态提交为 READY。因此当前生产实现已改为在私有桌面内定位 LMC 树节点并调用原生 Verify;后续仍复用同一 PCB/COM/保存链路。该路线同样需要 iCDB 设计服务器端口(10000-10100)。
## 8. 2026-09-17 跑通流程复现与真实阻断点
`build/background-trials/verify-54a3af873736` 是一次完整跑通的记录(生产中心库,Audio_D2128_ESD)。它的流程**没有任何 Library Manager 菜单步骤**:
```
23:03:40 backup
23:03:41 pcb_launch D:\Mentor.9.5EE\SDD_HOME\wg\win32in\ExpeditionPCB.exe <pcb> -ReusableCircuit
23:05:13 identity_verified COM 文档身份 = Work\Audio_D2128_ESD.prj / Audio_D2128_ESD.pcb
23:05:13 integration_status {ForwardAnnotation:2, SynchCES:2, LoadCES:2, BackAnnotation:2}
23:05:26 saved_and_closed LICENSE_OK/SAVE_OK/IS_SAVED/POST_SAVE_SYNCHRONIZED/CLOSE_OK/QUIT_OK
23:05:27 complete PASS,中心库 Cert 工程已更新
```
历史结论:Library Manager 的 `Verify` 菜单内部会启动同一个 ReusableCircuit PCB,因此直接命令行启动曾经可以复现 PCB 内部动作,但无法替代 LMC 菜单本身的状态提交。当前生产主线(`mentor_adapter.execute_job`)改为 `library_manager_verify.launch_library_verify` 的原生 Verify 调用,再绑定其创建的 PCB 进程:
| 环节 | 证据 |
| --- | --- |
| PCB 命令行 | `pcb_launch` 事件(含 `wg\win32in` 路径与 `-ReusableCircuit` 开关) |
| 启动期弹窗 | `dialogs.jsonl`:`Select the desired product license`(控件 1)、`Tip of the Day`(控件 1)、`Do you want to save the Reusable Block cell?`(控件 6=IDYES) |
| 保存/关闭 | cscript 助手输出六个标记,缺一不可 |
| 提交确认 | 中心库 `Cert\<prj>.prj` 的 mtime 必须变化,且 `Cert\PCB\Layout\LayoutDB.lyt` 存在 |
### 真实阻断点:iCDB 设计服务器端口被系统保留
2026-09-17 之后的复跑全部失败,`Work\PCB\LogFiles\PCBLogFile.txt` 写明:
```
No server is running for the project and could not bring it alive (Could not run server)
```
对应 `Work\database\cdbsvr\log\<时间>/<日期>.txt` 的根因:
```
ERROR: Could not listen for client connections: Socket Exception ... BindFailed
ERROR: NoNetworkPortAvailable ... No free network port in range [10000 - 10100]
```
本机 `netsh int ipv4 show excludedportrange protocol=tcp` 显示 `9930-10029`、`10030-10129` 等保留区间把 10000–10100 全部覆盖,Python 直接 `bind()` 也返回 `WinError 10013`(而 12000 可绑定)。这是 Hyper-V/WSL 的动态端口预留,不是工具缺陷。
修复(需管理员):`net stop winnat && net start winnat`。工具已内置该检测:命中时立即以 `BLOCKED` 结束并给出上述命令,不再等到超时。
### 目录/数据问题的条目
同一中心库里 `1GPHY_8211`(Work 下无唯一 PRJ)与 `1GPHY_RTL8211F_A`(PRJ 指向不存在的 `1GPHY_RTL8211F.pcb`)在 preflight 阶段即 `BLOCKED`,与刷新流程无关,属条目数据问题。
## 9. 2026-09-24 Verify 导出只读探测
新增 `tools/status_bridge/bin/VerifyProbe32.exe --probe-exports`。探测桥使用与
Mentor EE 7.9 相同的 x86 进程加载 `LMCDLL70.dll` 和 `LibManagerDBPI.dll`,只调用
`GetProcAddress`,不调用任何 Verify/UnVerify 写接口。
本机实测返回五个导出:
- `IsVerifiedReuseBlock`:找到,地址 `0x100544E0`;
- `GetStatusRBInContextOfCL`:找到,地址 `0x1006DDC0`;
- `VerifyReuseBlock`:找到,地址 `0x10057840`;
- `UnVerifyReuseBlock`:找到,地址 `0x10061B40`;
- `GetReusableCircuitVerificationStatus`:找到,地址随模块加载基址变化。
探测响应明确标记 `write_call.enabled=false`。首次实现曾在结束时主动卸载 DLL,进程
出现 `0xC0000374`;移除 `FreeLibrary` 后正常退出,说明 Mentor 的 MFC/DBPI 模块
状态不能由短桥主动卸载,只能让操作系统在进程退出时回收。
这次探测确认了“写导出存在”,但没有确认 `CFilename` 的构造 ABI。因此正式工具仍
只使用 `IsVerifiedReuseBlock` 读取状态;`VerifyReuseBlock` 需要继续在隔离 `.lmc`
副本上完成 ABI 构造和前后状态验证后,才可讨论接入。
## 10. 2026-09-25 原生 CLibServer 生命周期与 Verify 阻断点
在隔离目录
`diagnostics/native-verify-probe-20260925/` 中新增了 Win32
`NativeVerifyProbe32.exe`。它复现 Mentor 自带 `RFSymMergeUtility.exe` 的只读
生命周期:
```text
operator new(0xC)
CLibServer(path)
Init()
Load(path, 1)
Close()
~CLibServer()
```
实机输出为 `init_return=0`、`load_return=0`、`closed=true`、`destroyed=true`,
隔离 LMC 的 SHA256 在 probe 前后保持
`7701DC9661088BAF7AB3A08861B7BE0E2C9B016E0BF158B60AF6597E73246A73` 不变。这
确认了 x86 `__thiscall`、12 字节对象大小、窄字符路径和 `Load` 模式 `1`,但没有
调用任何 Verify/Save 写接口。
进一步静态审计确认:
- `SetVerifyRCCellsFlag(int)` 只是把值写到 `this` 的首字段;
- `VerifyRCCells(int)` 的唯一直接调用点在 `CLibServer::Save` 内部;
- `vbcam_tl.exe` 只调用构造/Init/Load 和分区枚举,没有 Verify/Save;
- `RFSymMergeUtility.exe` 的保存顺序是 `Save(NULL,0,0)` 后检查数据库再 `Close()`,
但它没有调用 Verify 导出本身。
随后在隔离副本上执行了一次受保护的 Save 驱动实验:
`SetVerifyRCCellsFlag(1)`、`Save(NULL,0,0)`,并在进程退出后重新读取状态。结果为:
- `Init=0`、`Load=0`、`Save=0`,关闭和析构正常;
- 只改写了副本 `mentor_lib.lmc`,`ReusableBlocksLP` 未变化;
- 状态桥仍返回 `IP101GR=PENDING`。
这证明低层 `CLibServer` Save 成功并不等于 CBB Verify 状态提交成功。缺失的提交
上下文仍由 Library Manager 的 reusable-block/PCB certificate 链路持有。因此生产
工具继续只使用只读 `IsVerifiedReuseBlock` 状态桥和原有 LMC/PCB Verify 流程;不再
尝试把 `VerifyRCCells(0/1)` 或 `SetVerifyRCCellsFlag` 直接接入生产。
+269
View File
@@ -0,0 +1,269 @@
Set-StrictMode -Version Latest
$script:RequiredStates = @(
'library_item_present',
'verify_result',
'cbb_status_flag',
'error_state'
)
function Get-CbbRefreshRequiredStates {
return @($script:RequiredStates)
}
function Read-CbbRefreshStatus {
[CmdletBinding()]
param([Parameter(Mandatory)][string]$Path)
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
throw "Status file does not exist: $Path"
}
try {
$status = Get-Content -LiteralPath $Path -Raw -Encoding UTF8 | ConvertFrom-Json -ErrorAction Stop
}
catch {
throw "Status file is not valid UTF-8 JSON: $Path"
}
if ($null -eq $status -or $status.schemaVersion -ne 1 -or $null -eq $status.states) {
throw 'Status must contain schemaVersion=1 and states.'
}
foreach ($name in $script:RequiredStates) {
$property = $status.states.PSObject.Properties[$name]
if ($null -eq $property) {
throw "Status is missing state: $name"
}
if ([string]$property.Value -notin @('red', 'yellow', 'green', 'unknown')) {
throw "Unsupported state color for ${name}: $($property.Value)"
}
}
return $status
}
function Get-CbbRefreshNextAction {
[CmdletBinding()]
param([Parameter(Mandatory)]$Status)
foreach ($name in $script:RequiredStates) {
$color = [string]$Status.states.PSObject.Properties[$name].Value
if ($color -in @('red', 'yellow')) {
return [pscustomobject]@{
State = $name
Color = $color
Action = switch ($name) {
'library_item_present' { 'locate_uploaded_cbb' }
'verify_result' { 'run_cbb_verify' }
'cbb_status_flag' { 'confirm_cbb_green_flag' }
'error_state' { 'resolve_cbb_verify_error' }
}
}
}
if ($color -eq 'unknown') {
return [pscustomobject]@{
State = $name
Color = $color
Action = 'blocked_unknown_state'
}
}
}
return $null
}
function Test-CbbRefreshAllGreen {
[CmdletBinding()]
param([Parameter(Mandatory)]$Status)
foreach ($name in $script:RequiredStates) {
if ([string]$Status.states.PSObject.Properties[$name].Value -ne 'green') {
return $false
}
}
return $true
}
function New-CbbRefreshVerification {
[CmdletBinding()]
param(
[Parameter(Mandatory)]$Status,
[Parameter(Mandatory)][AllowEmptyCollection()][object[]]$Observations
)
$next = Get-CbbRefreshNextAction -Status $Status
$allGreen = Test-CbbRefreshAllGreen -Status $Status
$issues = New-Object 'System.Collections.Generic.List[string]'
if ($null -ne $next) {
[void]$issues.Add("pending_action:$($next.Action)")
}
foreach ($observation in @($Observations)) {
if ($null -eq $observation -or [string]::IsNullOrWhiteSpace([string]$observation.timestampUtc)) {
[void]$issues.Add('observation_missing_timestamp')
}
if ([string]$observation.result -in @('error', 'timeout', 'unknown')) {
[void]$issues.Add("observation_$($observation.result)")
}
}
[pscustomobject]@{
schemaVersion = 1
generatedAtUtc = [datetime]::UtcNow.ToString('o')
result = if ($allGreen -and $issues.Count -eq 0) { 'PASS' } else { 'BLOCKED' }
allGreen = $allGreen
nextAction = if ($null -eq $next) { $null } else { $next.Action }
issues = @($issues)
observationCount = @($Observations).Count
}
}
function Write-CbbRefreshVerification {
[CmdletBinding()]
param(
[Parameter(Mandatory)]$Verification,
[Parameter(Mandatory)][string]$Path
)
$parent = Split-Path -Parent ([IO.Path]::GetFullPath($Path))
if ($parent -and -not (Test-Path -LiteralPath $parent -PathType Container)) {
New-Item -ItemType Directory -Path $parent -Force | Out-Null
}
$temporary = "$Path.tmp-$([guid]::NewGuid().ToString('N'))"
try {
$Verification | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $temporary -Encoding UTF8
Move-Item -LiteralPath $temporary -Destination $Path -Force
}
finally {
if (Test-Path -LiteralPath $temporary -PathType Leaf) {
Remove-Item -LiteralPath $temporary -Force -ErrorAction SilentlyContinue
}
}
}
function Get-CbbReuseBlockImporterPath {
[CmdletBinding()]
param([string]$MentorBin = $env:SDD_LM_BIN)
if ([string]::IsNullOrWhiteSpace($MentorBin)) {
throw 'Mentor bin is not configured. Set SDD_LM_BIN or pass -MentorBin.'
}
$path = Join-Path ([IO.Path]::GetFullPath($MentorBin)) 'ReuseBlockImporter.exe'
if (-not (Test-Path -LiteralPath $path -PathType Leaf)) {
throw "ReuseBlockImporter.exe was not found: $path"
}
return [IO.Path]::GetFullPath($path)
}
function Invoke-CbbReuseBlockContentCheck {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$LmcFile,
[Parameter(Mandatory)][string]$BlockName,
[Parameter(Mandatory)][string]$LibSpec,
[Parameter(Mandatory)][string]$DmsLoginConfig,
[string]$MentorBin = $env:SDD_LM_BIN,
[string]$ReportPath,
[int]$TimeoutSeconds = 120
)
$lmc = [IO.Path]::GetFullPath($LmcFile)
if (-not (Test-Path -LiteralPath $lmc -PathType Leaf)) {
throw "Library file was not found: $lmc"
}
if ([string]::IsNullOrWhiteSpace($BlockName)) { throw 'BlockName cannot be empty.' }
if ([string]::IsNullOrWhiteSpace($LibSpec)) { throw 'LibSpec cannot be empty.' }
if ([string]::IsNullOrWhiteSpace($DmsLoginConfig)) { throw 'DmsLoginConfig cannot be empty.' }
if ($TimeoutSeconds -lt 1) { throw 'TimeoutSeconds must be at least 1.' }
$exe = Get-CbbReuseBlockImporterPath -MentorBin $MentorBin
if ([string]::IsNullOrWhiteSpace($ReportPath)) {
$logDir = Join-Path ([IO.Path]::GetDirectoryName($lmc)) 'LogFiles'
# Match Mentor's safeName procedure: Windows-invalid key characters become '_'.
$safeBlockName = ($BlockName -replace '[\\/:*?"<>|]', '_')
$ReportPath = Join-Path $logDir ("restorerb_RULP_{0}_contents.log" -f $safeBlockName)
}
$report = [IO.Path]::GetFullPath($ReportPath)
$reportDir = Split-Path -Parent $report
if ($reportDir -and -not (Test-Path -LiteralPath $reportDir -PathType Container)) {
New-Item -ItemType Directory -Path $reportDir -Force | Out-Null
}
$arguments = @('-lmcFile', $lmc, '-blockName', $BlockName, '-logicalType', 'LP',
'-chkContents', '-libSpec', $LibSpec, '-dmsLoginConfig', $DmsLoginConfig)
$quote = {
param([string]$value)
if ($value -notmatch '[\s"]') { return $value }
return '"' + ($value -replace '(\\*)"', '$1$1\"' -replace '(\\+)$', '$1$1') + '"'
}
$psi = [Diagnostics.ProcessStartInfo]::new()
$psi.FileName = $exe
$psi.Arguments = (($arguments | ForEach-Object { & $quote ([string]$_) }) -join ' ')
$psi.WorkingDirectory = [IO.Path]::GetDirectoryName($lmc)
$psi.UseShellExecute = $false
$psi.CreateNoWindow = $true
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$startedUtc = [datetime]::UtcNow
$process = [Diagnostics.Process]::new()
$process.StartInfo = $psi
try {
if (-not $process.Start()) { throw 'ReuseBlockImporter process did not start.' }
# Drain both pipes while the child runs. Reading after WaitForExit can
# deadlock once the child fills the pipe buffer, which would be
# misreported as a timeout.
$stdoutTask = $process.StandardOutput.ReadToEndAsync()
$stderrTask = $process.StandardError.ReadToEndAsync()
if (-not $process.WaitForExit($TimeoutSeconds * 1000)) {
try { $process.Kill() } catch { }
$result = 'timeout'
$exitCode = $null
}
else {
$result = 'unknown'
$exitCode = $process.ExitCode
}
$stdout = ''
$stderr = ''
# Bounded drain: a grandchild holding the pipe open must not hang the
# check. Partial output is dropped rather than blocking forever.
try { if ($stdoutTask.Wait(5000)) { $stdout = [string]$stdoutTask.Result } } catch { }
try { if ($stderrTask.Wait(5000)) { $stderr = [string]$stderrTask.Result } } catch { }
}
catch {
$result = 'error'
$exitCode = $null
$stdout = ''
$stderr = $_.Exception.ToString()
}
finally {
$process.Dispose()
}
$combined = @($stdout, $stderr) -join "`r`n"
[IO.File]::WriteAllText($report, $combined, [Text.UTF8Encoding]::new($false))
if ($result -eq 'unknown') {
if ($combined -match '(?i)completed successfully' -and $combined -notmatch '(?i)failed|error') {
$result = 'pass'
}
elseif ($combined -match '(?i)failed|error|cannot connect|bad data') {
$result = 'fail'
}
elseif ($exitCode -eq 0) {
$result = 'unknown'
}
else {
$result = 'fail'
}
}
[pscustomobject]@{
operation = 'reuse_block_content_check'
lmcFile = $lmc
blockName = $BlockName
logicalType = 'LP'
libSpec = $LibSpec
reportPath = $report
executable = $exe
startedAtUtc = $startedUtc.ToString('o')
completedAtUtc = [datetime]::UtcNow.ToString('o')
exitCode = $exitCode
result = $result
output = $combined
}
}
Export-ModuleMember -Function Get-CbbRefreshRequiredStates, Read-CbbRefreshStatus, Get-CbbRefreshNextAction, Test-CbbRefreshAllGreen, New-CbbRefreshVerification, Write-CbbRefreshVerification, Get-CbbReuseBlockImporterPath, Invoke-CbbReuseBlockContentCheck
+73
View File
@@ -0,0 +1,73 @@
[CmdletBinding()]
param(
[string]$WindowTitlePattern = 'Library Manager',
[int]$ProcessId = 0,
[Parameter(Mandatory)][string]$OutputJson
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName UIAutomationClient
Add-Type -AssemblyName UIAutomationTypes
$root = [System.Windows.Automation.AutomationElement]::RootElement
$windows = @($root.FindAll(
[System.Windows.Automation.TreeScope]::Children,
[System.Windows.Automation.Condition]::TrueCondition
) | Where-Object {
[string]$_.Current.Name -match $WindowTitlePattern
})
if ($ProcessId -gt 0) {
$windows = @($windows | Where-Object {
[int]$_.Current.ProcessId -eq $ProcessId
})
}
if ($windows.Count -ne 1) {
throw "Expected exactly one Library Manager window, found $($windows.Count)."
}
function Get-ElementRecord {
param([Parameter(Mandatory)]$Element)
$patterns = New-Object 'System.Collections.Generic.List[string]'
foreach ($pattern in @(
[System.Windows.Automation.InvokePattern]::Pattern,
[System.Windows.Automation.ExpandCollapsePattern]::Pattern
)) {
try {
if ($null -ne $Element.GetCurrentPattern($pattern)) {
[void]$patterns.Add([string]$pattern.ProgrammaticName)
}
}
catch { }
}
[pscustomobject]@{
name = [string]$Element.Current.Name
automationId = [string]$Element.Current.AutomationId
controlType = [string]$Element.Current.ControlType.ProgrammaticName
className = [string]$Element.Current.ClassName
processId = [int]$Element.Current.ProcessId
nativeWindowHandle = [int]$Element.Current.NativeWindowHandle
isEnabled = [bool]$Element.Current.IsEnabled
patterns = @($patterns)
}
}
$tree = @($windows[0].FindAll(
[System.Windows.Automation.TreeScope]::Descendants,
[System.Windows.Automation.Condition]::TrueCondition
) | ForEach-Object { Get-ElementRecord -Element $_ })
$document = [ordered]@{
schemaVersion = 1
capturedAtUtc = [datetime]::UtcNow.ToString('o')
windowTitlePattern = $WindowTitlePattern
processId = [int]$windows[0].Current.ProcessId
window = Get-ElementRecord -Element $windows[0]
elements = $tree
}
$parent = Split-Path -Parent ([IO.Path]::GetFullPath($OutputJson))
if ($parent -and -not (Test-Path -LiteralPath $parent -PathType Container)) {
New-Item -ItemType Directory -Path $parent -Force | Out-Null
}
$document | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $OutputJson -Encoding UTF8
$document | ConvertTo-Json -Depth 8
+24
View File
@@ -0,0 +1,24 @@
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$StatusJson,
[Parameter(Mandatory)][string]$OutputJson
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$module = Join-Path $PSScriptRoot 'CBBRefresh.Core.psm1'
Import-Module $module -Force
$status = Read-CbbRefreshStatus -Path $StatusJson
$observations = @()
if ($null -ne $status.observations) {
$observations = @($status.observations)
}
$verification = New-CbbRefreshVerification -Status $status -Observations $observations
Write-CbbRefreshVerification -Verification $verification -Path $OutputJson
$verification | ConvertTo-Json -Depth 8
if ($verification.result -eq 'PASS') {
exit 0
}
exit 3
+57
View File
@@ -0,0 +1,57 @@
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$LmcFile,
[Parameter(Mandatory)][string]$BlockName,
[Parameter(Mandatory)][string]$LibSpec,
[Parameter(Mandatory)][string]$DmsLoginConfig,
[string]$MentorBin = $env:SDD_LM_BIN,
[string]$ReportPath,
[string]$EvidenceJson,
[int]$TimeoutSeconds = 120
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$module = Join-Path $PSScriptRoot 'CBBRefresh.Core.psm1'
Import-Module $module -Force
try {
$invokeArgs = @{
LmcFile = $LmcFile
BlockName = $BlockName
LibSpec = $LibSpec
DmsLoginConfig = $DmsLoginConfig
MentorBin = $MentorBin
ReportPath = $ReportPath
TimeoutSeconds = $TimeoutSeconds
}
$check = Invoke-CbbReuseBlockContentCheck @invokeArgs
if (-not [string]::IsNullOrWhiteSpace($EvidenceJson)) {
$parent = Split-Path -Parent ([IO.Path]::GetFullPath($EvidenceJson))
if ($parent -and -not (Test-Path -LiteralPath $parent -PathType Container)) {
New-Item -ItemType Directory -Path $parent -Force | Out-Null
}
$check | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $EvidenceJson -Encoding UTF8
}
$check | ConvertTo-Json -Depth 8
switch ($check.result) {
'pass' { exit 0 }
'fail' { exit 4 }
'timeout' { exit 5 }
default { exit 3 }
}
}
catch {
$errorResult = [pscustomobject]@{
operation = 'reuse_block_content_check'
result = 'error'
error = $_.Exception.ToString()
lmcFile = $LmcFile
blockName = $BlockName
}
$errorResult | ConvertTo-Json -Depth 8
if (-not [string]::IsNullOrWhiteSpace($EvidenceJson)) {
$errorResult | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $EvidenceJson -Encoding UTF8
}
exit 2
}
+26
View File
@@ -0,0 +1,26 @@
# Library Manager Verify 现场探针清单
本文件是接入 Library Manager 7.9.5 UI 自动化前的必要证据清单。未取得现场证据前,工具只运行离线校验,不自动点击生产中心库。
## 需要确认的控件
在 Library Manager 窗口中记录 Verify 菜单项、对话框按钮和 CBB 状态节点的:窗口标题、进程名/PID、控件类型、AutomationId、Name、IsEnabled、状态颜色的可读来源、可执行动作和动作完成信号。
| 状态键 | 界面对象 | 需要确认的动作 | 完成信号 |
| --- | --- | --- | --- |
| `library_item_present` | 上传后的 CBB 条目 | 定位并核对 CBB 名称/来源 | 条目存在且身份匹配 |
| `verify_result` | Verify 菜单和对话框 | 右键 CBB 条目执行 Verify | Verify 对话框完成且无错误 |
| `cbb_status_flag` | CBB 条目状态标志 | 读取状态节点颜色 | 状态标志为绿色 |
| `error_state` | ERROR/Cell Name/警告节点 | 读取并记录错误,不自动删除属性 | 没有未处理错误 |
## 接入规则
- 仅通过 Windows UI Automation 的语义控件调用 `InvokePattern`,不使用坐标、图像匹配或 `SendKeys`。
- 每次点击前重新读取 Library Manager 窗口、中心库文件和 CBB 条目身份。
- 每次点击后等待状态属性或控件树发生可验证变化,再重新枚举四项校验状态;固定睡眠只能作为轮询间隔,不能作为完成判断。
- 发现多个匹配控件、控件没有 InvokePattern、颜色来源不可读、工程身份不一致或出现错误弹窗时,状态设为 `unknown` 并停止。
- 现场需分别采集:初始红灯、初始黄灯、单项变绿、四项全绿、错误弹窗和取消动作证据。
## 当前阻断项
本地资料只有截图、`.prj` 配置和历史操作规程,没有 Library Manager Verify 控件树或稳定 AutomationId。因此不能在本目录中臆造可用于生产的点击器;下一步应在可恢复的测试中心库上运行探针并把结果保存到 `evidence\`。
+277
View File
@@ -0,0 +1,277 @@
# CBB 中心库上传后校验工具
本目录是独立的 CBB 中心库上传后校验工具,不属于 Part Replacement,也不负责 CBB 工程复制或中心库上传。
## 功能边界
| 工具 | 处理对象 | 核心动作 | 结果 |
| --- | --- | --- | --- |
| `dxdesigner-part-replacement` | 普通器件 Part Number | 旧 Part 替换为新 Part | 原理图器件被替换 |
| `cbb-upload-795` | CBB 工程/中心库 | 复制、Packager、上传、Verify | 中心库新增或更新 CBB |
| 本工具 | 已上传到中心库的 CBB 条目 | 在 Library Manager 中执行/确认 Verify,检查条目和 CBB 状态标志 | 中心库 CBB 校验完成且结果可追溯 |
这里的“刷新检验”明确指 CBB 上传中心库后的收尾校验:在 Library Manager 找到刚上传的 CBB,右键执行 `Verify`,处理 Verify 流程中的按钮/错误,并确认条目状态标志变为绿色。它不替换 Part Number,不同步 PCB,不改写中心库、`.prj` 或网表文件,也不负责上传动作本身。
本校验工具不读取或修改 PCB 文件,也不依赖工作区中的 CBB 工程样本。
## 当前实现
运行时只依赖目标工作机器上可用的 Mentor/DMS 环境、中心库 `.lmc`、CBB 名称、LibSpec 和 DMS 登录配置。历史试跑记录、截图和旧版本探针不参与判定。
入口:
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\CBBRefresh.ps1 `
-StatusJson .\examples\project-integration-before.json `
-OutputJson .\runs\sample-report.json
```
输出会给出下一项应执行的 Verify 动作、是否已经全部通过、阻断原因和证据摘要。
### 已定位的正式 Verify 入口
运行真实校验前可先检查本机环境:
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\Test-CbbVerifyEnvironment.ps1 `
-DmsRoot 'C:\path\to\dms' `
-DmsLoginConfig 'C:\path\to\dms-login-config'
```
`ready=false` 时不要尝试 Verify;这表示 DMS 运行时或登录配置尚未就绪。
Library Manager 的安装脚本 `upc_utils.tcl` 使用 `ReuseBlockImporter.exe -chkContents` 完成 Logical-Physical CBB 内容校验,不需要通过坐标点击菜单。可直接调用:
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\Invoke-CbbVerify.ps1 `
-LmcFile 'F:\path\mentor_lib.lmc' `
-BlockName 'CBB_NAME' `
-LibSpec 'YOUR_LIBSPEC' `
-DmsLoginConfig 'C:\path\dms-login-config' `
-EvidenceJson .\runs\cbb-name-verify.json
```
命令使用固定的 `-logicalType LP` 和 `-chkContents`,输出报告默认落在 `.lmc` 同目录的 `LogFiles\restorerb_RULP_<CBB_NAME>_contents.log`(非法文件名字符会转成下划线)。`pass` 必须看到 `content checking completed successfully` 且没有错误文本;缺少 DMS 登录配置、DMS 未连接、内容检查失败或超时都会阻断。`-LibSpec` 与 `-DmsLoginConfig` 没有默认值,避免把未认证的测试误判为成功。
注意:该 CLI 是 Library Manager 内部的内容检查入口;它是否在当前站点版本中同步更新树节点的红/黄/绿色标志,仍需在已连接 DMS 的实际中心库上读取状态确认,工具不会仅凭进程退出码宣布“四绿”。
现场只读探针(在 Library Manager 已打开并选中刚上传的 CBB 条目时运行):
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\CBBRefresh.UiProbe.ps1 `
-WindowTitlePattern 'Library Manager' `
-OutputJson .\evidence\library-manager-ui.json
```
探针只读窗口控件,不执行点击;输出中的 `patterns` 用于确认 Verify 菜单项、Verify 对话框按钮和状态节点是否支持语义化 `InvokePattern`。
离线回归测试:
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\tests\CBBRefresh.Core.Tests.ps1
```
## 现场流程
1. 确认中心库上传动作已经完成,并记录中心库文件、CBB 名称和源工程。
2. 在 Library Manager 中定位刚上传的 CBB 条目,确认名称和来源匹配。
3. 对该条目执行原生 `Verify`,按对话框要求完成检查。
4. 每一步完成后重新读取条目状态;错误、红色标志或状态未知时停止。
5. 确认 Verify 结果、CBB 条目标志和错误状态全部为绿色。
6. 保存并关闭 Library Manager,保存校验证据和报告。
## 不允许的路径
- 不把校验当成 `Replace Symbol` 或 Part Number 替换。
- 不直接改写中心库、`.prj`、PCB、CES 或网表文件来伪造绿色状态。
- 不使用 `SendKeys`、屏幕坐标点击或无条件等待。
- 不把“弹窗关闭”或“没有报错”当作四绿成功。
后台触发说明:生产路径不会监听或注入用户真实键盘,也不会移动用户鼠标。它在私有桌面启动与 CBB 目录绑定的 `common\\win32\\bin\\ExpeditionPCB.exe <Work\\PCB\\name.pcb> -ReusableCircuit`,再绑定其 `wg` 子进程执行 Project Integration、保存和关闭;Library Manager 菜单路线仅保留为显式诊断路径。
## 2026-09-15 现场试跑记录
已在 `Skyworth_CBB_Lib\Mentor_lib_EE7.9\mentor_lib.lmc` 上完成一次只针对 CBB 校验的试跑:
- COM 只读枚举确认 `Logical-Physical` 中已有 `1GPHY_8211`、`1GPHY_RTL8211F_A`;未覆盖或删除任何条目。
- 目标条目采用用户截图所示的右键菜单 `Verify` 路径尝试执行。
- 当前版本的 Library Manager 树节点在未展开时不会通过 UI Automation 暴露 `Logical-Physical` 子项;上传工具因此在定位阶段超时。
- 两次 Verify 触发均没有出现可识别的完成对话框或状态变化,最终不得判定为绿色,报告为 `BLOCKED`。
完整证据见 `evidence\library-com-probe.json`、`evidence\library-manager-ui-after-verify.json`、`runs\verify-report-1GPHY_RTL8211F_A.json` 和 `runs\add.log`。后续自动化必须先语义化展开树节点,并为 `Verify` 建立可读的完成信号;没有完成信号时状态保持 `unknown`。
## 本地样本库验证
为区分“中心库不存在”和“Verify 接口不可用”,已在 `fixtures\sample-library` 创建隔离样本:
- `kFLOW_NONE=4` 创建的空库打开时提示 `Unable to determine flow type`,不可用于验证。
- 改用 `kFLOW_DX=1` 后生成的 `sample_verify_dx.lmc` 可以正常打开,但空库没有 CBB 条目。
- 复制生产库 `.lmc` 和 `ReusableBlocksLP` 到 `fixtures\cloned-library` 后,副本可以正常打开;对副本尝试键盘导航展开树并发送 `Verify`,仍没有可识别的 Verify 完成窗口或状态信号。
因此问题不是单纯“没有中心库”:有效 `.lmc` 能打开,真正缺口是 Library Manager CBB Verify 没有公开 COM 方法,且树节点/菜单的完成信号尚未稳定暴露。样本操作证据见 `evidence\sample-library-dx-create.json`、`evidence\sample-library-dx-ui.json`、`evidence\cloned-verify-run.json` 和 `evidence\sample-reusable-block-create.json`。
重启复测后,COM 在没有预先打开 Library Manager 的情况下仍能打开生产 `.lmc` 并枚举 CBB;随后直接启动 `.lmc` 得到 `Ready` 状态和可用的 `ATL:SysTreeView32`。因此可以排除中心库缺失,后续工作集中在树展开和 Verify 完成信号。
# CBB Refresh Verify
独立的中心库 CBB 上传后刷新校验工具。选择 `.lmc` 后自动读取 Reusable Blocks(Logical-Physical)并列出 CBB,点击校验即对每个 CBB 执行一次真实刷新:
1. 只读确认中心库条目与 `.lmc` 存在;
2. 如填写了 `LibSpec` 与 DMS 登录配置,先执行一次 `ReuseBlockImporter.exe -chkContents` 内容检查(失败即阻断,不触碰 PCB);
3. 在私有桌面上用**命令行**启动该 CBB 的 ReusableCircuit PCB(`ExpeditionPCB.exe <pcb> -ReusableCircuit`,即 Library Manager `Verify` 菜单内部执行的动作);
4. 通过 COM 核对文档身份、执行 Project Integration(四项 InSynch)、保存 Reusable Block cell 并关闭;
5. 确认中心库 `Cert` 工程已更新,并只读读取条目状态标志作为证据。
运行:
```powershell
python -m cbb_refresh_verify
```
或在本目录执行 `pip install -e .` 后使用 `cbb-refresh-verify`。
## 操作边界(不碰你的桌面)
- **不注入鼠标或键盘输入,不切换 Windows 桌面,不改写中心库源文件。** 生产路径在本次运行创建的私有桌面内启动中心库目录绑定的 ReusableCircuit PCB,随后用 COM 完成刷新、保存和关闭;只读状态桥在结束后确认 LMC 的 READY。Library Manager 菜单派发仅作为显式诊断路径保留。`tests/test_safety.py` 会在离线测试中阻止真实输入注入 API 重新进入生产代码。
- 所有自动化都跑在本进程创建的**私有 Windows 桌面**上:用户看不到窗口,光标不会被移动。
- 弹窗只认领本次运行自己启动的进程,并在该进程的私有桌面内投递 `BM_CLICK`。数据库异常恢复提示默认选择“最后一次用户保存的数据库”;其他弹窗优先确认/继续/恢复,只有 Project Integration 进度窗(仅有 Cancel)保持不动。所有弹窗文本和实际控件 ID 都写入 `dialogs.jsonl`。
- 超时或失败时,worker 所在 Job Object 连同 PCB、cscript 助手一并终止;如果外层 supervisor 先终止 worker,还会依据本次 CBB 的 PCB 命令行和启动前 PID 基线做一次定向清理。证据目录的 `events.jsonl` 会记录 `source=supervisor_cleanup` 的 `process_cleanup` 事件。
## 环境要求
| 依赖 | 说明 |
| --- | --- |
| Mentor EE 7.9.5 | `SDD_HOME`(默认 `D:\Mentor\7.9.5EE\SDD_HOME`);PCB Verify 入口优先取 `common\win32\bin\ExpeditionPCB.exe`,由其派生 `wg\win32\bin\ExpeditionPCB.exe`,仅在 common 不存在时回退到 wg |
| 设计数据库服务器端口 | iCDB 服务器必须在 **10000–10100** 内绑定一个 TCP 端口。若该区间被 Windows 保留(Hyper-V/WSL 动态预留,绑定报 `WinError 10013`),PCB 会提示 "could not bring it alive";工具会立即阻断并给出修复命令:以管理员执行 `net stop winnat && net start winnat` |
| DMS(仅可选内容检查) | 需要 `LibSpec` 与 DMS 登录配置文件;两者留空时跳过内容检查,只做 PCB 刷新 |
### Win10 / Win11 兼容性边界
Win11 不能仅凭当前开发机的离线 smoke test 宣称“Verify 已成功”;必须在安装了同一 Mentor EE 版本、同一中心库和 DMS/端口配置的机器上完成单个 CBB 的现场验收。Win10 现场失败的最新证据不是 Project Integration 或保存失败,而是 UIA `InvokePattern` 返回后只关闭了原生菜单,没有出现新的 `ExpeditionPCB.exe`;这表示 LMC 的 Verify 命令没有进入 Mentor 的 MFC 命令路由。另有一类 Win10 环境失败来自 iCDB 端口被 Hyper-V/WSL 保留,工具会在启动 PCB 前报告 `BLOCKED`。
每个条目的 `evidence/runtime.json` 会记录 Windows 产品版本、Build/UBR、Python 位数、Mentor 路径和 UIA 后端;`events.jsonl` 会同时记录 PCB 启动和清理阶段。只有同时出现 `pcb_worker_started`、`integration_status`、`saved_and_closed`、`complete`,并由状态桥复核为 `READY`,才算该机器上的成功。
Windows 版本判断以 Build 为准:`22000` 及以上归为 Win11,`10240–21999` 归为 Win10;`ProductName` 在 Win11 上可能仍显示为 `Windows 10 Pro`,不能单独用来判断系统版本。每个 worker 还会写入 `verify_mode`:默认是 `reusable_circuit_direct`。若 Win10 现场需要验证 Library Manager 原生菜单链,可在高级设置勾选“使用 Library Manager 原生 Verify(Win10 兼容测试)”,然后以单个 CBB 复测;该模式必须出现 `verify_invoke`、新的 `pcb_worker_started` 和最终 `READY`,菜单消失本身不算成功。
高级设置中的 `Mentor bin` 可填写 `lm\win32\bin`、`SDD_HOME` 或
`ReuseBlockImporter.exe` 的完整路径;工具会据此同时解析内容检查器和
`ExpeditionPCB.exe`。留空时会自动检查 `SDD_HOME`、`SDD_LM_BIN`、`CBB_MENTOR_BIN`
以及各本地盘符下常见的 `Mentor/<版本>/SDD_HOME`、`MentorGraphics/<版本>/SDD_HOME`
目录,并要求目录中至少存在一个 Mentor 可执行文件。发现结果在本次进程内缓存,
安装位置变更后重启工具即可重新扫描。
## 批量策略
每个 CBB 独立执行并写入自己的 evidence 和结果行。缺少 PCB/PRJ、内容检查失败、刷新失败或超时只影响当前项,记录 `BLOCKED/FAIL/TIMEOUT` 后继续下一项;不会因为单项失败终止整批。只有点击“当前项完成后停止”(或执行器返回 `QUEUE_STOP`)才把后续项目标为 `SKIPPED`。
GUI 中状态为 `绿色 / Ready` 的条目不能勾选、也不会进入批量队列。
### 批量状态桥(只读、默认启用)
`tools/status_bridge/bin/CbbStatusBridge32.exe` 是与 Mentor EE 7.9 x86/MFC ABI
匹配的只读桥。它通过 `--server` 常驻 JSONL 读取 `IsVerifiedReuseBlock`,每个 LMC
默认只启用一个串行桥进程,每 500 条自动轮换;超时、桥崩溃或非法响应只影响当前
CBB,并立即写入检查点。桥不可用时状态是 `UNAVAILABLE/UNKNOWN`,绝不会被当成
`READY`。主 UI 默认启用 `authoritative_status`;如需临时兼容旧版图标/文件证据,设置
`CBB_STATUS_BRIDGE_MODE=legacy`。状态桥子进程会由工具自动设置只读调用所需的
`CBB_STATUS_BRIDGE_ALLOW_PRIVATE=1`,直接在命令行运行桥时仍需显式设置该变量。
合成基线(不调用 Mentor,不代表现场耗时)如下:
| 条目数 | 完成 | 错误 | 进程轮换 | 总耗时 |
| ---: | ---: | ---: | ---: | ---: |
| 180 | 180 | 0 | 0 | 0.958 s |
| 3000 | 3000 | 0 | 5 | 16.786 s |
原始结果保存在 `runs/benchmark-180.json` 和 `runs/benchmark-3000.json`;现场
Mentor 桥耗时需在目标机器另行测量。
## 证据与日志
每次校验在 evidence 目录生成:
- `events.jsonl`:`backup` → `pcb_launch`/`pcb_worker_started`(中心库绑定的 ReusableCircuit)→ `identity_verified` → `integration_status`(四项状态流转)→ `save_helper` → `saved_and_closed`(保存标记)→ `complete`;
- `dialogs.jsonl`:被认领的弹窗及其控件 ID,未知弹窗原样记录;
- `save.log`:`LICENSE_OK / SAVE_OK / IS_SAVED / POST_SAVE_SYNCHRONIZED / CLOSE_OK / QUIT_OK`;
- `result.json`:状态、中心库标志读取结果、阻断原因;
- `image-status-map.json`:按中心库路径隔离的本机动态 `image_id` 校准快照(当前格式 `schema_version=2`);旧版本或无版本缓存会自动忽略并重新校准,日志会记录当前样本、缓存样本、Ready 主 ID、未映射 ID 和逐项决策原因;
- `backup/`:仅本地盘操作前的稳定文件副本;网络盘/UNC 跳过前置递归备份(`backup_skipped`);`database/LogFiles/tmp` 等易变目录和日志文件会排除,备份超时或失败不会阻断 PCB 校验。每个 CBB 结束后默认自动删除该目录,只保留 `events.jsonl`、`dialogs.jsonl`、`save.log` 和 `result.json` 等轻量证据。
超时采用无进展计时:界面和批量请求默认 600 秒无进展超时;它不是整个 CBB 的固定总时限,而是连续 600 秒没有可观察进展时才终止。PCB/COM 阶段切换、Project Integration 状态变化、保存标记变化和弹窗处理都会刷新计时器;重复的状态轮询不算进展。需要更快失败时仍可在界面将单项预算调低,但 30 秒只适合已确认 PCB 启动稳定的环境。
结果不会把“内容检查 PASS”冒充为中心库绿色状态:`library_flag` 只来自对条目状态的只读读取,读不到就是 `UNKNOWN`。Mentor 的树节点 `iImage` 是本机资源列表索引,不能跨安装固定写死为绿色;工具会在日志中为每个 CBB 记录 `image_id`,并从独立的 `Cert/Work` 持久化证据动态校准本机 ID。树 ID 可读时用于交叉核对,冲突不允许标记 Ready;LM 忙导致树 ID 暂时读不到时,完整的持久化证据仍可保留 Ready,缺少持久化证据的条目仍进入待校验。右键菜单文字(包括 `Unverify`)不参与状态判定。
### 状态接口审计
本机 `SDD_HOME\lm\win32\bin\LibraryManager.tlb` 的官方 COM 类型库已做只读审计。`IMGCLMReuseBlock` 公开的成员只有 `type`、`Name`、`PartitionName`,没有 `Verified`、`Ready`、`Status` 或 `IsVerified` 属性;因此不能从官方 Library Manager COM 直接读取绿色标志。
`LMCDLL70.dll` 和 `LibManagerDBPI.dll` 的导出表中可以看到 Mentor 的实际状态链:`IsVerifiedReuseBlock`、`GetStatusRBInContextOfCL`、`VerifyReuseBlock`、`UnVerifyReuseBlock` 以及 `GetReusableCircuitVerificationStatus`。反汇编确认 `IsVerifiedReuseBlock` 会调用 `GetReusableCircuitVerificationStatus`,再根据输出状态返回布尔值。这已经证明 Mentor 内部存在正式的 Verify 判定逻辑,而不是单纯依赖图标。
这些导出是 32 位 MFC/C++ ABI,参数包含 `CStringT`、内部枚举和数据库对象;当前工具是 64 位 Python,不能直接用 `ctypes` 安全调用。公开可调用的 `-chkContents` 只返回 CBB 内容检查结果,不等价于树节点 Verify 状态,也不保证刷新图标。工具现在通过同 Mentor 位数和 MFC ABI 的 C++ 只读桥接进程调用 `IsVerifiedReuseBlock`,主程序通过 JSON/标准输入输出读取状态,不伪造 `CStringT` 或按地址调用。
主 UI 默认以 `IsVerifiedReuseBlock` 返回值作为 Ready/Pending 的唯一权威状态;桥不可用、超时或错误不会变成 Ready。旧版官方文件证据、TreeView 的 `iImage`/`iSelectedImage` 和状态图标仍保留在 legacy 模式中,用于兼容和诊断,不参与默认 Ready 判定。
## 早期 CLI 入口(单独内容检查)
`Invoke-CbbVerify.ps1` 仍然可用,只做 Logical-Physical 内容检查,不做 PCB 刷新:
## 早期 CLI 入口(内容检查)
安装包自带的 Tcl 脚本 `upc_utils.tcl` 使用 `ReuseBlockImporter.exe -chkContents` 做 Logical-Physical 内容校验。这条 CLI 仍可用于快速内容检查,但它**不等于** Library Manager 的条目 Verify:
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\Invoke-CbbVerify.ps1 `
-LmcFile 'F:\path\mentor_lib.lmc' `
-BlockName 'CBB_NAME' `
-LibSpec 'YOUR_LIBSPEC' `
-DmsLoginConfig 'C:\path\dms-login-config' `
-EvidenceJson .\runs\cbb-name-verify.json
```
命令使用固定的 `-logicalType LP` 和 `-chkContents`,输出报告默认落在 `.lmc` 同目录的 `LogFiles\restorerb_RULP_<CBB_NAME>_contents.log`。`pass` 必须看到 `content checking completed successfully` 且没有错误文本;缺少 DMS 登录配置、DMS 未连接、内容检查失败或超时都会阻断。CLI 结果不会自动冒充 Library Manager 的绿色状态。
## 2026-09-28 r3 效率对比版
本轮只调整同步策略、减小高频调试落盘并增加现场计时,不更改 Mentor 启动路径、中心库路径修正、iCDB 地址处理或保存流程。
- 初始四项 `InSynch=2`:只执行一次 `ForwardAnnotate`。返回后重读四项,全部仍绿则直接 Save;若某项真正变为 `Required=1`,仅补做该项。错误、拒绝或未知状态仍阻断,不能把初始四绿当作 Verify 成功。
- 初始不是四绿:保留原来的完整四项同步路线。
- 取消弹窗代理逐次追加请求/响应文件。代理在同一台机器通过 `127.0.0.1` 的临时端口进行内存通信(随机令牌、请求关联和有界超时),不会连接网络库服务器;只写一次启动配置。
- 正常流程不生成连续窗口快照;`dialogs.jsonl` 只保存实际操作/错误,失败/超时时才保存最后的窗口现场。必要的弹窗监督仍运行,不能关闭它,否则许可/保存确认会卡住。
- `integration_status` 只在状态变化时落盘,不重复记录相同的四绿快照。
### 现场时间读法
每项的 `result.json` 和新增 `performance.json` 都包含 `timings_seconds`。批量报告和界面结束摘要也展示时间,单位为秒。
| 键 | 含义 |
| --- | --- |
| `preflight` | 前置文件/工程检查 |
| `worker_setup` | worker 启动到 Mentor 启动请求,含准备动作 |
| `pcb_startup` | Mentor 启动到 COM 文档身份确认 |
| `integration` | 整体同步阶段 |
| `forward_annotation` | 第一项调用加等待稳定的实际耗时 |
| `forward_annotation_call` | 第一项 COM 调用本身耗时,用于区分 Mentor 工作和外层等待 |
| `synch_ces` / `load_ces` / `back_annotation` | 实际执行的后续动作,跳过的项不会写成假测量的 0 秒 |
| `save` | 32 位保存 helper 中 `doc.Save()` 本身耗时 |
| `post_save_check` | 保存后四项同步状态确认耗时 |
| `close` / `quit` | 文档关闭 / 应用退出调用耗时 |
| `save_close` | 整段保存关闭,含许可、确认、状态检查 |
| `pcb_exit` | 保存关闭后到 PCB 退出和 Cert 检查 |
| `library_flag` | 最终权威状态读取 |
| `total` | 本项真实总耗时,包含清理(不含写最终报告的微小开销) |
阶段总计与动作/调用子计时重叠,不能把所有字段直接相加。父/worker 用单调时钟;helper 使用 VBScript Timer,处理午夜跨日,并明确记录计时来源。失败/超时的 `incomplete_timing_phases` 表示尚未结束的阶段,其数值只是已等待时间,不是完成耗时。
本机人工操作也约需 12 分钟,暂不将全部耗时归因于程序。界面、批量请求和同步函数的默认无进展预算统一为 **600 秒**,不是 10 分钟总时长上限;单个 Save 调用若超过 600 秒又没有任何新进展,仍会超时。重点比较 `forward_annotation_call`、`save` 和 `total`;本地测试通过不等于真实网络库已提速。
## 2026-09-29 r4 稳定性修复
- 正常执行 Save/IsSaved/Close 完成后,必须由状态桥 `IsVerifiedReuseBlock` 返回 READY/raw=1 才确认 PASS/GREEN。Cert 不参与成功门禁,成功路径不再读取 Cert 文件状态。
- 最终桥读到 PENDING 或暂时不可用时,按立即、等 3 秒、再等 5 秒进行最多三次只读查询;不重复 Verify,不把 PENDING/未知/图标假装成 READY。
- 严格过滤现场发现的无控件 IME 语言栏。原生数据库打开失败归类为 Mentor 数据库错误,仅点 No,不打开额外日志窗口。
- 启动前一次性采集已知 JobPrefs/目录诊断;临时目录缺失只警告,绝不自动修复/删除数据库或锁文件。
- 仅失败时留存已知 Mentor 原生日志的最后 128 KiB/文件及多行错误,清理后的补采集 helper 最多 8 秒,不加成功流程的日志扫描。
- 每次批次自动输出完整 `batch-*.log` 和只包含失败项的 `failures-*.log`;两者共享批次标识,界面结果摘要展示两个路径。
- 保留 600 秒无进展预算、初始四绿只点第一项、网络盘不递归备份、内存 IPC 和真实阶段计时。
变更细节、已知原生错误的边界及现场复测清单见 `docs/2026-09-29-stability-r4.md`。本地回归测试通过不代表真实 Win10/网络库已全部修复。
+49
View File
@@ -0,0 +1,49 @@
# Repository snapshot: 2026-09-29 r4
This repository contains the tested r4 source baseline, tests, packaging scripts,
project documentation, and the two verified x86 status/probe bridge executables.
The Verify execution logic is unchanged by this Git import.
## Reproduce source tests on Windows
Use Python 3.12 and install the project and developer test dependencies:
```powershell
python -m pip install -e .
python -m pip install pytest pytest-qt
python -m pytest -q
python -m compileall -q src tests
```
The source import was verified with 336 pytest cases. Tests use fake local files
and replace the production Mentor COM/process boundary where required; they do
not establish field success against a live network library.
The legacy PowerShell fixture-based tests refer to real Mentor sample libraries.
Those local samples are intentionally excluded from Git; do not substitute them
with production projects merely to run a smoke test.
## Build the Windows package
Install PyInstaller, then use the existing packaging entrypoint:
```powershell
python -m pip install pyinstaller
powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\packaging\Build-CbbRefreshVerify.ps1 -OutputDirectory dist
```
Runtime Mentor EE7.9.5EE, licensing and network-library access are supplied by the
field machine, not by this repository. The optional sibling replacement-tool
logging package is not committed here; the application has a standalone logging
fallback. Building the x86 C++ bridges from source requires the MSVC/MFC toolchain
described in tools/status_bridge/README.md; prebuilt tested bridges are included.
## Excluded local artifacts
Raw field logs, captured evidence, actual Mentor sample libraries/projects,
transient data, compiler caches, source backups and packaged distributions are
ignored. Existing local files are preserved; ignoring them is not deletion.
The tested package manifest and field-test instructions are retained in
`docs/releases`. The Windows installation ZIP remains a separate build artifact,
not a Git source file. No secrets or credentials are written into this repository.
+2
View File
@@ -0,0 +1,2 @@
$env:PYTHONPATH=(Join-Path $PSScriptRoot 'src') + ';F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src'
python -m cbb_refresh_verify
+43
View File
@@ -0,0 +1,43 @@
# CBB 中心库上传后校验操作规程
## 1. 输入与证据
本项目的 Skyworth 示例根目录是 `F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\CBB`。工程清单用于绑定 CBB 源工程和中心库条目;本工具不执行 PCB 同步,也不要求 PCB 文件作为校验输入。
每次作业至少记录:
- DxDesigner/Expedition 精确版本和构建号;
- 原理图工程路径、中心库文件和当前 CBB 标识;
- 上传后、Verify 每一步和最终的中心库状态;
- Verify 对话框的原生结果或错误号;
- 中心库条目标志和错误状态;
- 操作员、时间和截图/日志证据路径。
状态文件采用 UTF-8 JSON,状态只能是 `red`、`yellow`、`green` 或 `unknown`。
## 2. 状态和动作
| 状态键 | 校验动作 | 终态条件 |
| --- | --- | --- |
| `library_item_present` | 确认上传条目存在且名称/来源匹配 | `green` |
| `verify_result` | 对条目执行原生 `Verify` 并完成对话框 | `green` |
| `cbb_status_flag` | 确认 CBB 条目标志为绿色 | `green` |
| `error_state` | 检查没有 ERROR、Cell Name 或未处理警告 | `green` |
动作优先级按表中顺序执行。每次动作后必须重新读取条目和对话框状态;不能使用上一次读取的旧状态继续点击。
## 3. 通过条件
只有以下条件全部满足,报告才是 `PASS`:
- 四项中心库校验状态均为绿色;
- Verify 有对应的动作结果和完成时间;
- CBB 名称、源工程和中心库条目身份一致;
- 未发现 ERROR、Cell Name 或未处理警告;
- 证据文件完整且可读取。
任意状态为 `unknown`、错误、超时、路径不一致或证据缺失,报告为 `BLOCKED`。
## 4. 与上传/替换的先后关系
中心库上传由 `cbb-upload-795` 完成;上传成功后再运行本工具做 Verify 校验。若还包含普通器件替换或 PCB 同步,必须使用各自工具和独立证据目录,不能共享状态文件。
+35
View File
@@ -0,0 +1,35 @@
[CmdletBinding()]
param(
[string]$MentorHome = $env:SDD_HOME,
[string]$DmsRoot = $env:DBEDIR,
[string]$DmsLoginConfig
)
Set-StrictMode -Version Latest
$items = @()
function Add-Check([string]$Name, [bool]$Present, [string]$Detail) {
$script:items += [pscustomobject]@{ name=$Name; present=$Present; detail=$Detail }
}
if ([string]::IsNullOrWhiteSpace($MentorHome)) { Add-Check 'SDD_HOME' $false 'Environment variable is empty.' }
else { Add-Check 'SDD_HOME' (Test-Path -LiteralPath $MentorHome -PathType Container) $MentorHome }
if ([string]::IsNullOrWhiteSpace($DmsRoot)) { Add-Check 'DBEDIR' $false 'Environment variable is empty.' }
else { Add-Check 'DBEDIR' (Test-Path -LiteralPath $DmsRoot -PathType Container) $DmsRoot }
$jvmCandidates = @()
if ($DmsRoot) { $jvmCandidates += (Join-Path $DmsRoot 'jre\bin\client\jvm.dll') }
if ($MentorHome) { $jvmCandidates += (Join-Path $MentorHome 'common\win32\jre\default\bin\client\jvm.dll') }
$jvm = $jvmCandidates | Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } | Select-Object -First 1
Add-Check 'JVM' ($null -ne $jvm) ($(if ($jvm) { $jvm } else { ($jvmCandidates -join '; ') }))
$dmsBat = if ($DmsRoot) { Join-Path $DmsRoot 'bin\dmsdesktop.bat' } else { '' }
Add-Check 'DMS desktop launcher' (-not [string]::IsNullOrWhiteSpace($dmsBat) -and (Test-Path -LiteralPath $dmsBat -PathType Leaf)) $dmsBat
if ([string]::IsNullOrWhiteSpace($DmsLoginConfig)) { Add-Check 'DMS login config' $false 'Pass -DmsLoginConfig when running the real check.' }
else { Add-Check 'DMS login config' (Test-Path -LiteralPath $DmsLoginConfig -PathType Leaf) $DmsLoginConfig }
$result = [pscustomobject]@{ ready = (@($items | Where-Object { -not $_.present }).Count -eq 0); checks = @($items) }
$result | ConvertTo-Json -Depth 6
if (-not $result.ready) { exit 3 }
exit 0
+14
View File
@@ -0,0 +1,14 @@
{
"mentorVersion": "7.9.5",
"pollIntervalMilliseconds": 250,
"actionTimeoutSeconds": 120,
"requiredStates": [
"library_item_present",
"verify_result",
"cbb_status_flag",
"error_state"
],
"windowTitlePattern": "Library Manager",
"manualFallbackAllowed": true,
"writeRoute": "native_library_manager_verify"
}
+13
View File
@@ -0,0 +1,13 @@
{
"cbbRoot": "F:/Sync Tool Skyworth/Work Maps/Skyworth_CBB_Lib/CBB",
"projectList": "examples/skyworth-cbb-projects.txt",
"requiredMentorVersion": "7.9.5",
"refreshWindowTitlePattern": "Library Manager",
"refreshStates": [
"library_item_present",
"verify_result",
"cbb_status_flag",
"error_state"
],
"pcbArtifactsRequired": false
}
+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 图标、颜色、右键菜单、鼠标、键盘或固定窗口标题。
- 不并发修改同一个中心库。
- 不保存网络凭据,不覆盖或删除用户已有映射。
+15
View File
@@ -0,0 +1,15 @@
{
"schemaVersion": 1,
"project": {
"projectPath": "F:/Sync Tool Skyworth/Work Maps/Skyworth_CBB_Lib/CBB/1GPHY_RTL8211F/1GPHY_RTL8211F.prj",
"cbbName": "1GPHY_RTL8211F",
"mentorVersion": "7.9.5"
},
"states": {
"library_item_present": "green",
"verify_result": "yellow",
"cbb_status_flag": "yellow",
"error_state": "green"
},
"observations": []
}
+21
View File
@@ -0,0 +1,21 @@
{
"schemaVersion": 1,
"project": {
"projectPath": "F:/Sync Tool Skyworth/Work Maps/Skyworth_CBB_Lib/CBB/1GPHY_RTL8211F/1GPHY_RTL8211F.prj",
"cbbName": "1GPHY_RTL8211F",
"mentorVersion": "7.9.5"
},
"states": {
"library_item_present": "green",
"verify_result": "green",
"cbb_status_flag": "green",
"error_state": "green"
},
"observations": [
{
"timestampUtc": "2026-09-15T07:00:00Z",
"result": "success",
"action": "run_cbb_verify"
}
]
}
+6
View File
@@ -0,0 +1,6 @@
F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\CBB\1GPHY_8211\1GPHY_8211.prj
F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\CBB\1GPHY_RTL8211F\1GPHY_RTL8211F.prj
F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\CBB\1GPHY_RTL8211F_A\1GPHY_RTL8211F_A.prj
F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\CBB\1GPHY_YT8511C\1GPHY_YT8511C.prj
F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\CBB\1GPHY_ZX5201\2GPHY_ZX5201.prj
F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\CBB\1PEF7071_PHY\PEF7071_PHY.prj
+26
View File
@@ -0,0 +1,26 @@
param(
[string]$PythonExecutable,
[string]$OutputDirectory = 'dist'
)
$ErrorActionPreference='Stop'
$root=Split-Path $PSScriptRoot -Parent
$py = if($PythonExecutable){$PythonExecutable}elseif(Test-Path "$root\.venv\Scripts\python.exe"){"$root\.venv\Scripts\python.exe"}else{(Get-Command python).Source}
$distRoot = if ([IO.Path]::IsPathRooted($OutputDirectory)) {
[IO.Path]::GetFullPath($OutputDirectory)
} else {
[IO.Path]::GetFullPath((Join-Path $root $OutputDirectory))
}
Push-Location $root
try {
& $py -m PyInstaller --noconfirm --clean --distpath $distRoot packaging\CbbRefreshVerify.spec
if ($LASTEXITCODE -ne 0) { throw "PyInstaller failed: $LASTEXITCODE" }
$exe = Join-Path $distRoot 'CbbRefreshVerify-Background\CbbRefreshVerify.exe'
if (-not (Test-Path -LiteralPath $exe)) { throw 'PyInstaller 未生成 exe' }
$smokeRoot = Join-Path $root ('build\frozen-smoke-' + [guid]::NewGuid().ToString('N'))
$process = Start-Process -FilePath $exe -ArgumentList ('--smoke-test --data-root "' + $smokeRoot + '"') -WindowStyle Hidden -PassThru
if (-not $process.WaitForExit(30000)) { Stop-Process -Id $process.Id; throw 'Frozen UI smoke timeout' }
if ($process.ExitCode -ne 0) { throw "Frozen UI smoke failed: $($process.ExitCode)" }
$log = Get-Content -Raw -LiteralPath (Join-Path $smokeRoot 'logs\application.log')
if ($log -notmatch 'gui_smoke_window_created' -or $log -notmatch 'application_clean_shutdown exit_code=0') { throw 'Frozen UI lifecycle incomplete' }
Write-Output $exe
} finally { Pop-Location }
+28
View File
@@ -0,0 +1,28 @@
from pathlib import Path
project_root = Path(SPECPATH).parent
assets_root = project_root / 'src' / 'cbb_refresh_verify' / 'assets'
bridge_path = project_root / 'tools' / 'status_bridge' / 'bin' / 'CbbStatusBridge32.exe'
verify_probe_path = project_root / 'tools' / 'status_bridge' / 'bin' / 'VerifyProbe32.exe'
a = Analysis(
[str(project_root / 'src' / 'cbb_refresh_verify' / '__main__.py')],
pathex=[str(project_root / 'src'), r'F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src'],
binaries=(
[(str(bridge_path), 'tools/status_bridge/bin')] if bridge_path.is_file() else []
) + (
[(str(verify_probe_path), 'tools/status_bridge/bin')]
if verify_probe_path.is_file() else []
),
datas=[(str(project_root / 'src' / 'cbb_refresh_verify' / 'save_verified_block.vbs'), 'cbb_refresh_verify'),
(str(assets_root / 'cbb_refresh_verify.ico'), 'cbb_refresh_verify/assets'),
(str(assets_root / 'cbb_refresh_verify.png'), 'cbb_refresh_verify/assets'),
(str(assets_root / 'cbb_refresh_verify.svg'), 'cbb_refresh_verify/assets'),
(str(assets_root / 'dialog_rules.v1.json'), 'cbb_refresh_verify/assets')],
hiddenimports=['win32com.client','win32com.client.dynamic','pythoncom','pywintypes','win32job','pywinauto','pywinauto.uia_defines','pywinauto.controls.uiawrapper','pywinauto.win32_element_info','cbb_refresh_verify.dialog_agent','cbb_refresh_verify.dialog_probe','cbb_refresh_verify.dialog_rules','cbb_refresh_verify.ui.main_window','dx_productivity.trial_task_center.logging_setup','dx_productivity.trial_task_center.errors','dx_productivity.trial_task_center.retention'],
excludes=['PySide6.QtDesigner','PySide6.QtMultimedia','PySide6.QtMultimediaWidgets','PySide6.QtOpenGL','PySide6.QtOpenGLWidgets','PySide6.QtPdf','PySide6.QtPdfWidgets','PySide6.QtQml','PySide6.QtQuick','PySide6.QtQuickWidgets','PySide6.QtWebChannel','PySide6.QtWebEngineCore','PySide6.QtWebEngineWidgets'],
)
excluded_qt_binaries = {'icudt78.dll','icuuc.dll','qpdf.dll','qt6pdf.dll','qt6qml.dll','qt6qmlmeta.dll','qt6qmlmodels.dll','qt6qmlworkerscript.dll','qt6quick.dll','qt6quickwidgets.dll'}
a.binaries = [entry for entry in a.binaries if Path(entry[0]).name.casefold() not in excluded_qt_binaries]
pyz = PYZ(a.pure)
exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name='CbbRefreshVerify', console=False,
icon=str(assets_root / 'cbb_refresh_verify.ico'))
coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, name='CbbRefreshVerify-Background')
+16
View File
@@ -0,0 +1,16 @@
[build-system]
requires = ["setuptools>=75"]
build-backend = "setuptools.build_meta"
[project]
name = "cbb-refresh-verify"
version = "0.2.0"
requires-python = ">=3.12,<3.13"
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<0.7"]
[project.scripts]
cbb-refresh-verify = "cbb_refresh_verify.application:main"
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
+1
View File
@@ -0,0 +1 @@
__version__ = "0.1.0"
+2
View File
@@ -0,0 +1,2 @@
from cbb_refresh_verify.application import main
raise SystemExit(main())
+126
View File
@@ -0,0 +1,126 @@
from __future__ import annotations
import argparse, os, sys
from pathlib import Path
from typing import Sequence
from .runtime_logging import configure
def configure_qt_application(app):
"""Apply a predictable light palette across machines and Qt themes."""
from PySide6.QtGui import QColor, QPalette
app.setStyle('Fusion')
palette = app.palette()
colors = {
QPalette.ColorRole.Window: '#f5f6f8',
QPalette.ColorRole.WindowText: '#202124',
QPalette.ColorRole.Base: '#ffffff',
QPalette.ColorRole.AlternateBase: '#eef1f5',
QPalette.ColorRole.Text: '#202124',
QPalette.ColorRole.Button: '#eef1f5',
QPalette.ColorRole.ButtonText: '#202124',
QPalette.ColorRole.Highlight: '#2f6fed',
QPalette.ColorRole.HighlightedText: '#ffffff',
QPalette.ColorRole.ToolTipBase: '#ffffff',
QPalette.ColorRole.ToolTipText: '#202124',
QPalette.ColorRole.PlaceholderText: '#6b7280',
}
for role, color in colors.items():
palette.setColor(role, QColor(color))
app.setPalette(palette)
app.setStyleSheet(
'QWidget { color: #202124; }'
'QTableWidget, QLineEdit, QTextEdit, QSpinBox { '
'background: #ffffff; color: #202124; selection-color: #202124; }'
'QHeaderView::section { background: #e9edf2; color: #202124; }'
'QPushButton, QToolButton { color: #202124; }'
)
return app
def resolve_data_root(cli_value: Path | None) -> Path:
if cli_value is not None: return cli_value.expanduser().resolve()
if getattr(sys, "frozen", False): return Path(sys.executable).resolve().parent / "data"
local = os.environ.get("LOCALAPPDATA")
return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve()
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--dialog-agent', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--block', action='append', default=[], help=argparse.SUPPRESS)
parser.add_argument('--libspec', default='', help=argparse.SUPPRESS)
parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS)
parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS)
parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS); parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS)
args = parser.parse_args(list(argv) if argv is not None else None)
if args.collect_failure_logs:
from .verify_diagnostics import failure_logs_main
return failure_logs_main(args.collect_failure_logs)
if args.dialog_agent:
from .dialog_agent import dialog_agent_main
return dialog_agent_main(args.dialog_agent)
if args.verify_worker:
from .mentor_adapter import worker_main
import contextlib
with args.verify_worker.with_name('worker.log').open('a', encoding='utf-8') as log:
with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
return worker_main(args.verify_worker)
context = configure(resolve_data_root(args.data_root)); logger = context.logger; logger.info("application_start")
try:
if args.batch_lmc:
from .verify_runner import (VerifyRequest, native_lm_verify_enabled,
run_batch, write_batch_report, failure_report_path)
from .library_reader import read_library_fast
from .batch_status import authoritative_status_map
from .network_path import LibraryPathLease, select_library_file
with LibraryPathLease.acquire(args.batch_lmc) as lease:
mentor_path = select_library_file(lease.mentor_path)
logger.info(
'library_path_lease display=%s mentor=%s drive=%s remote=%s created=%s',
lease.display_path, mentor_path, lease.drive or '-',
lease.remote_root or '-', lease.created)
names = list(args.block)
if not names:
library = read_library_fast(
mentor_path,
status_reader=lambda path, names: authoritative_status_map(
names, path, context.root/'status-scan.jsonl'),
)
if library.error: raise RuntimeError(library.error)
names = [record.name for record in library.records if record.status != 'READY']
if not names: raise RuntimeError('中心库未读取到需要校验的 CBB')
requests = [VerifyRequest(mentor_path, name, context.root/'evidence',
libspec=args.libspec, dms_login_config=args.dms_login_config,
mentor_bin=args.mentor_bin, logging_context=context,
mapped_drive=lease.drive,
mapped_remote_root=lease.remote_root,
native_lm_verify=native_lm_verify_enabled())
for name in names]
results = run_batch(requests)
report = write_batch_report(requests, results, context.root/'reports')
logger.info('batch_report path=%s', report)
logger.info('failure_report path=%s', failure_report_path(report))
code = 0 if all(result.status == 'PASS' for result in results) else 2
logger.info('application_clean_shutdown exit_code=%s', code)
return code
from .ui.main_window import MainWindow, application_icon_path
if args.smoke_test:
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
from PySide6.QtWidgets import QApplication
app = QApplication.instance() or QApplication([sys.executable])
configure_qt_application(app)
window = MainWindow(logging_context=context); window.show()
icon_path = application_icon_path()
if icon_path.is_file():
from PySide6.QtGui import QIcon
app.setWindowIcon(QIcon(str(icon_path)))
if args.smoke_test:
from PySide6.QtCore import QTimer
logger.info('gui_smoke_window_created title=%s', window.windowTitle())
QTimer.singleShot(250, app.quit)
code = int(app.exec()); logger.info("application_clean_shutdown exit_code=%s", code); return code
except Exception: logger.exception("application_startup_failure"); return 1
finally:
for handler in logger.handlers: handler.flush()
Binary file not shown.

After

Width:  |  Height:  |  Size: 264 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">
<rect x="3" y="3" width="58" height="58" rx="10" fill="#0f766e"/>
<rect x="11" y="12" width="42" height="32" rx="4" fill="#f8fafc"/>
<rect x="15" y="16" width="34" height="24" rx="2" fill="#dbeafe"/>
<path d="M20 29l6 6 14-14" fill="none" stroke="#16a34a" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
<rect x="25" y="47" width="14" height="4" rx="2" fill="#f8fafc"/>
</svg>

After

Width:  |  Height:  |  Size: 489 B

@@ -0,0 +1,128 @@
{
"schema_version": 1,
"rules": [
{
"rule_id": "license-selector",
"priority": 100,
"category": "SAFE_RECOVERY",
"phases": ["PCB_STARTING", "LICENSE_ACQUISITION", "DOCUMENT_ATTACH"],
"semantic_all": ["select the desired product license"],
"required_control_classes": ["GXWND", "Button"],
"action": "accept_license",
"channels": ["interface", "uia_select", "win32_button_click", "win32_mouse_click", "uia_invoke"],
"postcondition": "window_gone"
},
{
"rule_id": "database-restoration",
"priority": 95,
"category": "SAFE_RECOVERY",
"phases": ["PCB_STARTING", "DATABASE_RECOVERY", "DOCUMENT_ATTACH"],
"semantic_any": ["database restoration", "last user saved database", "数据库恢复"],
"action": "restore_last_saved",
"channels": ["uia_select", "win32_button_click", "uia_invoke"],
"postcondition": "window_gone"
},
{
"rule_id": "open-lock-confirm",
"priority": 90,
"category": "SAFE_RECOVERY",
"phases": ["PCB_STARTING", "DOCUMENT_ATTACH"],
"semantic_any": ["continue to open the design with read/write access permission", "confirm that no other users have the design open"],
"action": "confirm_open_lock",
"channels": ["win32_button_click", "uia_invoke"],
"postcondition": "window_gone"
},
{
"rule_id": "forward-annotation-confirm",
"priority": 85,
"category": "SAFE_CONFIRM",
"phases": ["PCB_STARTING", "DOCUMENT_ATTACH", "PROJECT_INTEGRATION"],
"semantic_all": ["new changes are ready for forward annotation", "do you want to forward annotate now"],
"action": "confirm_forward_annotation",
"channels": ["win32_button_click", "uia_invoke"],
"postcondition": "window_gone"
},
{
"rule_id": "reusable-block-save",
"priority": 90,
"category": "SAFE_CONFIRM",
"phases": ["SAVE", "CLOSE"],
"semantic_all": ["do you want to save the reusable block cell"],
"action": "save_reusable_block",
"channels": ["win32_button_click", "uia_invoke"],
"postcondition": "window_gone"
},
{
"rule_id": "integration-progress",
"priority": 80,
"category": "OBSERVE_PROGRESS",
"phases": ["PROJECT_INTEGRATION"],
"semantic_all": ["your task is being processed", "elapsed time"],
"semantic_none": ["error", "failed"],
"postcondition": "signature_changed"
},
{
"rule_id": "project-integration-panel",
"priority": 110,
"category": "OBSERVE_PROGRESS",
"phases": ["PROJECT_INTEGRATION"],
"semantic_all": ["project file and design", "forward annotation required"],
"semantic_none": ["there were errors", "error saving the reusable block"],
"postcondition": "signature_changed"
},
{
"rule_id": "integration-error",
"priority": 120,
"category": "FATAL_ACK",
"phases": ["PROJECT_INTEGRATION"],
"semantic_all": ["there were errors"],
"action": "acknowledge_fatal",
"channels": ["win32_button_click", "uia_invoke"],
"postcondition": "window_gone",
"error_code": "PROJECT_INTEGRATION_FAILED"
},
{
"rule_id": "save-error",
"priority": 120,
"category": "FATAL_ACK",
"phases": ["SAVE", "CLOSE"],
"semantic_all": ["error saving the reusable block"],
"action": "acknowledge_fatal",
"channels": ["win32_button_click", "uia_invoke"],
"postcondition": "window_gone",
"error_code": "SAVE_REUSABLE_BLOCK_FAILED"
},
{
"rule_id": "design-server-error",
"priority": 120,
"category": "FATAL_ACK",
"phases": ["PCB_STARTING", "DOCUMENT_ATTACH"],
"semantic_any": ["could not run server", "could not bring it alive"],
"action": "acknowledge_fatal",
"channels": ["win32_button_click", "uia_invoke"],
"postcondition": "window_gone",
"error_code": "DESIGN_SERVER_FAILED"
},
{
"rule_id": "database-load-error",
"priority": 120,
"category": "FATAL_ACK",
"phases": ["PCB_STARTING", "DATABASE_RECOVERY", "DOCUMENT_ATTACH"],
"semantic_all": ["database load is being terminated"],
"action": "acknowledge_fatal",
"channels": ["win32_button_click", "uia_invoke"],
"postcondition": "window_gone",
"error_code": "DATABASE_LOAD_FAILED"
},
{
"rule_id": "tip-of-day",
"priority": 50,
"category": "SAFE_CONFIRM",
"phases": ["PCB_STARTING", "DOCUMENT_ATTACH"],
"semantic_all": ["tip of the day"],
"action": "dismiss_tip",
"channels": ["win32_button_click", "uia_invoke"],
"postcondition": "window_gone"
}
]
}
+298
View File
@@ -0,0 +1,298 @@
"""Persistent, authoritative batch status scanning for CBB libraries.
This module only reads status through the Mentor bridge. It deliberately does
not infer ``READY`` from files, icons, or previous UI observations.
"""
from __future__ import annotations
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
from typing import Iterable
from .status_bridge import (BridgeResponseError, BridgeResult, BridgeUnavailable,
StatusBridgeClient, StatusBridgeServer)
from .network_path import absolute_preserving_drive
TERMINAL_ERRORS = frozenset({"ERROR", "TIMEOUT", "UNAVAILABLE", "MALFORMED", "CRASHED"})
VALID_STATUSES = frozenset({"READY", "PENDING"}) | TERMINAL_ERRORS
@dataclass(frozen=True)
class LmcFingerprint:
path: str
size: int
mtime_ns: int
sha256: str
reusable_blocks_sha256: str
@dataclass(frozen=True)
class BatchStatusRequest:
block_name: str
lmc_file: Path
block_type: str = "RULP"
@dataclass(frozen=True)
class BatchStatusRecord:
block_name: str
status: str
source: str = ""
raw_status: int | str | None = None
detail: str = ""
fingerprint: str = ""
timestamp: str = ""
@property
def completed(self) -> bool:
return self.status in VALID_STATUSES
def to_json(self) -> dict[str, object]:
return asdict(self)
def _sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _fingerprint_tree(root: Path) -> str:
"""Fingerprint only the top-level CBB set; never descend into payloads."""
digest = hashlib.sha256()
if not root.is_dir():
digest.update(b"<missing>")
return digest.hexdigest()
entries: list[tuple[str, int]] = []
try:
children = os.scandir(root)
except OSError:
digest.update(b"<unavailable>")
return digest.hexdigest()
with children:
for entry in children:
try:
if not entry.is_dir(follow_symlinks=False):
continue
metadata = entry.stat(follow_symlinks=False)
entries.append((entry.name, metadata.st_mtime_ns))
except OSError:
entries.append((entry.name, 0))
for name, mtime_ns in sorted(entries, key=lambda item: item[0].casefold()):
digest.update(name.encode("utf-8", errors="surrogatepass"))
digest.update(b"\0" + str(mtime_ns).encode("ascii") + b"\n")
return digest.hexdigest()
def fingerprint_library(lmc: Path) -> LmcFingerprint:
"""Return a checkpoint fingerprint without reading the reusable payload.
The lightweight cache key includes LMC metadata and the top-level CBB set.
Authoritative state is still queried from Mentor; no CBB payload tree is
recursively traversed merely to decide whether a status scan can resume.
"""
path = absolute_preserving_drive(lmc)
stat = path.stat()
reusable = path.parent / "ReusableBlocksLP"
reusable_sha256 = _fingerprint_tree(reusable)
# Metadata alone is not a safe checkpoint key: on network shares and on
# file systems with coarse timestamp resolution, two different LMC
# contents can have the same size and mtime. Include the actual file
# digest so a changed central library can never reuse an old status row.
content_sha256 = _sha256_file(path)
combined = hashlib.sha256()
combined.update(content_sha256.encode("ascii"))
combined.update(b"\0" + str(stat.st_size).encode("ascii"))
combined.update(b"\0" + str(stat.st_mtime_ns).encode("ascii") + b"\0")
combined.update(reusable_sha256.encode("ascii"))
return LmcFingerprint(
path=str(path),
size=stat.st_size,
mtime_ns=stat.st_mtime_ns,
sha256=combined.hexdigest(),
reusable_blocks_sha256=reusable_sha256,
)
class BatchCheckpoint:
"""Read and append complete JSONL records without trusting torn lines."""
def __init__(self, records: dict[str, BatchStatusRecord] | None = None) -> None:
self.records = dict(records or {})
@property
def completed_names(self) -> set[str]:
return set(self.records)
def get(self, name: str) -> BatchStatusRecord | None:
return self.records.get(name)
@classmethod
def load(cls, path: Path) -> "BatchCheckpoint":
records: dict[str, BatchStatusRecord] = {}
checkpoint = Path(path)
if not checkpoint.is_file():
return cls(records)
with checkpoint.open("r", encoding="utf-8") as handle:
for line in handle:
line = line.strip()
if not line:
continue
try:
payload = json.loads(line)
except json.JSONDecodeError:
# A process may have been interrupted during the final write.
continue
if not isinstance(payload, dict):
continue
name = str(payload.get("block_name") or "").strip()
status = str(payload.get("status") or "").upper()
if not name or status not in VALID_STATUSES:
continue
records[name] = BatchStatusRecord(
block_name=name,
status=status,
source=str(payload.get("source") or ""),
raw_status=payload.get("raw_status"),
detail=str(payload.get("detail") or ""),
fingerprint=str(payload.get("fingerprint") or ""),
timestamp=str(payload.get("timestamp") or ""),
)
return cls(records)
def append(self, path: Path, record: BatchStatusRecord) -> None:
checkpoint = Path(path)
checkpoint.parent.mkdir(parents=True, exist_ok=True)
with checkpoint.open("a", encoding="utf-8", newline="\n") as handle:
handle.write(json.dumps(record.to_json(), ensure_ascii=False, separators=(",", ":")) + "\n")
handle.flush()
self.records[record.block_name] = record
def _now() -> str:
return datetime.now(timezone.utc).isoformat()
class BatchStatusSession:
"""Supervised serial bridge session with checkpoint recovery."""
def __init__(self, bridge: StatusBridgeClient, *, timeout_seconds: float = 10.0,
rotate_every: int = 500) -> None:
self.bridge = bridge
self.timeout_seconds = max(0.1, float(timeout_seconds))
self.rotate_every = max(1, int(rotate_every))
self.restart_count = 0
def scan(self, names: Iterable[str], lmc_file: Path, checkpoint_path: Path,
*, block_type: str = "RULP", resume: bool = True) -> list[BatchStatusRecord]:
fingerprint = fingerprint_library(Path(lmc_file))
if resume:
checkpoint = BatchCheckpoint.load(checkpoint_path)
else:
checkpoint = BatchCheckpoint()
checkpoint_file = Path(checkpoint_path)
checkpoint_file.parent.mkdir(parents=True, exist_ok=True)
checkpoint_file.write_text('', encoding='utf-8')
results: list[BatchStatusRecord] = []
names = tuple(str(name) for name in names)
server = self.bridge if all(callable(getattr(self.bridge, method, None))
for method in ("start", "restart", "close")) else None
if server is not None:
server.start()
try:
queried = 0
for index, name in enumerate(names):
previous = checkpoint.get(name)
if previous and previous.fingerprint == fingerprint.sha256:
results.append(previous)
continue
try:
result: BridgeResult = self.bridge.query(
Path(lmc_file), name, block_type=block_type,
timeout_seconds=self.timeout_seconds,
)
record = BatchStatusRecord(
block_name=name, status=result.status, source=result.source,
raw_status=result.raw_status, detail=result.detail,
fingerprint=fingerprint.sha256, timestamp=_now(),
)
except BridgeUnavailable as error:
record = BatchStatusRecord(block_name=name, status="UNAVAILABLE",
detail=str(error), fingerprint=fingerprint.sha256,
timestamp=_now())
except BridgeResponseError as error:
message = str(error)
lower_message = message.casefold()
unavailable = any(marker in message for marker in ("LMCDLL70", "私有 MFC", "未找到可用"))
malformed = (any(marker in message for marker in (
"路径不匹配", "请求标识不匹配", "CBB 标识不匹配",
)) or "mismatch" in lower_message)
status = ("TIMEOUT" if "超时" in message or "timeout" in lower_message
else "UNAVAILABLE" if unavailable
else "MALFORMED" if malformed else "ERROR")
record = BatchStatusRecord(block_name=name, status=status, detail=message,
fingerprint=fingerprint.sha256, timestamp=_now())
if server is not None and status not in {"UNAVAILABLE", "MALFORMED"}:
try:
server.restart()
except BridgeUnavailable:
pass
except Exception as error: # bridge failures isolate one CBB
record = BatchStatusRecord(block_name=name, status="ERROR", detail=str(error),
fingerprint=fingerprint.sha256, timestamp=_now())
if server is not None:
try:
server.restart()
except BridgeUnavailable:
pass
checkpoint.append(checkpoint_path, record)
results.append(record)
if record.status in {"UNAVAILABLE", "MALFORMED"} and index + 1 < len(names):
# Startup/protocol failures cannot be repaired by retrying
# the same request contract for every CBB.
# Preserve a terminal record for each remaining name so a
# later run can resume after the environment is fixed.
for remaining in names[index + 1:]:
unavailable_record = BatchStatusRecord(
block_name=remaining, status=record.status, detail=record.detail,
fingerprint=fingerprint.sha256, timestamp=_now(),
)
checkpoint.append(checkpoint_path, unavailable_record)
results.append(unavailable_record)
break
queried += 1
if server is not None and queried % self.rotate_every == 0 and name != names[-1]:
server.restart()
finally:
if server is not None:
server.close()
return results
def authoritative_status_map(names: Iterable[str], lmc_file: Path, checkpoint_path: Path,
*, bridge_path: Path | None = None,
timeout_seconds: float = 10.0) -> dict[str, str]:
"""Return only bridge-backed statuses for an optional UI integration.
A missing bridge is represented as ``UNAVAILABLE``/``UNKNOWN`` by callers;
it is never promoted to ``READY``.
"""
bridge = StatusBridgeServer(bridge_path, env={"CBB_STATUS_BRIDGE_ALLOW_PRIVATE": "1"})
try:
names = tuple(str(name) for name in names)
try:
records = BatchStatusSession(bridge, timeout_seconds=timeout_seconds).scan(
names, lmc_file, checkpoint_path, resume=False)
return {record.block_name: record.status for record in records}
except BridgeUnavailable:
return {name: "UNAVAILABLE" for name in names}
finally:
bridge.close()
+3
View File
@@ -0,0 +1,3 @@
"""Shared execution defaults for GUI, batch requests and integration."""
DEFAULT_TIMEOUT_SECONDS = 600
+127
View File
@@ -0,0 +1,127 @@
"""Launch automation on a private Windows desktop, never the input desktop."""
import subprocess
import win32con
import win32event
import win32job
import win32process
import win32service
def startup_desktop_name(name, *, interactive_input=False):
"""Return the CreateProcess desktop target for a worker.
The normal route gets an isolated desktop. The explicit compatibility
route inherits the caller's input desktop so Mentor's navigator can use
its physical-cursor hit test; it is never selected implicitly.
"""
if interactive_input:
return None
return 'winsta0\\' + str(name)
class DesktopWorker:
def __init__(self, command, name, *, interactive_input=False):
self.name = name
self.interactive_input = bool(interactive_input)
self.desktop = None if self.interactive_input else win32service.CreateDesktop(
name, 0, win32con.GENERIC_ALL, None)
# The worker spawns Expedition PCB and a cscript helper. Bind the whole
# tree to a job so a supervisor kill can never orphan a process.
self.job = win32job.CreateJobObject(None, '')
self.job_bound = False
self.companions = []
self.companion_pids = []
startup = win32process.STARTUPINFO()
# subprocess.STARTUPINFO does NOT pass lpDesktop to CreateProcess.
startup.lpDesktop = startup_desktop_name(name, interactive_input=self.interactive_input)
self.handle, thread, self.pid, _ = win32process.CreateProcess(
command[0], subprocess.list2cmdline(command), None, None, False,
win32con.CREATE_NO_WINDOW, None, None, startup)
thread.Close()
try:
info = win32job.QueryInformationJobObject(self.job, win32job.JobObjectExtendedLimitInformation)
info['BasicLimitInformation']['LimitFlags'] |= win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
win32job.SetInformationJobObject(self.job, win32job.JobObjectExtendedLimitInformation, info)
win32job.AssignProcessToJobObject(self.job, self.handle)
self.job_bound = True
except Exception:
# Kill-through-job is a cleanup guarantee, not a launch requirement.
self.job_bound = False
def start_companion(self, command):
startup = win32process.STARTUPINFO()
startup.lpDesktop = startup_desktop_name(
self.name, interactive_input=getattr(self, 'interactive_input', False))
handle, thread, pid, _ = win32process.CreateProcess(
command[0], subprocess.list2cmdline(command), None, None, False,
win32con.CREATE_NO_WINDOW, None, None, startup)
thread.Close()
try:
if self.job_bound:
win32job.AssignProcessToJobObject(self.job, handle)
except Exception:
try:
win32process.TerminateProcess(handle, 1)
finally:
handle.Close()
raise
self.companions.append(handle)
if not hasattr(self, 'companion_pids'):
self.companion_pids = []
self.companion_pids.append(int(pid))
return int(pid)
def poll(self):
code = win32process.GetExitCodeProcess(self.handle)
return None if code == 259 else code
@property
def returncode(self):
return self.poll()
def kill(self):
if self.job_bound:
try:
win32job.TerminateJobObject(self.job, 1)
return
except Exception:
pass
# Fallback: terminate the worker and every descendant it launched.
try:
subprocess.run(['taskkill', '/PID', str(self.pid), '/T', '/F'],
capture_output=True, timeout=20,
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
except Exception:
try:
win32process.TerminateProcess(self.handle, 1)
except Exception:
pass
def wait(self, timeout=5):
if win32event.WaitForSingleObject(self.handle, int(timeout*1000)) != win32con.WAIT_OBJECT_0:
raise TimeoutError('Automation worker did not exit')
return self.poll()
def close(self):
# A job may be unavailable on a machine where the worker is already
# assigned to another job. In that case merely closing our handles
# would orphan PCB/cscript descendants, so terminate the tree before
# releasing the desktop and job handles.
try:
if self.poll() is None:
self.kill()
except Exception:
pass
for companion in self.companions:
try:
companion.Close()
except Exception:
pass
self.companions.clear()
self.companion_pids.clear()
self.handle.Close()
# Closing the last job handle reaps any survivor thanks to
# KILL_ON_JOB_CLOSE; this also covers a supervisor crash.
self.job.Close()
if self.desktop is not None:
self.desktop.CloseDesktop()
+498
View File
@@ -0,0 +1,498 @@
"""Private-desktop dialog agent with bounded, in-memory loopback IPC."""
from __future__ import annotations
from dataclasses import asdict, dataclass
import json
import socket
from collections import deque
from pathlib import Path
import subprocess
import sys
import time
from uuid import uuid4
from .dialog_models import (
DialogPhase,
WindowSnapshot,
compatible_window_identity,
stable_fingerprint,
)
from .dialog_probe import WindowProbe, WindowProbeError
SCHEMA_VERSION = 1
class DialogAgentProtocolError(RuntimeError):
pass
@dataclass(frozen=True)
class ActionResult:
channel: str = ""
accepted_controls: tuple[int, ...] = ()
error_code: str = ""
detail: str = ""
def to_record(self):
return asdict(self)
@classmethod
def from_record(cls, record):
values = dict(record or {})
values["accepted_controls"] = tuple(values.get("accepted_controls", ()))
return cls(**values)
@dataclass(frozen=True)
class AgentPaths:
config: Path
port: int
token: str
@classmethod
def from_config(cls, config_path: Path) -> "AgentPaths":
config_path = Path(config_path)
document = json.loads(config_path.read_text(encoding="utf-8"))
if document.get("schema_version") != SCHEMA_VERSION:
raise DialogAgentProtocolError("Unsupported dialog-agent schema")
return cls(config_path, int(document["port"]), str(document["token"]))
class JsonChannel:
"""One connection, newline-framed JSON, no polling traffic written to disk."""
def __init__(self, connection):
self.connection = connection
self.buffer = b""
def send(self, document, timeout_seconds=2.0):
self.connection.settimeout(timeout_seconds)
payload = json.dumps(document, ensure_ascii=False).encode("utf-8") + b"\n"
self.connection.sendall(payload)
def receive(self, timeout_seconds):
deadline = time.monotonic() + timeout_seconds
while b"\n" not in self.buffer:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError("dialog-agent receive timed out")
self.connection.settimeout(remaining)
data = self.connection.recv(65536)
if not data:
raise EOFError("dialog-agent disconnected")
self.buffer += data
if len(self.buffer) > 8 * 1024 * 1024:
raise DialogAgentProtocolError("dialog-agent message too large")
line, self.buffer = self.buffer.split(b"\n", 1)
return json.loads(line.decode("utf-8"))
def close(self):
self.connection.close()
def dialog_agent_command(config_path: Path):
if getattr(sys, "frozen", False):
return [sys.executable, "--dialog-agent", str(config_path)]
return [sys.executable, "-m", "cbb_refresh_verify", "--dialog-agent", str(config_path)]
class DialogActionExecutor:
def __init__(self, *, win32gui=None, win32con=None, uia_wrapper=None):
if win32gui is None:
import win32gui as win32gui_module
win32gui = win32gui_module
if win32con is None:
import win32con as win32con_module
win32con = win32con_module
self.win32gui = win32gui
self.win32con = win32con
self.uia_wrapper = uia_wrapper or self._default_uia_wrapper
@staticmethod
def _default_uia_wrapper(handle):
from pywinauto import Desktop
return Desktop(backend="uia").window(handle=handle).wrapper_object()
@staticmethod
def _target(snapshot: WindowSnapshot, target: dict):
candidates = tuple(control for control in snapshot.controls if control.enabled)
if "control_id" in target:
candidates = tuple(c for c in candidates if c.control_id == int(target["control_id"]))
if "automation_id" in target:
candidates = tuple(c for c in candidates if c.automation_id == str(target["automation_id"]))
if "control_type" in target:
candidates = tuple(c for c in candidates
if c.control_type.casefold() == str(target["control_type"]).casefold())
if "name_contains" in target:
token = str(target["name_contains"]).casefold()
candidates = tuple(c for c in candidates if token in c.name.casefold())
if not target:
candidates = tuple(c for c in candidates
if c.class_name.casefold() == "button"
and c.control_id in {1, 6})
return candidates[0] if len(candidates) == 1 else None
@staticmethod
def _license_target(snapshot: WindowSnapshot):
selectors = tuple(
control for control in snapshot.controls
if control.enabled and (
"selectionitem" in {value.casefold() for value in control.patterns}
or control.control_type.casefold() == "listitem"
)
)
if any(control.selected or control.checked for control in selectors):
confirmations = tuple(
control for control in snapshot.controls
if control.enabled and control.class_name.casefold() == "button"
and control.control_id == 1
)
return confirmations[0] if len(confirmations) == 1 else None
unselected = tuple(control for control in selectors
if not control.selected and not control.checked)
if len(unselected) == 1:
return unselected[0]
# Some EE7.9 installations expose the license chooser as a GXWND
# pane without exposing any selectable child. Clicking that pane (or
# its group button) is a no-op; the dialog's default license is
# accepted by the real OK control instead. Prefer that confirmation
# target whenever no SelectionItem/ListItem was found.
confirmations = tuple(
control for control in snapshot.controls
if control.enabled and control.class_name.casefold() == "button"
and control.control_id == 1
)
if len(confirmations) == 1:
return confirmations[0]
opener = tuple(
control for control in snapshot.controls
if control.enabled and control.class_name.casefold() == "button"
and control.control_id == 5225
)
return opener[0] if len(opener) == 1 else None
@staticmethod
def _restore_database_target(snapshot: WindowSnapshot):
"""Select the user-saved database before confirming restoration."""
controls = tuple(control for control in snapshot.controls if control.enabled)
marker = ("last user saved database", "最后一次用户保存", "最后保存", "用户保存")
choice = next(
(control for control in controls
if control.control_type.casefold() in {"radiobutton", "button", "listitem"}
and any(token in control.name.casefold() for token in marker)
and not (control.selected or control.checked)),
None,
)
if choice is not None:
return choice
return next(
(control for control in controls
if control.class_name.casefold() == "button"
and control.control_id == 1),
None,
)
def _private_mouse_click(self, target, parent_hwnd: int):
"""Click a custom control on the companion's private desktop.
GX/MFC controls can ignore a zero-coordinate posted click even though
the message is accepted. Use the control's center in client coordinates
and synchronously deliver the message so the owner processes it before
the postcondition probe runs. No foreground activation or real cursor
movement is involved.
"""
left = top = right = bottom = 0
try:
rect = self.win32gui.GetClientRect(target.handle)
left, top, right, bottom = (int(value) for value in rect)
except Exception:
try:
rect = self.win32gui.GetWindowRect(target.handle)
left, top, right, bottom = (int(value) for value in rect)
right, bottom = right - left, bottom - top
left, top = 0, 0
except Exception:
# Preserve the legacy message-only fallback for probe/test
# backends that cannot provide geometry.
left = top = right = bottom = 0
x = max(0, (right - left) // 2)
y = max(0, (bottom - top) // 2)
lparam = (y << 16) | (x & 0xFFFF)
down = 0x0201 # WM_LBUTTONDOWN
up = 0x0202 # WM_LBUTTONUP
send_message = getattr(self.win32gui, "SendMessage", None)
if send_message is not None:
send_message(target.handle, down, 1, lparam)
send_message(target.handle, up, 0, lparam)
else:
self.win32gui.PostMessage(target.handle, down, 1, lparam)
self.win32gui.PostMessage(target.handle, up, 0, lparam)
# Some owner-drawn buttons do not synthesize BN_CLICKED from mouse
# messages. Forward the equivalent command to the dialog owner.
if send_message is not None and parent_hwnd:
send_message(parent_hwnd, 0x0111, int(target.control_id), target.handle)
def perform(self, snapshot: WindowSnapshot, action: dict) -> ActionResult:
channels = tuple(action.get("channels", ()))
action_name = action.get("action")
if action_name == "accept_license":
target = self._license_target(snapshot)
elif action_name == "restore_last_saved":
target = self._restore_database_target(snapshot)
else:
target = self._target(snapshot, dict(action.get("target", {})))
if target is None:
return ActionResult(error_code="ACTION_TARGET_NOT_UNIQUE",
detail="没有找到唯一且可用的目标控件")
if action_name == "restore_last_saved" and target.control_id != 1:
# EE7.9's custom radio button can block a UIA SelectionItem call
# on Win10. BM_CLICK is asynchronous and keeps the agent
# responsive; UIA remains an explicit fallback if Win32 fails.
channels = ("win32_button_click",
*(channel for channel in channels
if channel != "win32_button_click"))
for channel in channels:
if channel == "interface":
continue
if channel.startswith("uia_"):
try:
patterns = {value.casefold() for value in target.patterns}
if channel == "uia_select" and "selectionitem" not in patterns:
continue
if channel == "uia_toggle" and "toggle" not in patterns:
continue
if channel == "uia_invoke" and not (
"invoke" in patterns or target.class_name.casefold() == "button"):
continue
wrapper = self.uia_wrapper(target.handle)
if channel == "uia_invoke":
wrapper.invoke()
elif channel == "uia_select":
wrapper.select()
elif channel == "uia_toggle":
wrapper.toggle()
else:
continue
return ActionResult(channel=channel, accepted_controls=(target.control_id,))
except Exception:
continue
if channel == "win32_button_click" and target.class_name.casefold() == "button":
try:
self.win32gui.PostMessage(
target.handle, getattr(self.win32con, "BM_CLICK", 0x00F5), 0, 0)
return ActionResult(channel=channel, accepted_controls=(target.control_id,))
except Exception:
continue
if channel == "win32_mouse_click" and action.get("action") == "accept_license":
try:
self._private_mouse_click(target, snapshot.hwnd)
return ActionResult(channel=channel, accepted_controls=(target.control_id,))
except Exception:
continue
return ActionResult(error_code="ACTION_CHANNEL_FAILED",
detail=f"动作通道均失败: {', '.join(channels)}")
class DialogAgentServer:
def __init__(self, paths: AgentPaths, *, probe, executor=None, poll_seconds=0.02):
self.paths = paths
self.probe = probe
self.executor = executor or DialogActionExecutor()
self.poll_seconds = max(0.005, float(poll_seconds))
self.sequence = 0
self.requests = deque(maxlen=1)
self.responses = deque(maxlen=1)
connection = socket.create_connection(("127.0.0.1", paths.port), timeout=10)
connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.channel = JsonChannel(connection)
self.channel.send({"token": paths.token}, timeout_seconds=10)
self.observed_snapshots = {}
@classmethod
def from_config(cls, config_path: Path, *, probe, executor=None):
return cls(AgentPaths.from_config(config_path), probe=probe, executor=executor)
def _response(self, request, **values):
self.sequence += 1
response = {
"schema_version": SCHEMA_VERSION,
"request_id": request.get("request_id", ""),
"sequence": self.sequence,
**values,
}
self.channel.send(response)
self.responses.append(response)
def _handle(self, request):
self.requests.append(request)
if request.get("schema_version") != SCHEMA_VERSION:
self._response(request, error_code="DIALOG_PROTOCOL_ERROR", detail="schema_version 不匹配")
return
try:
phase = DialogPhase(request["phase"])
if request.get("op") == "observe":
snapshots = self.probe.capture(phase)
self.observed_snapshots.clear()
for snapshot in snapshots:
self.observed_snapshots[stable_fingerprint(snapshot)] = snapshot
self._response(request, result=[item.to_record() for item in snapshots])
return
if request.get("op") == "perform":
expected = self.observed_snapshots.get(request.get("fingerprint"))
if expected is None:
self._response(request, result=ActionResult(
error_code="STALE_DIALOG",
detail="窗口已消失或指纹已变化",
).to_record())
return
else:
# The supervisor just observed this exact fingerprint. A
# second full child/UIA scan can block on EE7.9's native
# license dialog, so execute against that validated
# snapshot instead of rescanning it synchronously.
snapshot = expected
result = self.executor.perform(snapshot, dict(request.get("action", {})))
self._response(request, result=result.to_record())
return
self._response(request, error_code="DIALOG_PROTOCOL_ERROR", detail="未知 op")
except WindowProbeError as error:
self._response(request, error_code=error.error_code, detail=error.detail)
except Exception as error:
self._response(request, error_code="DIALOG_AGENT_ERROR", detail=str(error))
def serve_once(self) -> bool:
try:
request = self.channel.receive(self.poll_seconds)
except TimeoutError:
return False
self._handle(request)
return True
def serve_forever(self) -> int:
try:
while True:
self.serve_once()
except (EOFError, ConnectionError, OSError):
return 0
finally:
self.channel.close()
class DialogAgentClient:
def __init__(self, paths: AgentPaths, listener, *, timeout_seconds: float = 2.0):
self.paths = paths
self.listener = listener
self.channel = None
self.timeout_seconds = max(0.1, float(timeout_seconds))
self.last_sequence = 0
@classmethod
def prepare(cls, root: Path, *, desktop_name: str, timeout_seconds=2.0):
root = Path(root)
root.mkdir(parents=True, exist_ok=True)
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
listener.bind(("127.0.0.1", 0))
listener.listen(1)
paths = AgentPaths(root / "dialog-agent.json", listener.getsockname()[1], uuid4().hex)
paths.config.write_text(json.dumps({
"schema_version": SCHEMA_VERSION, "transport": "loopback_memory",
"desktop_name": desktop_name, "port": paths.port, "token": paths.token,
}, ensure_ascii=False), encoding="utf-8")
return cls(paths, listener, timeout_seconds=timeout_seconds)
except Exception:
listener.close()
raise
@classmethod
def start(cls, worker, root: Path, *, timeout_seconds: float = 2.0):
client = cls.prepare(root, desktop_name=worker.name, timeout_seconds=timeout_seconds)
try:
worker.start_companion(dialog_agent_command(client.paths.config))
client._accept(timeout_seconds=10.0)
return client
except Exception:
client.close()
raise
def _accept(self, timeout_seconds):
if self.channel is not None:
return
self.listener.settimeout(timeout_seconds)
connection, _address = self.listener.accept()
channel = JsonChannel(connection)
try:
connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
hello = channel.receive(timeout_seconds)
if hello.get("token") != self.paths.token:
raise DialogAgentProtocolError("dialog-agent authentication failed")
self.channel = channel
except Exception:
channel.close()
raise
finally:
self.listener.close()
def _request(self, op: str, phase: DialogPhase, **values):
try:
self._accept(self.timeout_seconds)
request_id = uuid4().hex
self.channel.send({
"schema_version": SCHEMA_VERSION, "request_id": request_id,
"op": op, "phase": phase.value, **values,
}, self.timeout_seconds)
response = self.channel.receive(self.timeout_seconds)
except (OSError, EOFError) as error:
raise DialogAgentProtocolError(f"DIALOG_PROTOCOL_TIMEOUT_OR_DISCONNECT: {op}: {error}") from error
if response.get("schema_version") != SCHEMA_VERSION:
raise DialogAgentProtocolError("响应 schema_version 不匹配")
if response.get("request_id") != request_id:
raise DialogAgentProtocolError("响应 request_id 不匹配")
sequence = int(response.get("sequence", 0))
if sequence <= self.last_sequence:
raise DialogAgentProtocolError("响应 sequence 非单调递增")
self.last_sequence = sequence
if response.get("error_code"):
raise DialogAgentProtocolError(f"{response['error_code']}: {response.get('detail', '')}")
return response.get("result")
def observe(self, phase: DialogPhase) -> tuple[WindowSnapshot, ...]:
result = self._request("observe", phase)
return tuple(WindowSnapshot.from_record(item) for item in (result or ()))
def perform(self, *, hwnd: int, fingerprint: str, action: dict,
phase: DialogPhase) -> ActionResult:
result = self._request(
"perform", phase, hwnd=int(hwnd), fingerprint=str(fingerprint), action=dict(action))
return ActionResult.from_record(result)
def close(self):
if self.channel is not None:
self.channel.close()
self.listener.close()
class _CurrentDesktop:
@staticmethod
def EnumDesktopWindows():
import win32gui
handles = []
def collect(handle, _context):
handles.append(int(handle))
return True
win32gui.EnumWindows(collect, None)
return tuple(handles)
def dialog_agent_main(config_path: Path) -> int:
import pythoncom
pythoncom.CoInitialize()
try:
probe = WindowProbe(desktop=_CurrentDesktop())
return DialogAgentServer.from_config(config_path, probe=probe).serve_forever()
finally:
pythoncom.CoUninitialize()
+146
View File
@@ -0,0 +1,146 @@
"""Stable, serializable window evidence used by dialog supervision."""
from __future__ import annotations
from dataclasses import asdict, dataclass
from enum import Enum
import hashlib
import json
import re
from typing import Any
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, ...] = ()
@classmethod
def from_record(cls, record: dict[str, Any]) -> "ControlSnapshot":
values = dict(record)
values["patterns"] = tuple(values.get("patterns", ()))
return cls(**values)
@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, ...]
owner_hwnd: int = 0
diagnostics: tuple[str, ...] = ()
@property
def texts(self) -> tuple[str, ...]:
return tuple(control.name for control in self.controls if control.name.strip())
@property
def signature(self) -> tuple[object, ...]:
return (
self.title,
tuple((control.control_id, control.class_name, control.name,
control.enabled, control.checked, control.selected)
for control in self.controls),
)
def to_record(self) -> dict[str, Any]:
record = asdict(self)
record["phase"] = self.phase.value
return record
@classmethod
def from_record(cls, record: dict[str, Any]) -> "WindowSnapshot":
values = dict(record)
values["phase"] = DialogPhase(values["phase"])
values["controls"] = tuple(ControlSnapshot.from_record(item)
for item in values.get("controls", ()))
values["diagnostics"] = tuple(values.get("diagnostics", ()))
return cls(**values)
@dataclass(frozen=True)
class RuleDecision:
rule_id: str = ""
category: str = ""
action: str = ""
channels: tuple[str, ...] = ()
target: tuple[tuple[str, object], ...] = ()
postcondition: str = ""
error_code: str = ""
detail: str = ""
_GUID = re.compile(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", re.I)
_WINDOWS_PATH = re.compile(r"(?i)(?:[a-z]:\\|\\\\)[^\s|]+")
_NUMBER = re.compile(r"\b\d+(?:\.\d+)?\b")
_SPACE = re.compile(r"\s+")
def normalize_text(value: str) -> str:
text = str(value or "").casefold()
text = _GUID.sub("<guid>", text)
text = _WINDOWS_PATH.sub("<path>", text)
text = _NUMBER.sub("<n>", text)
return _SPACE.sub(" ", text).strip()
def stable_fingerprint(snapshot: WindowSnapshot) -> str:
controls = sorted(
(
control.control_id,
control.class_name.casefold(),
normalize_text(control.name),
control.automation_id.casefold(),
control.control_type.casefold(),
tuple(sorted(pattern.casefold() for pattern in control.patterns)),
)
for control in snapshot.controls
)
stable = {
"phase": snapshot.phase.value,
"process_name": snapshot.process_name.casefold(),
"process_role": snapshot.process_role.casefold(),
"window_class": snapshot.window_class.casefold(),
"owned": bool(snapshot.owner_hwnd),
"title": normalize_text(snapshot.title),
"controls": controls,
}
payload = json.dumps(stable, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
def compatible_window_identity(expected: WindowSnapshot, actual: WindowSnapshot) -> bool:
"""Allow transient control-tree changes without accepting a new window."""
return (
expected.hwnd == actual.hwnd
and expected.pid == actual.pid
and expected.process_name.casefold() == actual.process_name.casefold()
and expected.window_class.casefold() == actual.window_class.casefold()
and normalize_text(expected.title) == normalize_text(actual.title)
)
+296
View File
@@ -0,0 +1,296 @@
"""Class-agnostic Win32 discovery with best-effort UI Automation evidence."""
from __future__ import annotations
from pathlib import Path
import queue
import threading
from typing import Callable
from .dialog_models import ControlSnapshot, DialogPhase, WindowSnapshot
class WindowProbeError(RuntimeError):
def __init__(self, error_code: str, detail: str) -> None:
self.error_code = error_code
self.detail = detail
super().__init__(detail)
def _winerror(error: BaseException):
value = getattr(error, "winerror", None)
if value is None:
arguments = getattr(error, "args", ())
value = arguments[0] if arguments else None
return value
def _bounded_call(function: Callable[[], object], timeout_seconds: float):
results: queue.Queue[tuple[bool, object]] = queue.Queue(maxsize=1)
def run():
try:
results.put((True, function()))
except BaseException as error:
results.put((False, error))
threading.Thread(target=run, daemon=True, name="CbbDialogUiaProbe").start()
try:
succeeded, value = results.get(timeout=max(0.05, float(timeout_seconds)))
except queue.Empty as error:
raise TimeoutError(f"UIA probe exceeded {timeout_seconds:g}s") from error
if not succeeded:
raise value
return value
class PywinautoUiaFacade:
"""Read UIA metadata only; this class never activates or clicks a window."""
@staticmethod
def _patterns(wrapper) -> tuple[str, ...]:
names = []
for name, attribute in (
("Invoke", "iface_invoke"),
("SelectionItem", "iface_selection_item"),
("Toggle", "iface_toggle"),
("Value", "iface_value"),
("Window", "iface_window"),
):
try:
if getattr(wrapper, attribute, None) is not None:
names.append(name)
except Exception:
pass
return tuple(names)
def controls(self, hwnd: int):
from pywinauto import Desktop
root = Desktop(backend="uia").window(handle=int(hwnd)).wrapper_object()
wrappers = (root, *root.descendants())
records = []
for wrapper in wrappers:
info = wrapper.element_info
selected = False
checked = False
try:
selected = bool(wrapper.is_selected())
except Exception:
pass
try:
checked = int(wrapper.get_toggle_state()) != 0
except Exception:
pass
records.append({
"handle": int(getattr(info, "handle", 0) or 0),
"control_id": int(getattr(info, "control_id", 0) or 0),
"class_name": str(getattr(info, "class_name", "") or ""),
"name": str(getattr(info, "name", "") or ""),
"automation_id": str(getattr(info, "automation_id", "") or ""),
"control_type": str(getattr(info, "control_type", "") or ""),
"enabled": bool(getattr(info, "enabled", True)),
"selected": selected,
"checked": checked,
"patterns": self._patterns(wrapper),
})
return tuple(records)
def _default_process_name_reader(pid: int) -> str:
import win32api
import win32con
import win32process
access = getattr(win32con, "PROCESS_QUERY_LIMITED_INFORMATION", 0x1000)
try:
process = win32api.OpenProcess(access, False, int(pid))
except Exception:
process = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ,
False, int(pid))
try:
try:
path = win32process.QueryFullProcessImageName(process, 0)
except Exception:
path = win32process.GetModuleFileNameEx(process, 0)
return Path(path).name
finally:
process.Close()
def _process_role(process_name: str) -> str:
lowered = process_name.casefold()
if any(token in lowered for token in ("expedition", "xtremedesign", "mgcpcb")):
return "pcb"
if "license" in lowered:
return "license"
if any(token in lowered for token in ("cdbsvr", "designserver", "cscript")):
return "helper"
return "unknown"
class WindowProbe:
_IGNORED_WINDOW_CLASSES = frozenset({
"uac_inputindicatoroverlaywnd",
"uac input indicator",
# ExpeditionPCB creates this hidden browser host while attaching a
# document. It is not a modal prompt, and UIA probing it repeatedly
# costs up to the full probe timeout while producing no actionable
# controls (the latest failed runs generated dozens of these records).
"internet explorer_hidden",
})
def __init__(self, *, desktop, win32gui=None, win32process=None,
process_name_reader=None, uia=None, uia_timeout_seconds: float = 0.75) -> None:
if win32gui is None:
import win32gui as win32gui_module
win32gui = win32gui_module
if win32process is None:
import win32process as win32process_module
win32process = win32process_module
self.desktop = desktop
self.win32gui = win32gui
self.win32process = win32process
self.process_name_reader = process_name_reader or _default_process_name_reader
self.uia = uia or PywinautoUiaFacade()
self.uia_timeout_seconds = max(0.05, float(uia_timeout_seconds))
def _handles(self) -> tuple[int, ...]:
try:
return tuple(int(handle) for handle in self.desktop.EnumDesktopWindows())
except Exception as error:
if _winerror(error) in (0, 2):
return ()
raise WindowProbeError("WINDOW_ENUM_ERROR", f"EnumDesktopWindows 失败: {error}") from error
def _children(self, hwnd: int) -> tuple[int, ...]:
children: list[int] = []
def collect(handle, _context):
children.append(int(handle))
return True
try:
self.win32gui.EnumChildWindows(hwnd, collect, None)
except Exception as error:
raise WindowProbeError("WINDOW_ENUM_ERROR", f"EnumChildWindows({hwnd}) 失败: {error}") from error
return tuple(children)
def _win32_control(self, hwnd: int) -> ControlSnapshot:
gui = self.win32gui
class_name = str(gui.GetClassName(hwnd) or "")
checked = False
selected = False
try:
if class_name.casefold() == "button":
checked = bool(gui.SendMessage(hwnd, 0x00F0, 0, 0))
elif class_name.casefold() == "combobox":
selected = int(gui.SendMessage(hwnd, 0x0147, 0, 0)) >= 0
elif class_name.casefold() == "listbox":
selected = int(gui.SendMessage(hwnd, 0x0188, 0, 0)) >= 0
except Exception:
pass
return ControlSnapshot(
handle=int(hwnd),
control_id=int(gui.GetDlgCtrlID(hwnd)),
class_name=class_name,
name=str(gui.GetWindowText(hwnd) or ""),
control_type=class_name,
enabled=bool(gui.IsWindowEnabled(hwnd)),
checked=checked,
selected=selected,
)
@staticmethod
def _merge_controls(win32_controls, uia_records):
by_handle = {control.handle: control for control in win32_controls}
extras = []
for record in uia_records:
uia_control = ControlSnapshot.from_record(dict(record))
existing = by_handle.get(uia_control.handle)
if existing is None:
extras.append(uia_control)
continue
by_handle[uia_control.handle] = ControlSnapshot(
handle=existing.handle,
control_id=uia_control.control_id or existing.control_id,
class_name=uia_control.class_name or existing.class_name,
name=uia_control.name or existing.name,
automation_id=uia_control.automation_id,
control_type=uia_control.control_type or existing.control_type,
enabled=uia_control.enabled,
selected=uia_control.selected or existing.selected,
checked=uia_control.checked or existing.checked,
patterns=uia_control.patterns,
)
ordered = [by_handle[control.handle] for control in win32_controls]
return tuple((*ordered, *extras))
def capture_one(self, hwnd: int, phase: DialogPhase) -> WindowSnapshot | None:
gui = self.win32gui
try:
if not gui.IsWindowVisible(hwnd):
return None
pid = int(self.win32process.GetWindowThreadProcessId(hwnd)[1])
try:
process_name = str(self.process_name_reader(pid) or "")
except Exception:
process_name = ""
controls = tuple(self._win32_control(child) for child in self._children(hwnd))
diagnostics = []
try:
uia_records = _bounded_call(lambda: self.uia.controls(hwnd), self.uia_timeout_seconds)
controls = self._merge_controls(controls, uia_records)
except Exception as error:
diagnostics.append(f"UIA_ERROR: {error}")
owner = 0
try:
owner = int(gui.GetWindow(hwnd, 4) or 0) # GW_OWNER
except Exception:
pass
return WindowSnapshot(
hwnd=int(hwnd),
pid=pid,
process_name=process_name,
process_role=_process_role(process_name),
window_class=str(gui.GetClassName(hwnd) or ""),
title=str(gui.GetWindowText(hwnd) or ""),
phase=phase,
controls=controls,
owner_hwnd=owner,
diagnostics=tuple(diagnostics),
)
except WindowProbeError:
raise
except Exception:
return None
def capture(self, phase: DialogPhase) -> tuple[WindowSnapshot, ...]:
snapshots = []
for hwnd in self._handles():
try:
window_class = str(self.win32gui.GetClassName(hwnd) or "")
except Exception:
window_class = ""
lowered_class = window_class.casefold()
# Windows may create input-indicator overlays and MFC Afx host
# windows on the private desktop while PCB is starting. They are
# not actionable dialogs and probing their child/UIA trees can
# block the JSONL agent after a license dialog closes.
if lowered_class in self._IGNORED_WINDOW_CLASSES or lowered_class.startswith("afx:"):
continue
if phase == DialogPhase.PROJECT_INTEGRATION:
try:
title = str(self.win32gui.GetWindowText(hwnd) or "").strip().casefold()
except Exception:
title = ""
# Project Integration is the COM-driven owner panel. It is
# intentionally observed through ProjectIntegration.Status;
# probing its very large MFC/UIA tree can block the dialog
# agent and falsely abort a valid refresh.
if title in {"project integration", "项目集成"}:
continue
snapshot = self.capture_one(hwnd, phase)
if snapshot is not None:
snapshots.append(snapshot)
return tuple(snapshots)
+224
View File
@@ -0,0 +1,224 @@
"""Declarative, phase-aware rules for Mentor dialog decisions."""
from __future__ import annotations
from dataclasses import dataclass, fields, replace
import json
from pathlib import Path
import sys
from typing import Any, Sequence
from .dialog_models import DialogPhase, RuleDecision, WindowSnapshot, normalize_text
class RuleConfigError(ValueError):
pass
def default_rules_path() -> Path:
source = Path(__file__).resolve().parent / "assets" / "dialog_rules.v1.json"
frozen = Path(getattr(sys, "_MEIPASS", source.parent.parent)) / "cbb_refresh_verify" / "assets" / "dialog_rules.v1.json"
return frozen if frozen.is_file() else source
_CATEGORIES = {"OBSERVE_PROGRESS", "SAFE_RECOVERY", "SAFE_CONFIRM", "FATAL_ACK"}
_CHANNELS = {"interface", "uia_invoke", "uia_select", "uia_toggle", "win32_button_click", "win32_mouse_click"}
_POSTCONDITIONS = {"", "window_gone", "control_selected", "control_enabled", "signature_changed", "next_phase"}
@dataclass(frozen=True)
class DialogRule:
rule_id: str
priority: int
category: str
phases: tuple[DialogPhase, ...]
enabled: bool = True
process_names: tuple[str, ...] = ()
process_roles: tuple[str, ...] = ()
window_classes: tuple[str, ...] = ()
semantic_all: tuple[str, ...] = ()
semantic_any: tuple[str, ...] = ()
semantic_none: tuple[str, ...] = ()
required_control_types: tuple[str, ...] = ()
required_control_classes: tuple[str, ...] = ()
action: str = ""
channels: tuple[str, ...] = ()
target: tuple[tuple[str, object], ...] = ()
postcondition: str = ""
error_code: str = ""
def _tuple_strings(value: Any) -> tuple[str, ...]:
if value is None:
return ()
if not isinstance(value, list):
raise RuleConfigError("规则列表字段必须是 JSON array")
return tuple(str(item) for item in value)
def _parse_rule(raw: dict[str, Any]) -> DialogRule:
known = {field.name for field in fields(DialogRule)}
unknown = set(raw) - known
if unknown:
raise RuleConfigError(f"规则包含未知字段: {', '.join(sorted(unknown))}")
try:
phases = tuple(DialogPhase(value) for value in raw["phases"])
target_value = raw.get("target", {})
if not isinstance(target_value, dict):
raise RuleConfigError("target 必须是 JSON object")
rule = DialogRule(
rule_id=str(raw["rule_id"]),
priority=int(raw["priority"]),
category=str(raw["category"]),
phases=phases,
enabled=bool(raw.get("enabled", True)),
process_names=_tuple_strings(raw.get("process_names")),
process_roles=_tuple_strings(raw.get("process_roles")),
window_classes=_tuple_strings(raw.get("window_classes")),
semantic_all=_tuple_strings(raw.get("semantic_all")),
semantic_any=_tuple_strings(raw.get("semantic_any")),
semantic_none=_tuple_strings(raw.get("semantic_none")),
required_control_types=_tuple_strings(raw.get("required_control_types")),
required_control_classes=_tuple_strings(raw.get("required_control_classes")),
action=str(raw.get("action", "")),
channels=_tuple_strings(raw.get("channels")),
target=tuple(sorted(target_value.items())),
postcondition=str(raw.get("postcondition", "")),
error_code=str(raw.get("error_code", "")),
)
except (KeyError, TypeError, ValueError) as error:
if isinstance(error, RuleConfigError):
raise
raise RuleConfigError(f"无效规则: {raw.get('rule_id', '<missing>')}: {error}") from error
if not rule.rule_id or not rule.phases:
raise RuleConfigError("rule_id 和 phases 不能为空")
if rule.category not in _CATEGORIES:
raise RuleConfigError(f"未知 category: {rule.category}")
unknown_channels = set(rule.channels) - _CHANNELS
if unknown_channels:
raise RuleConfigError(f"未知 action channel: {', '.join(sorted(unknown_channels))}")
if rule.postcondition not in _POSTCONDITIONS:
raise RuleConfigError(f"未知 postcondition: {rule.postcondition}")
return rule
def _read_document(path: Path) -> list[dict[str, Any]]:
try:
document = json.loads(Path(path).read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as error:
raise RuleConfigError(f"无法读取规则 {path}: {error}") from error
if document.get("schema_version") != 1:
raise RuleConfigError(f"不支持的 schema_version: {document.get('schema_version')}")
rules = document.get("rules")
if not isinstance(rules, list):
raise RuleConfigError("rules 必须是 JSON array")
return rules
def load_rules(default_path: Path, override_path: Path | None = None) -> tuple[DialogRule, ...]:
ordered: list[str] = []
raw_by_id: dict[str, dict[str, Any]] = {}
for raw in _read_document(default_path):
rule_id = str(raw.get("rule_id", ""))
if not rule_id or rule_id in raw_by_id:
raise RuleConfigError(f"默认规则 ID 重复或为空: {rule_id}")
ordered.append(rule_id)
raw_by_id[rule_id] = dict(raw)
if override_path is not None and Path(override_path).is_file():
seen: set[str] = set()
for override in _read_document(override_path):
rule_id = str(override.get("rule_id", ""))
if not rule_id or rule_id in seen:
raise RuleConfigError(f"现场规则 ID 重复或为空: {rule_id}")
seen.add(rule_id)
if rule_id in raw_by_id:
raw_by_id[rule_id].update(override)
else:
ordered.append(rule_id)
raw_by_id[rule_id] = dict(override)
return tuple(_parse_rule(raw_by_id[rule_id]) for rule_id in ordered)
def _semantic_text(snapshot: WindowSnapshot) -> str:
return normalize_text(" ".join((snapshot.title, *snapshot.texts)))
def _matches(rule: DialogRule, snapshot: WindowSnapshot, *, include_phase: bool) -> bool:
if not rule.enabled:
return False
if include_phase and snapshot.phase not in rule.phases:
return False
if rule.process_names and snapshot.process_name.casefold() not in {v.casefold() for v in rule.process_names}:
return False
if rule.process_roles and snapshot.process_role.casefold() not in {v.casefold() for v in rule.process_roles}:
return False
if rule.window_classes and snapshot.window_class.casefold() not in {v.casefold() for v in rule.window_classes}:
return False
semantic = _semantic_text(snapshot)
all_tokens = tuple(normalize_text(value) for value in rule.semantic_all)
any_tokens = tuple(normalize_text(value) for value in rule.semantic_any)
none_tokens = tuple(normalize_text(value) for value in rule.semantic_none)
if any(token not in semantic for token in all_tokens):
return False
if any_tokens and not any(token in semantic for token in any_tokens):
return False
if any(token in semantic for token in none_tokens):
return False
control_types = {control.control_type.casefold() for control in snapshot.controls}
control_classes = {control.class_name.casefold() for control in snapshot.controls}
if not {value.casefold() for value in rule.required_control_types}.issubset(control_types):
return False
if not {value.casefold() for value in rule.required_control_classes}.issubset(control_classes):
return False
return True
def _decision(rule: DialogRule) -> RuleDecision:
return RuleDecision(
rule_id=rule.rule_id,
category=rule.category,
action=rule.action,
channels=rule.channels,
target=rule.target,
postcondition=rule.postcondition,
error_code=rule.error_code if rule.category == "FATAL_ACK" else "",
)
def decide(snapshot: WindowSnapshot, rules: Sequence[DialogRule]) -> RuleDecision:
# Windows Text Services Framework language-bar window exposed by Mentor's
# process is not a Mentor modal: it has no controls and must not abort a run.
if (snapshot.window_class.casefold() == 'cicerouiwndframe'
and normalize_text(snapshot.title) == 'tf_floatinglangbar_wndtitle'
and not snapshot.controls):
return RuleDecision(rule_id='ime-floating-language-bar', category='OBSERVE_PROGRESS')
combined = normalize_text(' '.join((snapshot.title, *snapshot.texts)))
if ('problem encountered while opening one of the database files' in combined
and 'loading of the job has failed' in combined):
return RuleDecision(
rule_id='mentor-database-open-failed', category='FATAL_ACK',
action='acknowledge_fatal',
channels=('win32_button_click', 'uia_invoke'),
target=(('control_id', 7),), postcondition='window_gone',
error_code='MENTOR_DATABASE_LOAD_FAILED', detail=' | '.join(snapshot.texts))
matches = [rule for rule in rules if _matches(rule, snapshot, include_phase=True)]
if matches:
best_priority = max(rule.priority for rule in matches)
best = [rule for rule in matches if rule.priority == best_priority]
if len(best) != 1:
ids = ", ".join(sorted(rule.rule_id for rule in best))
return RuleDecision(error_code="DIALOG_RULE_CONFLICT", detail=f"同优先级规则冲突: {ids}")
return _decision(best[0])
out_of_phase = [rule for rule in rules if _matches(rule, snapshot, include_phase=False)]
if out_of_phase:
best = max(out_of_phase, key=lambda rule: rule.priority)
return RuleDecision(
rule_id=best.rule_id,
category=best.category,
error_code="DIALOG_OUT_OF_PHASE",
detail=f"规则 {best.rule_id} 不允许在阶段 {snapshot.phase.value} 执行",
)
return RuleDecision(
error_code="UNKNOWN_DIALOG",
detail=" | ".join(snapshot.texts) or snapshot.title or "无标题窗口",
)
+624
View File
@@ -0,0 +1,624 @@
"""Confirmed, bounded handling for modal dialogs owned by a Verify job."""
from __future__ import annotations
from dataclasses import dataclass
import time
from typing import Protocol, Sequence
from .dialog_agent import ActionResult
from .dialog_models import DialogPhase, WindowSnapshot, stable_fingerprint
from .dialog_rules import DialogRule, decide
class DialogObservationError(RuntimeError):
def __init__(self, error_code: str, detail: str) -> None:
self.error_code = str(error_code)
self.detail = str(detail)
super().__init__(self.detail)
@dataclass(frozen=True)
class DialogControl:
handle: int
control_id: int
class_name: str
text: str
enabled: bool
checked: bool = False
selected: bool = False
@dataclass(frozen=True)
class DialogSnapshot:
hwnd: int
pid: int
title: str
controls: tuple[DialogControl, ...]
@property
def texts(self) -> tuple[str, ...]:
return tuple(control.text for control in self.controls if control.text.strip())
@property
def signature(self) -> tuple[object, ...]:
return (
self.title,
tuple((control.control_id, control.class_name, control.text,
control.enabled, control.checked, control.selected)
for control in self.controls),
)
def as_log_record(self) -> dict[str, object]:
return {
"hwnd": self.hwnd,
"pid": self.pid,
"title": self.title,
"controls": [
{
"handle": control.handle,
"id": control.control_id,
"class": control.class_name,
"text": control.text,
"enabled": control.enabled,
"checked": control.checked,
"selected": control.selected,
}
for control in self.controls
],
}
@dataclass(frozen=True)
class DialogDecision:
action: str = ""
error_code: str = ""
detail: str = ""
observe_only: bool = False
@dataclass(frozen=True)
class DialogPollResult:
activity: bool = False
action_sent: bool = False
resolved: bool = False
error_code: str = ""
detail: str = ""
snapshot: DialogSnapshot | None = None
accepted_controls: tuple[int, ...] = ()
action: str = ""
rule_id: str = ""
channel: str = ""
observed_snapshots: tuple[object, ...] = ()
class DialogBackend(Protocol):
def observe(self) -> Sequence[DialogSnapshot]: ...
def perform(self, snapshot: DialogSnapshot, action: str) -> Sequence[int]: ...
class AgentDialogBackend:
"""Adapt the private-desktop JSONL client to the supervisor backend."""
def __init__(self, client) -> None:
self.client = client
def observe(self, phase: DialogPhase):
return self.client.observe(phase)
def perform(self, snapshot: WindowSnapshot, action: dict, phase: DialogPhase) -> ActionResult:
return self.client.perform(
hwnd=snapshot.hwnd,
fingerprint=stable_fingerprint(snapshot),
action=action,
phase=phase,
)
class Win32DialogBackend:
"""Observe and act on dialogs without moving focus, cursor, or desktop."""
def __init__(self, pids, *, desktop=None, win32gui=None, win32process=None,
win32con=None) -> None:
if win32gui is None:
import win32gui as win32gui_module
win32gui = win32gui_module
if win32process is None:
import win32process as win32process_module
win32process = win32process_module
if win32con is None:
import win32con as win32con_module
win32con = win32con_module
self.pids = pids
self.desktop = desktop
self.win32gui = win32gui
self.win32process = win32process
self.win32con = win32con
def _allowed_pids(self) -> set[int]:
values = self.pids() if callable(self.pids) else self.pids
return {int(value) for value in (values or ()) if value is not None}
def _window_handles(self) -> tuple[int, ...]:
if self.desktop is not None:
try:
return tuple(int(handle) for handle in self.desktop.EnumDesktopWindows())
except Exception as error:
# EnumDesktopWindows returns FALSE when a newly-created
# private desktop has no windows yet. pywin32 exposes that
# normal startup state as winerror 0 or, on some Windows
# builds, stale winerror 2. Keep polling until the worker
# creates its first window; genuine access/handle failures
# remain structured errors below.
error_code = getattr(error, 'winerror', None)
if error_code is None:
arguments = getattr(error, 'args', ())
error_code = arguments[0] if arguments else None
if error_code in (0, 2):
return ()
raise DialogObservationError(
"WINDOW_ENUM_ERROR", f"EnumDesktopWindows 失败: {error}"
) from error
handles: list[int] = []
def collect(handle, _context):
handles.append(int(handle))
return True
try:
self.win32gui.EnumWindows(collect, None)
except Exception as error:
raise DialogObservationError(
"WINDOW_ENUM_ERROR", f"EnumWindows 失败: {error}"
) from error
return tuple(handles)
def _children(self, hwnd: int) -> tuple[int, ...]:
children: list[int] = []
def collect(handle, _context):
children.append(int(handle))
return True
try:
self.win32gui.EnumChildWindows(hwnd, collect, None)
except Exception as error:
raise DialogObservationError(
"WINDOW_ENUM_ERROR", f"EnumChildWindows({hwnd}) 失败: {error}"
) from error
return tuple(children)
def _control(self, hwnd: int) -> DialogControl:
gui = self.win32gui
class_name = str(gui.GetClassName(hwnd) or "")
checked = False
selected = False
try:
if class_name.casefold() == "button":
checked = bool(gui.SendMessage(hwnd, 0x00F0, 0, 0)) # BM_GETCHECK
elif class_name.casefold() == "combobox":
selected = int(gui.SendMessage(hwnd, 0x0147, 0, 0)) >= 0 # CB_GETCURSEL
elif class_name.casefold() == "listbox":
selected = int(gui.SendMessage(hwnd, 0x0188, 0, 0)) >= 0 # LB_GETCURSEL
except Exception:
pass
return DialogControl(
handle=int(hwnd),
control_id=int(gui.GetDlgCtrlID(hwnd)),
class_name=class_name,
text=str(gui.GetWindowText(hwnd) or ""),
enabled=bool(gui.IsWindowEnabled(hwnd)),
checked=checked,
selected=selected,
)
def observe(self) -> tuple[DialogSnapshot, ...]:
gui = self.win32gui
allowed = self._allowed_pids()
snapshots = []
for hwnd in self._window_handles():
try:
if not gui.IsWindowVisible(hwnd) or gui.GetClassName(hwnd) != "#32770":
continue
pid = int(self.win32process.GetWindowThreadProcessId(hwnd)[1])
# A newly-created private desktop is already an isolation
# boundary and can contain helper-process dialogs. On the
# input desktop, retain strict PID scoping.
if self.desktop is None and pid not in allowed:
continue
controls = tuple(self._control(child) for child in self._children(hwnd))
snapshots.append(DialogSnapshot(
hwnd=int(hwnd), pid=pid, title=str(gui.GetWindowText(hwnd) or ""),
controls=controls,
))
except DialogObservationError:
raise
except Exception:
# A window can disappear between enumeration and inspection.
continue
return tuple(snapshots)
@staticmethod
def _has_any(value: str, tokens: tuple[str, ...]) -> bool:
lowered = value.casefold()
return any(token in lowered for token in tokens)
def _buttons(self, snapshot: DialogSnapshot) -> tuple[DialogControl, ...]:
return tuple(control for control in snapshot.controls
if control.class_name.casefold() == "button" and control.enabled)
def _click(self, control: DialogControl) -> int:
self.win32gui.PostMessage(control.handle, getattr(self.win32con, "BM_CLICK", 0x00F5), 0, 0)
return control.control_id
def perform(self, snapshot: DialogSnapshot, action: str) -> tuple[int, ...]:
buttons = self._buttons(snapshot)
positive = ("yes", "ok", "continue", "retry", "restore", "open", "use", "load",
"是", "确定", "继续", "重试", "恢复", "打开", "使用", "加载")
negative = ("cancel", "no", "abort", "stop", "close", "exit",
"否", "取消", "终止", "停止", "关闭", "退出")
if action == "restore_last_saved":
marker = ("last user saved database", "最后一次用户保存", "最后保存", "用户保存")
selection = next((button for button in buttons if self._has_any(button.text, marker)), None)
accepted = []
if selection is not None and not selection.checked:
return (self._click(selection),)
confirm = next((button for button in buttons
if button.control_id == 1 or button.text.casefold() in ("ok", "确定")), None)
if confirm is not None:
accepted.append(self._click(confirm))
return tuple(accepted)
if action == "accept_license":
selector_button = next(
(control for control in buttons
if self._has_any(control.text, ("select the desired product license",
"选择所需产品许可证"))),
None,
)
selectors = tuple(
control for control in snapshot.controls
if (control.class_name.casefold() in {"combobox", "listbox"}
or (control.class_name.casefold() == "button"
and control.control_id not in {1, 2, 6, 7}))
)
if selector_button is not None:
# EE7.9.5 exposes the product-license chooser as a Button
# next to a custom GXWND list. Open it first; the selected
# license is only observable after the chooser is expanded.
return (self._click(selector_button),)
if selectors and not any(control.selected or control.checked for control in selectors):
return ()
if action == "decline_database_log":
# Do not fall back to the affirmative button and open a log viewer.
target = next((button for button in buttons if button.control_id == 7), None)
return (self._click(target),) if target is not None else ()
preferred_ids = {
"accept_license": (1,),
"save_reusable_block": (6,),
"confirm_open_lock": (6,),
"dismiss_tip": (1, 2),
"acknowledge_fatal": (1, 2),
}.get(action, ())
target = next((button for control_id in preferred_ids for button in buttons
if button.control_id == control_id), None)
if target is None:
target = next((button for button in buttons
if self._has_any(button.text, positive)
and not self._has_any(button.text, negative)), None)
if target is None and action in {"dismiss_tip", "acknowledge_fatal"}:
target = next((button for button in buttons
if not self._has_any(button.text, negative)), None)
return (self._click(target),) if target is not None else ()
@dataclass
class _PendingDialog:
signature: tuple[object, ...]
action: str
attempts: int = 0
last_attempt: float = float("-inf")
@dataclass
class _PendingRuleAction:
hwnd: int
fingerprint: str
rule_id: str
action: str
channels: tuple[str, ...]
target: tuple[tuple[str, object], ...]
postcondition: str
signature: tuple[object, ...]
attempts: int = 0
last_attempt: float = float("-inf")
_FATAL_MARKERS = (
("error saving the reusable block", "SAVE_REUSABLE_BLOCK_FAILED"),
("could not run server", "DESIGN_SERVER_FAILED"),
("could not bring it alive", "DESIGN_SERVER_FAILED"),
("database load is being terminated", "DATABASE_LOAD_FAILED"),
("there were errors", "PROJECT_INTEGRATION_FAILED"),
)
def classify_dialog(snapshot: DialogSnapshot) -> DialogDecision:
title = snapshot.title.casefold()
joined = " ".join(snapshot.texts).casefold()
combined = f"{title} {joined}"
if ("problem encountered while opening one of the database files" in combined
and "loading of the job has failed" in combined):
return DialogDecision(action="decline_database_log",
error_code="MENTOR_DATABASE_LOAD_FAILED",
detail=" | ".join(snapshot.texts) or snapshot.title)
for marker, error_code in _FATAL_MARKERS:
if marker in combined:
return DialogDecision(
action="acknowledge_fatal",
error_code=error_code,
detail=" | ".join(snapshot.texts) or snapshot.title,
)
if "your task is being" in joined and "elapsed time" in joined:
return DialogDecision(observe_only=True)
if ("database restoration" in title
or ("restore database" in joined and "last user saved database" in joined)
or "数据库恢复" in joined):
return DialogDecision(action="restore_last_saved")
if "select the desired product license" in joined:
return DialogDecision(action="accept_license")
if "do you want to save the reusable block cell" in joined:
return DialogDecision(action="save_reusable_block")
if ("continue to open the design with read/write access permission" in joined
or "confirm that no other users have the design open" in joined):
return DialogDecision(action="confirm_open_lock")
if "tip of the day" in combined:
return DialogDecision(action="dismiss_tip")
return DialogDecision(
error_code="UNKNOWN_DIALOG",
detail=" | ".join(snapshot.texts) or snapshot.title or "无标题弹窗",
)
class DialogSupervisor:
"""Retry known actions and declare success only after state transition."""
def __init__(self, backend: DialogBackend, *, retry_seconds: float = 0.75,
max_attempts: int = 3, clock=None,
rules: Sequence[DialogRule] | None = None) -> None:
self.backend = backend
self.retry_seconds = max(0.0, float(retry_seconds))
self.max_attempts = max(1, int(max_attempts))
self._clock = clock or time.monotonic
self._pending: dict[int, _PendingDialog] = {}
self._observed: dict[int, tuple[object, ...]] = {}
self.rules = tuple(rules) if rules is not None else None
self._rule_pending: dict[tuple[str, str], _PendingRuleAction] = {}
self._rule_observed: dict[str, tuple[object, ...]] = {}
@staticmethod
def _candidate(snapshot: WindowSnapshot) -> bool:
class_name = snapshot.window_class.casefold()
return bool(
snapshot.owner_hwnd
or class_name in {"#32770", "gxwnd", "taskdialog"}
or snapshot.process_role == "license"
)
@staticmethod
def _postcondition_met(pending: _PendingRuleAction,
snapshot: WindowSnapshot | None,
phase: DialogPhase) -> bool:
if pending.postcondition == "window_gone":
return snapshot is None
if snapshot is None:
return False
if pending.postcondition == "signature_changed":
return snapshot.signature != pending.signature
if pending.postcondition == "control_selected":
return any(control.selected or control.checked for control in snapshot.controls)
if pending.postcondition == "control_enabled":
return any(control.enabled for control in snapshot.controls)
if pending.postcondition == "next_phase":
return snapshot.phase != phase
return snapshot.signature != pending.signature
def _poll_rules(self, phase: DialogPhase) -> DialogPollResult:
try:
all_snapshots = tuple(self.backend.observe(phase))
except Exception as error:
code = getattr(error, "error_code", "DIALOG_PROTOCOL_ERROR")
detail = getattr(error, "detail", str(error))
return DialogPollResult(error_code=code, detail=detail)
snapshots = tuple(snapshot for snapshot in all_snapshots if self._candidate(snapshot))
current_by_hwnd = {snapshot.hwnd: snapshot for snapshot in snapshots}
resolved = False
activity = False
for key, pending in tuple(self._rule_pending.items()):
snapshot = current_by_hwnd.get(pending.hwnd)
if self._postcondition_met(pending, snapshot, phase):
del self._rule_pending[key]
resolved = True
activity = True
now = self._clock()
for snapshot in snapshots:
fingerprint = stable_fingerprint(snapshot)
decision = decide(snapshot, self.rules or ())
if (decision.error_code
and decision.category not in {"FATAL_ACK", "OBSERVE_PROGRESS"}):
return DialogPollResult(
activity=True,
resolved=resolved,
error_code=decision.error_code,
detail=decision.detail,
snapshot=snapshot,
rule_id=decision.rule_id,
observed_snapshots=snapshots,
)
if decision.category == "OBSERVE_PROGRESS":
previous = self._rule_observed.get(fingerprint)
if previous != snapshot.signature:
self._rule_observed[fingerprint] = snapshot.signature
activity = True
continue
key = (snapshot.hwnd, decision.rule_id)
pending = self._rule_pending.get(key)
if pending is None:
pending = _PendingRuleAction(
hwnd=snapshot.hwnd,
fingerprint=fingerprint,
rule_id=decision.rule_id,
action=decision.action,
channels=decision.channels,
target=decision.target,
postcondition=decision.postcondition,
signature=snapshot.signature,
)
self._rule_pending[key] = pending
activity = True
if now - pending.last_attempt < self.retry_seconds:
continue
if pending.attempts >= self.max_attempts:
return DialogPollResult(
activity=activity,
resolved=resolved,
error_code="DIALOG_ACTION_STUCK",
detail=(f"规则 {pending.rule_id} 已尝试 {pending.attempts} 次,"
"动作后置条件仍未满足"),
snapshot=snapshot,
action=pending.action,
rule_id=pending.rule_id,
observed_snapshots=snapshots,
)
action_payload = {
"action": pending.action,
"channels": list(pending.channels),
"target": dict(pending.target),
"postcondition": pending.postcondition,
"rule_id": pending.rule_id,
}
result = self.backend.perform(snapshot, action_payload, phase)
pending.attempts += 1
pending.last_attempt = now
fatal_code = decision.error_code if decision.category == "FATAL_ACK" else ""
error_code = fatal_code or result.error_code
detail = decision.detail or result.detail
return DialogPollResult(
activity=True,
action_sent=bool(result.accepted_controls),
resolved=resolved,
error_code=error_code,
detail=detail,
snapshot=snapshot,
accepted_controls=result.accepted_controls,
action=pending.action,
rule_id=pending.rule_id,
channel=result.channel,
observed_snapshots=snapshots,
)
active_fingerprints = {stable_fingerprint(snapshot) for snapshot in snapshots}
for fingerprint in tuple(self._rule_observed):
if fingerprint not in active_fingerprints:
del self._rule_observed[fingerprint]
activity = True
resolved = True
return DialogPollResult(activity=activity, resolved=resolved,
observed_snapshots=snapshots)
def poll(self, phase: DialogPhase | None = None) -> DialogPollResult:
if phase is not None:
if self.rules is None:
raise RuntimeError("phase-aware dialog supervision requires rules")
return self._poll_rules(phase)
try:
snapshots = tuple(self.backend.observe())
except DialogObservationError as error:
return DialogPollResult(
error_code=error.error_code,
detail=error.detail,
)
current = {snapshot.hwnd: snapshot for snapshot in snapshots}
resolved = False
activity = False
for hwnd, pending in tuple(self._pending.items()):
snapshot = current.get(hwnd)
if snapshot is None or snapshot.signature != pending.signature:
del self._pending[hwnd]
resolved = True
activity = True
for hwnd in tuple(self._observed):
if hwnd not in current:
del self._observed[hwnd]
resolved = True
activity = True
now = self._clock()
for snapshot in snapshots:
decision = classify_dialog(snapshot)
if decision.error_code:
accepted: tuple[int, ...] = ()
if decision.action:
accepted = tuple(int(value) for value in self.backend.perform(snapshot, decision.action))
return DialogPollResult(
activity=True,
action_sent=bool(accepted),
resolved=resolved,
error_code=decision.error_code,
detail=decision.detail,
snapshot=snapshot,
accepted_controls=accepted,
action=decision.action,
)
if decision.observe_only:
previous = self._observed.get(snapshot.hwnd)
if previous != snapshot.signature:
self._observed[snapshot.hwnd] = snapshot.signature
activity = True
continue
if snapshot.hwnd in self._observed:
del self._observed[snapshot.hwnd]
activity = True
pending = self._pending.get(snapshot.hwnd)
if pending is None:
pending = _PendingDialog(snapshot.signature, decision.action)
self._pending[snapshot.hwnd] = pending
activity = True
if now - pending.last_attempt < self.retry_seconds:
continue
if pending.attempts >= self.max_attempts:
return DialogPollResult(
activity=activity,
resolved=resolved,
error_code="DIALOG_STUCK",
detail=(f"弹窗操作 {pending.action} 已尝试 {pending.attempts} 次仍未关闭: "
f"{' | '.join(snapshot.texts) or snapshot.title}"),
snapshot=snapshot,
action=pending.action,
)
accepted = tuple(int(value) for value in self.backend.perform(snapshot, pending.action))
pending.attempts += 1
pending.last_attempt = now
return DialogPollResult(
activity=activity,
action_sent=bool(accepted),
resolved=resolved,
snapshot=snapshot,
accepted_controls=accepted,
action=pending.action,
)
return DialogPollResult(activity=activity, resolved=resolved)
+121
View File
@@ -0,0 +1,121 @@
"""State-driven Project Integration refresh; no UI or COM creation here."""
import time
from .mentor_adapter import ActivityDeadline
from .defaults import DEFAULT_TIMEOUT_SECONDS
ACTIONS = (
('ForwardAnnotation', 'ForwardAnnotate'),
('SynchCES', 'SynchCES'),
('LoadCES', 'LoadCES'),
('BackAnnotation', 'BackAnnotate'),
)
class IntegrationError(RuntimeError):
pass
def value(obj, name):
result = getattr(obj, name)
return result() if callable(result) else result
def statuses(pi):
return {name: int(value(pi, name + 'Status')) for name, _ in ACTIONS}
def refresh_integration(pi, *, emit=lambda **event: None, settle_seconds=5, timeout_seconds=DEFAULT_TIMEOUT_SECONDS,
error_reader=None, sleep=time.sleep, clock=None):
clock = clock or time.monotonic
def check_error():
if error_reader is None:
return
detail = error_reader()
if detail:
emit(stage='integration_error', detail=detail)
raise IntegrationError(f'Project Integration error: {detail}')
deadline = ActivityDeadline(timeout_seconds, clock=clock) if timeout_seconds is not None else None
in_flight = {}
executed = set()
action_history = []
green_entry = None
previous_state = None
while True:
check_error()
state = statuses(pi)
if state != previous_state:
emit(stage='integration_status', statuses=state)
if green_entry is None:
green_entry = all(status == 2 for status in state.values())
if previous_state is not None and state != previous_state and deadline is not None:
deadline.touch()
previous_state = state
for name, status in state.items():
# NoCES=3 is recorded as unsupported, never claimed green.
if status not in (1, 2):
raise IntegrationError(f'{name}: unsupported status {status}')
for name in tuple(in_flight):
if state[name] == 2:
started, call_elapsed = in_flight.pop(name)
emit(stage='integration_action_complete', action=dict(ACTIONS)[name], status=2,
elapsed_seconds=round(clock() - started, 6),
call_elapsed_seconds=round(call_elapsed, 6))
# When all four lamps start green, mirror the manual refresh: one
# ForwardAnnotate, then only repair statuses that actually become Required.
# Non-green entry keeps the previously validated four-action route.
refreshed = ('ForwardAnnotation' in executed if green_entry
else len(executed) == len(ACTIONS))
if refreshed and not in_flight and all(status == 2 for status in state.values()):
emit(stage='integration_complete', statuses=state, actions=action_history,
policy='green_first_only' if green_entry else 'required_full_sequence')
return state
if deadline is not None and deadline.expired():
raise IntegrationError('Project Integration timeout')
if in_flight:
sleep(.2)
continue
action_started = False
for name, method in ACTIONS:
if state[name] == 2 and (name in executed or
(green_entry and name != 'ForwardAnnotation')):
continue
allowed = bool(value(pi, 'Is' + name + 'Allowed'))
# A green item still has to receive one Verify refresh attempt.
# Mentor may report the capability as false for that item; this
# flag is a gate only for a genuinely Required (status=1) item.
if state[name] != 2 and not allowed:
emit(stage='integration_action_unavailable', action=method,
initial_status=state[name], reason='mentor_not_allowed')
raise IntegrationError(f'{name}: required but not allowed')
emit(stage='integration_action', action=method, initial_status=state[name],
reason='required_verification' if name not in executed else 'resynchronize')
started = clock()
try:
action_result = value(pi, method)
except Exception as error:
emit(stage='integration_error', action=method, detail=str(error),
elapsed_seconds=round(clock() - started, 6))
raise IntegrationError(f'{method}: {error}') from error
if not action_result:
raise IntegrationError(f'{method} returned false')
in_flight[name] = (started, clock() - started)
executed.add(name)
action_history.append(method)
action_started = True
if deadline is not None:
deadline.touch()
until = clock() + settle_seconds
previous = state
while statuses(pi) == state and clock() < until:
check_error()
sleep(.2)
if statuses(pi) != previous:
if deadline is not None:
deadline.touch()
break # Every operation may change other statuses; always reread.
if not action_started:
sleep(.2)
@@ -0,0 +1,299 @@
"""Library Manager's native CBB Verify entry point.
The Verify action belongs to Library Manager, not to an independently started
Expedition PCB process. This module runs inside the worker's private Windows
desktop, resolves the exact LMC and CBB tree item, opens that item's native
context menu, and invokes the unique Verify menu item through UI Automation.
"""
from __future__ import annotations
from dataclasses import dataclass
import ctypes
from pathlib import Path
import os
import subprocess
import time
from typing import Any
def same_path(first: str | Path, second: str | Path) -> bool:
return os.path.normcase(os.path.abspath(str(first))) == os.path.normcase(os.path.abspath(str(second)))
def _sdd_home_from_bin(value: str | Path | None) -> Path | None:
if not value:
return None
candidate = Path(value)
if candidate.is_file():
candidate = candidate.parent
for parent in (candidate, *candidate.parents):
if parent.name.casefold() == "sdd_home":
return parent
return None
def library_manager_path(mentor_bin: str | Path | None = None) -> Path:
from .mentor_paths import discover_sdd_home
discovered = discover_sdd_home(mentor_bin)
if discovered is not None:
return discovered / "lm" / "win32" / "bin" / "LibraryManager.exe"
root = _sdd_home_from_bin(mentor_bin)
if root is None:
configured = os.environ.get("SDD_HOME", r"D:\Mentor\7.9.5EE\SDD_HOME")
root = Path(configured)
return root / "lm" / "win32" / "bin" / "LibraryManager.exe"
def _library_processes() -> list[tuple[int, str, str]]:
import win32com.client
service = win32com.client.GetObject("winmgmts:")
return [
(int(process.ProcessId), str(process.ExecutablePath or ""), str(process.CommandLine or ""))
for process in service.ExecQuery(
"SELECT ProcessId, ExecutablePath, CommandLine "
"FROM Win32_Process WHERE Name='LibraryManager.exe'"
)
]
def _fresh_library_pids(before: set[int], current: set[int], launcher_pid: int) -> set[int]:
"""Return only this invocation's LM processes, including its launcher."""
return (set(current) - {int(pid) for pid in before}) | {int(launcher_pid)}
def _rect_edges(rect) -> tuple[int, int, int, int]:
"""Return rectangle edges from Win32 tuples or pywinauto RECT objects."""
if all(hasattr(rect, name) for name in ("left", "top", "right", "bottom")):
return tuple(int(getattr(rect, name)) for name in ("left", "top", "right", "bottom"))
left, top, right, bottom = rect
return int(left), int(top), int(right), int(bottom)
def _menu_click_lparam(menu_rect, item_rect) -> int:
"""Encode a popup-menu item center as client-relative mouse coordinates."""
menu_left, menu_top, _menu_right, _menu_bottom = _rect_edges(menu_rect)
item_left, item_top, item_right, item_bottom = _rect_edges(item_rect)
x = max(0, ((item_left + item_right) // 2) - menu_left)
y = max(0, ((item_top + item_bottom) // 2) - menu_top)
return ((y & 0xFFFF) << 16) | (x & 0xFFFF)
def _post_menu_item_click(menu_handle: int, item_rect) -> None:
"""Activate a popup item with messages on the private desktop only."""
import win32con
import win32gui
popup_rect = win32gui.GetWindowRect(int(menu_handle))
lparam = _menu_click_lparam(popup_rect, item_rect)
win32gui.PostMessage(int(menu_handle), win32con.WM_MOUSEMOVE, 0, lparam)
win32gui.PostMessage(int(menu_handle), win32con.WM_LBUTTONDOWN,
win32con.MK_LBUTTON, lparam)
win32gui.PostMessage(int(menu_handle), win32con.WM_LBUTTONUP, 0, lparam)
def _post_tree_context_menu(tree_handle: int, lparam: int) -> None:
import win32con
import win32gui
# Library Manager resolves the hit item from its preceding mouse-move
# message. Sending the complete private-window message sequence avoids
# activating the user's input desktop.
win32gui.PostMessage(tree_handle, win32con.WM_MOUSEMOVE, 0, lparam)
win32gui.PostMessage(tree_handle, win32con.WM_RBUTTONDOWN, win32con.MK_RBUTTON, lparam)
win32gui.PostMessage(tree_handle, win32con.WM_RBUTTONUP, 0, lparam)
def _invoke_interactive_verify(target, item) -> None:
"""Prepare the real input desktop before opening the native context menu.
EE7.9 resolves the context-menu owner from the focused Library Manager
window and the physical cursor position. Selecting the tree item alone
is not sufficient: UI Automation may report a successful right-click
while the MFC command is never dispatched. Keep this sequence isolated
to the explicit interactive compatibility path.
"""
target.set_focus()
item.select()
item.click_input(button='right')
def _find_target_window(desktop: Any, library: Path, fresh_pids: set[int]):
for window in desktop.windows():
try:
title = window.window_text()
if not window.is_visible() or not title.startswith("Library Manager:"):
continue
if not same_path(title.split(":", 1)[1].strip(), library):
continue
if window.process_id() in fresh_pids:
return window
except Exception:
continue
return None
@dataclass
class LibraryVerifySession:
target: Any
process: subprocess.Popen
tree_handle: int
library: Path
block_name: str
def close(self) -> None:
try:
self.target.close()
except Exception:
pass
try:
if self.process.poll() is None:
self.process.terminate()
self.process.wait(timeout=5)
except Exception:
try:
self.process.kill()
except Exception:
pass
def launch_library_verify(
library: str | Path,
block_name: str,
emit,
deadline: float,
*,
mentor_bin: str | Path | None = None,
interactive_input: bool = False,
) -> LibraryVerifySession:
"""Invoke Verify from the exact Library Manager LMC context."""
from pywinauto import Desktop
from pywinauto.controls.common_controls import TreeViewWrapper
from pywinauto import win32defines
library = Path(library)
executable = library_manager_path(mentor_bin)
if not executable.is_file():
raise RuntimeError(f"找不到 Library Manager: {executable}")
before = {pid for pid, _, _ in _library_processes()}
launch_kwargs = {}
if not interactive_input:
launch_kwargs['creationflags'] = getattr(subprocess, "CREATE_NO_WINDOW", 0)
process = subprocess.Popen([str(executable), str(library)], **launch_kwargs)
emit(
stage="lm_started",
lm_pid=int(process.pid),
command=[str(executable), str(library)],
library=str(library),
block=block_name,
)
session = None
try:
# The worker already owns a private desktop. Enumerating this desktop
# never changes the user's foreground window or cursor.
desktop = Desktop(backend="win32")
while time.monotonic() < deadline:
current = {pid for pid, _, _ in _library_processes()}
fresh = _fresh_library_pids(before, current, int(process.pid))
target = _find_target_window(desktop, library, fresh)
if target is not None:
break
time.sleep(0.2)
else:
raise RuntimeError("后台 Library Manager 窗口未就绪")
emit(
stage="lm_ready",
lm_pid=int(target.process_id()),
library=str(library),
block=block_name,
)
trees = [window for window in target.descendants() if "TreeView" in window.class_name()]
if len(trees) != 1:
raise RuntimeError("后台 Library Manager 导航树不唯一")
tree = TreeViewWrapper(trees[0].handle)
root_name = library.name
item = tree.get_item(
["Central Libraries", root_name, "Reusable Blocks", "Logical-Physical", block_name],
exact=True,
)
item.ensure_visible()
tree.send_message(win32defines.TVM_SELECTITEM, win32defines.TVGN_CARET, item.elem)
if not item.is_selected():
raise RuntimeError(f"后台 CBB 选择校验失败: {block_name}")
ui_window = Desktop(backend="uia").window(handle=target.handle)
matches = [
entry for entry in ui_window.descendants(control_type="TreeItem")
if entry.window_text() == block_name
]
if len(matches) != 1:
raise RuntimeError(f"后台无法唯一定位 CBB: {block_name}")
if interactive_input:
# EE7.9's navigator determines the context-menu owner from the
# physical cursor, ignoring the posted lParam. This branch is
# explicit and inherits the caller's input desktop; the default
# production path remains isolated and message-only.
_invoke_interactive_verify(target, item)
else:
rect = matches[0].rectangle()
lparam = ctypes.c_uint32(
((int(rect.mid_point().y) & 0xFFFF) << 16) | (int(rect.mid_point().x) & 0xFFFF)
).value
_post_tree_context_menu(tree.handle, lparam)
time.sleep(0.25)
menus = [menu for menu in Desktop(backend="uia").windows(control_type="Menu") if menu.is_visible()]
actions = [
(menu, entry)
for menu in menus
for entry in menu.descendants(control_type="MenuItem")
if entry.window_text().replace("&", "") == "Verify"
and entry.is_enabled()
]
if len(actions) != 1:
raise RuntimeError(f"{block_name}: 后台 Verify 菜单不可用")
menu, verify_action = actions[0]
from .post_verify_diagnostics import invoke_with_evidence
invoke_with_evidence(
verify_action.invoke,
lambda event: emit(**event),
{
'library': str(library), 'block': block_name,
'lm_pid': target.process_id(),
'menu_automation_id': str(verify_action.element_info.automation_id or ''),
},
)
# Win10's UIA provider can acknowledge InvokePattern on the native
# #32768 popup without dispatching the MFC command. The private
# popup coordinate message is retained only as the final observed
# fallback; menu closure is diagnostic evidence, not Verify success.
menu_handle = int(getattr(getattr(menu, 'element_info', None), 'handle', 0) or
getattr(menu, 'handle', 0) or 0)
if menu_handle and not interactive_input:
time.sleep(0.35)
try:
still_visible = bool(menu.is_visible())
except Exception:
still_visible = True
if still_visible:
_post_menu_item_click(menu_handle, verify_action.rectangle())
emit(
stage='verify_menu_fallback',
lm_pid=target.process_id(),
menu_hwnd=menu_handle,
channel='private_popup_message',
)
session = LibraryVerifySession(target, process, int(tree.handle), library, block_name)
return session
except Exception:
if session is None:
try:
process.terminate()
except Exception:
pass
raise
+396
View File
@@ -0,0 +1,396 @@
from pathlib import Path
import re
import logging
import json
from collections import Counter, defaultdict
from .models import CbbRecord, LibraryReadResult
from .network_path import absolute_preserving_drive
logger = logging.getLogger(__name__)
CACHE_SCHEMA_VERSION = 2
def infer_image_status_map(tree_images, status_by_name, names):
"""Derive the current machine's image-ID map from persisted observations."""
observations = defaultdict(set)
ready_counts = Counter()
for name in tuple(names):
image = tree_images.get(name)
status = str(status_by_name.get(name, 'UNKNOWN') or 'UNKNOWN').upper()
if image is not None and status in {'READY', 'PENDING'}:
observations[image].add(status)
if status == 'READY':
ready_counts[image] += 1
# A current Pending observation is stronger than a stale complete Cert
# tree: an item can retain Cert artifacts after a user clicks Unverify.
# Resolve mixed observations to Pending so the live icon cannot be hidden
# by historical filesystem output.
has_pending_anchor = any('PENDING' in statuses for statuses in observations.values())
if has_pending_anchor:
return {
image: 'PENDING' if 'PENDING' in statuses else 'READY'
for image, statuses in observations.items()
if statuses
}
# When every persisted row says Ready, an item manually changed to
# Unverify has no filesystem anchor. Keep only the modal Ready ID as the
# positive anchor; an additional ID is handled as an unseen Pending ID.
if not ready_counts:
return {}
modal_count = max(ready_counts.values())
modal_ids = {image for image, count in ready_counts.items() if count == modal_count}
return {image: 'READY' for image in modal_ids}
def _read_image_status_cache(path, library=None):
if path is None:
return {}
try:
payload = json.loads(Path(path).read_text(encoding='utf-8'))
if isinstance(payload, dict):
if payload.get('schema_version') != CACHE_SCHEMA_VERSION:
logger.info('image_status_cache_legacy_or_unknown_schema path=%s schema=%s',
path, payload.get('schema_version'))
return {}
if library is not None:
stored_library = str(payload.get('library', '') or '')
current_library = str(absolute_preserving_drive(library))
if stored_library and stored_library.casefold() != current_library.casefold():
logger.info('image_status_cache_library_mismatch path=%s stored=%s current=%s',
path, stored_library, library)
return {}
raw = payload.get('image_status_map', {}) if isinstance(payload, dict) else {}
return {int(image): str(status).upper() for image, status in raw.items()
if str(status).upper() in {'READY', 'PENDING'}}
except (OSError, ValueError, TypeError):
return {}
def _write_image_status_cache(path, image_status_map, library=None):
if path is None or not image_status_map:
return
try:
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps({
'schema_version': CACHE_SCHEMA_VERSION,
'library': str(absolute_preserving_drive(library)) if library is not None else '',
'image_status_map': {str(image): status for image, status in image_status_map.items()},
}, ensure_ascii=False, indent=2), encoding='utf-8')
except OSError as error:
logger.warning('image_status_cache_write_failed path=%s error=%s', path, error)
def infer_tree_statuses(tree_images, filesystem_statuses, names, *, image_status_map=None):
"""Calibrate icon indices from independent persisted evidence.
``iImage`` is a resource-list position, not a stable Mentor API. An
index is usable only when all CBBs with that index have the same known
Cert-derived status. Ambiguous or unanchored indices remain UNKNOWN.
"""
calibrated = (dict(image_status_map) if image_status_map is not None
else infer_image_status_map(tree_images, filesystem_statuses, names))
ready_ids = {image for image, status in calibrated.items() if status == 'READY'}
return {
name: calibrated.get(
tree_images.get(name),
'PENDING' if tree_images.get(name) is not None and ready_ids else 'UNKNOWN',
)
for name in tuple(names)
}
def reconcile_statuses(tree_statuses, filesystem_statuses, names):
"""Reconcile live icon evidence with persisted Cert/Work evidence.
Complete persisted evidence is sufficient when the tree ID cannot be read
(for example when LM is already busy). Once an ID has been calibrated from
the current library, the live tree status wins because Cert artifacts can
remain after a user clicks Unverify.
"""
result = {}
for name in tuple(names):
tree = str(tree_statuses.get(name, 'UNKNOWN') or 'UNKNOWN').upper()
filesystem = str(filesystem_statuses.get(name, 'UNKNOWN') or 'UNKNOWN').upper()
if tree in {'READY', 'PENDING'}:
result[name] = tree
elif filesystem in {'READY', 'PENDING'}:
result[name] = filesystem
else:
result[name] = 'UNKNOWN'
return result
def _item(collection, index):
item = getattr(collection, 'Item', None)
if callable(item): return item(index)
try: return collection(index)
except TypeError: return getattr(collection, str(index))
def _value(obj, name, default=None):
value = getattr(obj, name, default)
return value() if callable(value) else value
def filesystem_evidence_map(library: Path, names):
"""Collect independent persisted dimensions for each CBB.
The result deliberately exposes each Work/Cert artifact instead of
collapsing the decision into one file check. A complete set of six
artifacts is the persisted ``READY`` observation; an otherwise valid Work
project with an incomplete Cert set is ``PENDING``. An imported block with
no usable Work project is also ``PENDING`` so it can anchor the current
machine's unverified icon ID; PCB preflight may still skip it later.
"""
library = Path(library)
root = library.parent / 'ReusableBlocksLP'
result = {}
for name in tuple(names):
evidence = {
'status': 'UNKNOWN',
'project_count': 0,
'work_project': False,
'work_pcb': False,
'work_layout': False,
'cert_project': False,
'cert_pcb': False,
'cert_layout': False,
}
block = root / str(name)
work = block / 'Work'
projects = list(work.glob('*.prj')) if work.is_dir() else []
evidence['project_count'] = len(projects)
if len(projects) != 1:
evidence['status'] = 'PENDING'
result[name] = evidence
continue
project = projects[0]
evidence['work_project'] = project.is_file()
try:
content = project.read_text(encoding='utf-8', errors='replace')
match = re.search(r'^KEY PCBDesignPath "([^"]+)"', content, re.M)
pcb = absolute_preserving_drive(project.parent / match.group(1)) if match else None
if pcb is None or not pcb.is_relative_to(absolute_preserving_drive(work)):
evidence['status'] = 'PENDING'
result[name] = evidence
continue
cert = block / 'Cert'
cert_project = cert / project.name
cert_pcb = cert / pcb.relative_to(work)
cert_layout = cert_pcb.parent / 'Layout' / 'LayoutDB.lyt'
work_layout = pcb.parent / 'Layout' / 'LayoutDB.lyt'
paths = {
'work_project': project,
'work_pcb': pcb,
'work_layout': work_layout,
'cert_project': cert_project,
'cert_pcb': cert_pcb,
'cert_layout': cert_layout,
}
for key, path in paths.items():
evidence[key] = path.is_file()
work_valid = all(evidence[key] for key in ('work_project', 'work_pcb', 'work_layout'))
cert_valid = all(evidence[key] for key in ('cert_project', 'cert_pcb', 'cert_layout'))
evidence['status'] = 'READY' if work_valid and cert_valid else 'PENDING'
result[name] = evidence
except (OSError, ValueError):
result[name] = evidence
return result
def filesystem_status_map(library: Path, names):
"""Return only the persisted status derived from all six artifacts."""
return {name: details['status'] for name, details in filesystem_evidence_map(library, names).items()}
def read_library_fast(path: Path, *, status_reader=None):
"""List CBBs from ReusableBlocksLP without touching COM or the .lmc.
Useful when Library Manager is unavailable or already running: the folder
is the same source the LM tree shows, and an optional status_reader can
supply each item's flag without a full COM session.
"""
try:
path = Path(path)
if not path.is_file():
return LibraryReadResult((), f'中心库不存在: {path}')
folder = path.parent/'ReusableBlocksLP'
if not folder.is_dir():
return LibraryReadResult((), f'缺少 ReusableBlocksLP 目录: {folder}')
entries = [entry for entry in folder.iterdir() if entry.is_dir()]
names = tuple(sorted((entry.name for entry in entries), key=str.casefold))
statuses = {}
if status_reader is not None and names:
try:
statuses = dict(status_reader(path, names))
except TypeError:
for name in names:
try:
statuses[name] = status_reader(name)
except Exception:
statuses[name] = 'UNKNOWN'
except Exception as error:
# Do not turn a failed authoritative probe into a silent
# UNKNOWN list. UNKNOWN is calibration-only; a bridge or
# reader failure must remain visible and must not look like a
# valid scan that happened to find no statuses.
logger.warning('library_status_reader_failed path=%s error=%s', path, error)
statuses = {name: 'UNAVAILABLE' for name in names}
records = []
for entry in entries:
status = str(statuses.get(entry.name, 'UNKNOWN') or 'UNKNOWN')
if status not in {'READY', 'PENDING', 'UNKNOWN', 'UNAVAILABLE', 'ERROR', 'TIMEOUT'}:
status = 'UNKNOWN'
records.append(CbbRecord(entry.name, 'Reusable Blocks', status=status))
return LibraryReadResult(tuple(sorted(records, key=lambda item: item.name)))
except Exception as error:
return LibraryReadResult((), str(error))
def scan_open_library_status(library: Path, names, *, tree_image_reader=None,
mapping_store=None):
"""Read verification icons from an already-open LM, without launching it."""
names = tuple(names)
persisted_evidence = filesystem_evidence_map(library, names)
fallback = {name: details['status'] for name, details in persisted_evidence.items()}
def finish(tree_images):
tree_images = dict(tree_images or {})
current_map = infer_image_status_map(tree_images, fallback, names)
cached_map = _read_image_status_cache(mapping_store, library)
image_status_map = dict(cached_map)
cache_actions = {}
has_cached_ready = any(status == 'READY' for status in cached_map.values())
for image, status_value in current_map.items():
# The native image index is the machine-local status key. Once an
# index has been calibrated, a transient filesystem snapshot must
# not rewrite it: Cert/Work files can lag behind the TreeView
# after Verify. New indices are still learned from this scan, so
# an Unverify transition remains visible as a new Pending index.
if image in cached_map:
image_status_map[image] = cached_map[image]
cache_actions[image] = 'cached_image_id_authoritative'
elif has_cached_ready and status_value == 'READY':
# With an existing Ready anchor, an unseen icon cannot be
# promoted from stale Cert files alone. Keep it out of the
# map so infer_tree_statuses classifies it as Pending.
cache_actions[image] = 'unseen_tree_id_pending'
else:
image_status_map[image] = status_value
cache_actions[image] = 'current_evidence_calibrated'
if not image_status_map:
image_status_map = current_map
_write_image_status_cache(mapping_store, image_status_map, library)
tree_statuses = infer_tree_statuses(tree_images, fallback, names,
image_status_map=image_status_map)
status = reconcile_statuses(tree_statuses, fallback, names)
uncalibrated = [name for name in names if status.get(name, 'UNKNOWN') == 'UNKNOWN']
# The UI must never use UNKNOWN as a skip signal. Queue it as Pending
# so it receives the real Verify flow instead of being silently omitted.
effective = {name: ('PENDING' if value == 'UNKNOWN' else value)
for name, value in status.items()}
logger.info(
'library_status_sources names=%s image_histogram=%s current_image_map=%s cached_image_map=%s image_status_map=%s cache_actions=%s filesystem=%s calibrated_tree=%s final=%s uncalibrated_sample=%s conflicts=%s ready_anchor_ids=%s unseen_tree_ids=%s',
len(names), dict(Counter(str(value) for value in tree_images.values() if value is not None)),
dict(current_map), dict(cached_map),
dict(image_status_map),
dict(cache_actions),
dict(Counter(fallback.get(name, 'UNKNOWN') for name in names)),
dict(Counter(tree_statuses.get(name, 'UNKNOWN') for name in names)),
dict(Counter(effective.get(name, 'PENDING') for name in names)),
uncalibrated[:20],
[name for name in names if tree_statuses.get(name) in {'READY', 'PENDING'}
and fallback.get(name) in {'READY', 'PENDING'}
and tree_statuses.get(name) != fallback.get(name)][:20],
sorted(image for image, value in image_status_map.items() if value == 'READY'),
sorted(image for image in tree_images.values()
if image is not None and image not in image_status_map),
)
for name in names:
image_id = tree_images.get(name)
persisted = fallback.get(name, 'UNKNOWN')
tree = tree_statuses.get(name, 'UNKNOWN')
final = effective.get(name, 'PENDING')
if image_id is not None and image_id not in image_status_map and tree == 'PENDING':
reason = ('unseen_tree_id_vs_cached_ready_anchor' if cached_map
else 'unseen_tree_id_vs_ready_anchor')
elif persisted in {'READY', 'PENDING'} and tree in {'READY', 'PENDING'}:
reason = 'tree_id_and_persisted_match' if persisted == tree else 'tree_id_conflicts_persisted'
elif persisted in {'READY', 'PENDING'}:
reason = 'persisted_only'
elif tree in {'READY', 'PENDING'}:
reason = 'tree_id_calibrated'
else:
reason = 'insufficient_evidence'
logger.info(
'library_status_item name=%s image_id=%s filesystem=%s tree=%s final=%s evidence=%s dimensions=%s',
name, image_id, persisted, tree, final, reason, persisted_evidence.get(name, {}),
)
return effective
try:
from pywinauto import Desktop
from pywinauto.controls.common_controls import TreeViewWrapper
from cbb_refresh_verify.mentor_adapter import _tree_image, same_path
target = None
for window in Desktop(backend='win32').windows():
title = window.window_text()
if title.startswith('Library Manager:') and same_path(title.split(':', 1)[1].strip(), library):
target = window
break
if target is None:
if tree_image_reader is None:
from cbb_refresh_verify.mentor_adapter import read_library_tree_image_map
tree_image_reader = read_library_tree_image_map
return finish(tree_image_reader(library, names))
trees = [w for w in target.descendants() if 'TreeView' in w.class_name()]
if len(trees) != 1:
return finish({})
tree = TreeViewWrapper(trees[0].handle)
root_name = Path(library).name
images = {}
missing = []
for name in names:
try:
item = tree.get_item(['Central Libraries', root_name, 'Reusable Blocks', 'Logical-Physical', name], exact=True)
from cbb_refresh_verify.mentor_adapter import _tree_image_details
details = _tree_image_details(item, tree)
images[name] = details['image_id']
logger.info('library_tree_image_item name=%s image_id=%s selected_image_id=%s state_image_id=%s image_color=%s selected_image_color=%s state_image_color=%s',
name, details['image_id'], details['selected_image_id'],
details['state_image_id'], details['image_color'],
details['selected_image_color'], details['state_image_color'])
except Exception:
images[name] = None
missing.append(name)
logger.info('library_tree_image_probe requested=%s read=%s missing=%s',
len(names), len(names) - len(missing), missing[:20])
return finish(images)
except Exception as error:
logger.warning('library_status_probe_failed path=%s error=%s', library, error)
return finish({})
def read_library(path: Path, *, dispatch=None):
try:
if not Path(path).exists() and dispatch is None:
return LibraryReadResult((), f'中心库不存在: {path}')
if dispatch is None:
import win32com.client
dispatch = win32com.client.Dispatch
app=dispatch('LibraryManager.Application')
lib=app.OpenLibrary(str(path))
out=[]
# LibraryManager exposes Partitions as an indexed method (not a COM collection).
parts = lib.Partitions(7)
count = int(_value(parts, 'Count', 0) or 0)
for i in range(1, count + 1):
partition = _item(parts, i)
for j in range(1, int(_value(partition, 'Count', 0) or 0) + 1):
x=_item(partition, j)
out.append(CbbRecord(str(_value(x, 'Name', x)), str(_value(x, 'PartitionName', 'Reusable Blocks'))))
if not out:
folder = Path(path).parent / 'ReusableBlocksLP'
if folder.is_dir(): out.extend(CbbRecord(x.name, 'Reusable Blocks') for x in folder.iterdir() if x.is_dir())
return LibraryReadResult(tuple(sorted(set(out), key=lambda x:x.name)))
except Exception as error:
return LibraryReadResult((), str(error))
File diff suppressed because it is too large. Load diff
+183
View File
@@ -0,0 +1,183 @@
"""Bounded discovery of a Mentor EE installation.
Mentor is commonly installed on a non-system drive and the product name and
version directory vary between machines. This module only inspects explicit
configuration and a small set of conventional directories; it never walks an
entire drive.
"""
from __future__ import annotations
from pathlib import Path
from functools import lru_cache
import ctypes
import os
from typing import Iterable
_KNOWN_RELATIVE_BINARIES = (
Path('lm/win32/bin/LibraryManager.exe'),
Path('lm/win32/bin/ReuseBlockImporter.exe'),
Path('common/win32/bin/ExpeditionPCB.exe'),
Path('wg/win32/bin/ExpeditionPCB.exe'),
)
def _sdd_home_from_value(value: str | Path | None) -> Path | None:
if not value:
return None
candidate = Path(value)
if candidate.is_file():
candidate = candidate.parent
for parent in (candidate, *candidate.parents):
if parent.name.casefold() == 'sdd_home':
return parent
return None
def _configured_values(explicit: str | Path | None, environ: dict[str, str]) -> Iterable[Path]:
if explicit:
value = _sdd_home_from_value(explicit)
if value is not None:
yield value
for name in ('SDD_HOME', 'SDD_LM_BIN', 'CBB_MENTOR_BIN'):
value = _sdd_home_from_value(environ.get(name))
if value is not None:
yield value
def _search_roots(environ: dict[str, str], roots: Iterable[str | Path] | None) -> tuple[Path, ...]:
if roots is not None:
return tuple(Path(root) for root in roots)
configured = tuple(
Path(value) for value in environ.get('CBB_MENTOR_SEARCH_ROOTS', '').split(';')
if value.strip()
)
if configured:
return configured
roots = []
# Avoid probing disconnected mapped drives. GetDriveTypeW keeps the
# automatic scan local; network installations remain supported through an
# explicit SDD_HOME/SDD_LM_BIN or CBB_MENTOR_SEARCH_ROOTS.
if os.name == 'nt':
try:
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
mask = int(kernel32.GetLogicalDrives())
get_drive_type = kernel32.GetDriveTypeW
get_drive_type.argtypes = [ctypes.c_wchar_p]
get_drive_type.restype = ctypes.c_uint
for index in range(26):
if not (mask & (1 << index)):
continue
root = f'{chr(ord("A") + index)}:\\'
# DRIVE_REMOVABLE=2, DRIVE_FIXED=3
if int(get_drive_type(root)) in (2, 3):
roots.append(Path(root))
except (AttributeError, OSError):
pass
if not roots:
anchor = Path.cwd().anchor
roots = [Path(anchor)] if anchor else []
return tuple(roots)
def _candidate_homes(roots: Iterable[Path]) -> Iterable[Path]:
seen: set[str] = set()
for root in roots:
candidates = [root]
if root.name.casefold() != 'sdd_home':
candidates.extend((
root / 'SDD_HOME',
root / 'Mentor' / 'SDD_HOME',
root / 'MentorGraphics' / 'SDD_HOME',
root / 'Program Files' / 'Mentor Graphics' / 'SDD_HOME',
root / 'Program Files (x86)' / 'Mentor Graphics' / 'SDD_HOME',
))
for parent_name in ('Mentor', 'MentorGraphics', 'Mentor Graphics'):
for version_root in (root / parent_name, root / 'Program Files' / parent_name,
root / 'Program Files (x86)' / parent_name):
try:
candidates.extend(version_root.glob('*/SDD_HOME'))
except OSError:
continue
for candidate in candidates:
try:
key = os.path.normcase(str(candidate))
if key not in seen:
seen.add(key)
yield candidate
except (OSError, ValueError):
continue
def _has_known_binary(home: Path) -> bool:
try:
return any((home / relative).is_file() for relative in _KNOWN_RELATIVE_BINARIES)
except OSError:
return False
def discover_sdd_home(
explicit: str | Path | None = None,
*,
environ: dict[str, str] | None = None,
search_roots: Iterable[str | Path] | None = None,
) -> Path | None:
"""Return the best matching SDD_HOME, or ``None`` if none is installed.
Explicit values and environment variables win. Auto-discovery then
checks bounded conventional Mentor layouts. A candidate is accepted only
when at least one known Mentor executable exists below it.
"""
environ = dict(os.environ if environ is None else environ)
roots = tuple(str(root) for root in _search_roots(environ, search_roots))
return _discover_sdd_home_cached(
str(explicit or ''),
environ.get('SDD_HOME', ''),
environ.get('SDD_LM_BIN', ''),
environ.get('CBB_MENTOR_BIN', ''),
roots,
)
@lru_cache(maxsize=64)
def _discover_sdd_home_cached(
explicit: str,
sdd_home: str,
lm_bin: str,
mentor_bin: str,
roots: tuple[str, ...],
) -> Path | None:
environ = {
'SDD_HOME': sdd_home,
'SDD_LM_BIN': lm_bin,
'CBB_MENTOR_BIN': mentor_bin,
}
ordered: list[Path] = list(_configured_values(explicit, environ))
ordered.extend(_candidate_homes(Path(root) for root in roots))
seen: set[str] = set()
for home in ordered:
try:
key = os.path.normcase(str(home))
if key in seen:
continue
seen.add(key)
if _has_known_binary(home):
return home
except (OSError, ValueError):
continue
return None
def describe_installation(home: Path | None) -> dict[str, str | bool]:
"""Return stable, non-sensitive discovery evidence for runtime logs."""
if home is None:
return {'found': False, 'sdd_home': ''}
return {
'found': True,
'sdd_home': str(home),
'library_manager': str(home / 'lm/win32/bin/LibraryManager.exe'),
'reuse_block_importer': str(home / 'lm/win32/bin/ReuseBlockImporter.exe'),
'expedition_common': str(home / 'common/win32/bin/ExpeditionPCB.exe'),
'expedition_wg': str(home / 'wg/win32/bin/ExpeditionPCB.exe'),
}
+14
View File
@@ -0,0 +1,14 @@
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True)
class CbbRecord:
name: str
partition_name: str
logical_type: str = "LP"
status: str = "UNKNOWN"
@dataclass(frozen=True)
class LibraryReadResult:
records: tuple[CbbRecord, ...]
error: str | None = None
+246
View File
@@ -0,0 +1,246 @@
"""Bounded UNC-to-drive leases for Mentor tools that require drive paths."""
from __future__ import annotations
from dataclasses import dataclass
import ctypes
from ctypes import wintypes
import ntpath
import os
from pathlib import Path
from typing import Protocol
class NetworkPathError(RuntimeError):
"""A network library could not be exposed through a stable Mentor path."""
class WNetBackend(Protocol):
def mappings(self) -> dict[str, str]: ...
def used_drives(self) -> set[str]: ...
def add_mapping(self, drive: str, remote: str) -> None: ...
def cancel_mapping(self, drive: str) -> None: ...
class _NETRESOURCEW(ctypes.Structure):
_fields_ = [
("dwScope", wintypes.DWORD),
("dwType", wintypes.DWORD),
("dwDisplayType", wintypes.DWORD),
("dwUsage", wintypes.DWORD),
("lpLocalName", wintypes.LPWSTR),
("lpRemoteName", wintypes.LPWSTR),
("lpComment", wintypes.LPWSTR),
("lpProvider", wintypes.LPWSTR),
]
class WindowsWNetBackend:
"""Small ctypes wrapper that uses only the current Windows credentials."""
ERROR_NOT_CONNECTED = 2250
RESOURCETYPE_DISK = 1
CONNECT_TEMPORARY = 4
def __init__(self) -> None:
self._mpr = ctypes.WinDLL("mpr", use_last_error=True)
self._kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
def mappings(self) -> dict[str, str]:
result: dict[str, str] = {}
for code in range(ord("D"), ord("Z") + 1):
drive = f"{chr(code)}:"
size = wintypes.DWORD(32768)
buffer = ctypes.create_unicode_buffer(size.value)
error = self._mpr.WNetGetConnectionW(drive, buffer, ctypes.byref(size))
if error == 0:
result[drive] = buffer.value
elif error != self.ERROR_NOT_CONNECTED:
raise OSError(error, f"WNetGetConnectionW({drive})")
return result
def used_drives(self) -> set[str]:
mask = int(self._kernel32.GetLogicalDrives())
return {
f"{chr(ord('A') + index)}:"
for index in range(26)
if mask & (1 << index)
}
def add_mapping(self, drive: str, remote: str) -> None:
resource = _NETRESOURCEW()
resource.dwType = self.RESOURCETYPE_DISK
resource.lpLocalName = drive
resource.lpRemoteName = remote
error = self._mpr.WNetAddConnection2W(
ctypes.byref(resource), None, None, self.CONNECT_TEMPORARY
)
if error:
raise OSError(error, f"WNetAddConnection2W({drive}, {remote})")
def cancel_mapping(self, drive: str) -> None:
error = self._mpr.WNetCancelConnection2W(drive, 0, False)
if error and error != self.ERROR_NOT_CONNECTED:
raise OSError(error, f"WNetCancelConnection2W({drive})")
def _same_remote(left: str, right: str) -> bool:
return ntpath.normcase(ntpath.normpath(left)) == ntpath.normcase(ntpath.normpath(right))
def ensure_mapped_drive_visible(drive: str, remote_root: str, *,
backend: WNetBackend | None = None) -> dict[str, object]:
"""Ensure a worker process can see the mapped drive used by Mentor.
Windows drive mappings are associated with a logon/security context. A
PCB or iCDB child started from an elevated/private worker can therefore
lose a mapping that is visible to the UI process. Reuse an identical
mapping, create it only when absent, and reject a conflicting mapping.
The function never disconnects a mapping; ownership remains with the
user's session.
"""
raw_drive = str(drive or '').strip().rstrip('\\/')
raw_remote = str(remote_root or '').strip()
if not raw_drive or not raw_remote:
return {'drive': raw_drive, 'remote_root': raw_remote, 'created': False}
if not raw_drive.endswith(':'):
raw_drive = raw_drive[:2] if len(raw_drive) >= 2 and raw_drive[1] == ':' else raw_drive
normalized_drive = raw_drive.upper()
backend = backend or WindowsWNetBackend()
try:
mappings = backend.mappings()
except OSError as error:
raise NetworkPathError(
f"NETWORK_UNAVAILABLE: 无法读取网络盘映射 {normalized_drive}: {error}"
) from error
current = next((value for key, value in mappings.items()
if str(key).upper().rstrip('\\/') == normalized_drive), None)
if current:
if _same_remote(current, raw_remote):
return {'drive': normalized_drive, 'remote_root': current, 'created': False}
raise NetworkPathError(
f"NETWORK_UNAVAILABLE: 映射冲突 {normalized_drive}: 当前={current}, 需要={raw_remote}"
)
try:
backend.add_mapping(normalized_drive, raw_remote)
except OSError as error:
raise NetworkPathError(
f"NETWORK_UNAVAILABLE: 无法在 worker 会话恢复映射 {normalized_drive} -> {raw_remote}: {error}"
) from error
return {'drive': normalized_drive, 'remote_root': raw_remote, 'created': True}
def absolute_preserving_drive(path) -> Path:
"""Make a path absolute without resolving a mapped drive back to UNC."""
return Path(os.path.abspath(str(path)))
def _normalize_input_path(path) -> str:
raw = str(path).strip()
if raw.startswith("/"):
raw = raw.replace("/", "\\")
if raw.startswith("\\") and not raw.startswith("\\\\"):
raise NetworkPathError(
"NETWORK_UNAVAILABLE: UNC 路径必须以两个反斜杠开头,例如 \\\\server\\share"
)
if raw.startswith("\\\\"):
raw = "\\\\" + raw.lstrip("\\").replace("/", "\\")
return raw
def select_library_file(path) -> Path:
"""Return a concrete LMC, accepting a directory with exactly one LMC."""
candidate = Path(path)
if candidate.is_file():
if candidate.suffix.casefold() != ".lmc":
raise NetworkPathError(f"中心库文件必须是 .lmc: {candidate}")
return candidate
if candidate.is_dir():
files = sorted(
(item for item in candidate.iterdir()
if item.is_file() and item.suffix.casefold() == ".lmc"),
key=lambda item: item.name.casefold(),
)
if len(files) != 1:
raise NetworkPathError(
f"中心库目录必须包含唯一的 .lmc 文件,当前找到 {len(files)} 个: {candidate}"
)
return files[0]
raise NetworkPathError(f"中心库路径不存在或不可访问: {candidate}")
@dataclass
class LibraryPathLease:
display_path: Path
mentor_path: Path
drive: str = ""
remote_root: str = ""
created: bool = False
_backend: WNetBackend | None = None
_closed: bool = False
@classmethod
def acquire(cls, path, *, backend: WNetBackend | None = None) -> "LibraryPathLease":
raw = _normalize_input_path(path)
if not raw.startswith("\\\\"):
local = Path(path)
drive, _ = ntpath.splitdrive(raw)
if drive:
try:
backend = backend or WindowsWNetBackend()
remote = next((value for key, value in backend.mappings().items()
if str(key).upper().rstrip('\\/') == drive.upper()), '')
except (OSError, AttributeError):
remote = ''
return cls(local, local, drive.upper(), remote, False, backend)
return cls(local, local)
remote_root, tail = ntpath.splitdrive(raw)
if not remote_root or remote_root.count("\\") < 3:
raise NetworkPathError(f"NETWORK_UNAVAILABLE: 非法 UNC 中心库路径: {raw}")
backend = backend or WindowsWNetBackend()
try:
mappings = backend.mappings()
for drive, remote in mappings.items():
if _same_remote(remote, remote_root):
mentor = Path(drive + "\\" + tail.lstrip("\\/"))
return cls(Path(raw), mentor, drive, remote_root, False, backend)
used = {drive.upper().rstrip("\\") for drive in backend.used_drives()}
drive = next(
(f"{letter}:" for letter in reversed("DEFGHIJKLMNOPQRSTUVWXYZ")
if f"{letter}:" not in used),
"",
)
if not drive:
raise NetworkPathError("NETWORK_UNAVAILABLE: 没有可用的临时网络盘符")
backend.add_mapping(drive, remote_root)
mentor = Path(drive + "\\" + tail.lstrip("\\/"))
return cls(Path(raw), mentor, drive, remote_root, True, backend)
except NetworkPathError:
raise
except OSError as error:
raise NetworkPathError(
f"NETWORK_UNAVAILABLE: 无法挂载中心库 {remote_root}: {error}"
) from error
def close(self) -> None:
if self._closed:
return
self._closed = True
if not self.created or self._backend is None or not self.drive:
return
try:
current = self._backend.mappings().get(self.drive)
if current and _same_remote(current, self.remote_root):
self._backend.cancel_mapping(self.drive)
except OSError as error:
raise NetworkPathError(
f"NETWORK_UNAVAILABLE: 释放临时盘符 {self.drive} 失败: {error}"
) from error
def __enter__(self) -> "LibraryPathLease":
return self
def __exit__(self, exc_type, exc_value, traceback) -> None:
self.close()
+143
View File
@@ -0,0 +1,143 @@
"""Structured Expedition PCB COM bridge primitives.
The bridge uses only interfaces confirmed in Mentor's registered type
libraries. It never relies on window titles or foreground-window state.
"""
from __future__ import annotations
import os
from pathlib import Path
import time
class PcbBridgeError(RuntimeError):
def __init__(self, error_code: str, detail: str) -> None:
self.error_code = str(error_code)
self.detail = str(detail)
super().__init__(self.detail)
class AutomationLicenseError(PcbBridgeError):
def __init__(self, error_code: str, detail: str, *, fallback_allowed: bool) -> None:
self.fallback_allowed = bool(fallback_allowed)
super().__init__(error_code, detail)
_UNAVAILABLE_HRESULTS = {
-2147221164, # REGDB_E_CLASSNOTREG
-2146959355, # CO_E_SERVER_EXEC_FAILURE
-2147023174, # RPC_S_SERVER_UNAVAILABLE
}
def _hresult(error):
value = getattr(error, 'hresult', None)
if value is None:
arguments = getattr(error, 'args', ())
value = arguments[0] if arguments and isinstance(arguments[0], int) else None
return value
def validate_document(document, license_factory, *, emit=lambda **event: None):
"""Acquire and apply an Expedition automation token without exposing it."""
try:
key = document.Validate(0)
emit(stage='license_key_requested')
except Exception as error:
raise AutomationLicenseError(
'AUTOMATION_LICENSE_KEY_FAILED', f'无法取得 PCB 授权 key: {error}',
fallback_allowed=False,
) from error
try:
licensing = license_factory()
token = licensing.GetToken(key)
emit(stage='license_token_received')
except Exception as error:
fallback_allowed = _hresult(error) in _UNAVAILABLE_HRESULTS
raise AutomationLicenseError(
'AUTOMATION_LICENSE_UNAVAILABLE' if fallback_allowed else 'AUTOMATION_LICENSE_TOKEN_FAILED',
f'无法取得 PCB automation token: {error}',
fallback_allowed=fallback_allowed,
) from error
try:
document.Validate(token)
emit(stage='document_validated')
except Exception as error:
raise AutomationLicenseError(
'AUTOMATION_LICENSE_REJECTED', f'PCB automation token 被拒绝: {error}',
fallback_allowed=False,
) from error
def _same_path(first, second) -> bool:
return os.path.normcase(os.path.abspath(str(first))) == os.path.normcase(os.path.abspath(str(second)))
def require_document_identity(document, job):
expected_project = Path(job['project'])
expected_pcb = Path(job['pcb'])
try:
integration = document.ProjectIntegration
project_file = str(integration.ProjectFile)
document_name = str(document.Name)
except Exception as error:
raise PcbBridgeError('PCB_IDENTITY_UNAVAILABLE', f'PCB 文档身份不可读: {error}') from error
if not _same_path(project_file, expected_project) or document_name.casefold() != expected_pcb.name.casefold():
raise PcbBridgeError(
'PCB_IDENTITY_MISMATCH',
f'当前 PCB 工程身份不符: project={project_file}; document={document_name}',
)
return integration
def wait_for_target_document(job, app_provider, *, process_alive, emit=lambda **event: None,
error_reader=None, sleep=time.sleep):
"""Wait for the exact launched document; the parent process owns timeout."""
last_observation = None
while process_alive():
if error_reader is not None:
detail = error_reader()
if detail:
raise PcbBridgeError('PCB_STARTUP_FAILED', detail)
try:
app = app_provider()
document = app.ActiveDocument
if document:
try:
integration = require_document_identity(document, job)
except PcbBridgeError as error:
observation = (error.error_code, error.detail)
if observation != last_observation:
emit(stage='identity_wait', error_code=error.error_code, detail=error.detail)
last_observation = observation
else:
emit(stage='identity_verified', project=str(integration.ProjectFile),
document=str(document.Name))
return app, document, integration
except PcbBridgeError:
raise
except Exception as error:
observation = ('COM_NOT_READY', str(error))
if observation != last_observation:
# COM registration is an internal attach wait, not a user
# operation. Keep the transient detail out of the workflow
# event stream; a final attach failure still raises below.
last_observation = observation
sleep(.25)
raise PcbBridgeError('PCB_EXITED_BEFORE_COM', 'PCB 在 COM 文档就绪前退出')
def execution_outcome(*, save_complete: bool, pcb_exited: bool,
fatal_error: str = '') -> dict[str, object]:
if fatal_error:
code, _, detail = str(fatal_error).partition(':')
return {'status': 'FAIL', 'error_code': code.strip() or 'FATAL_DIALOG',
'stderr': detail.strip() or str(fatal_error), 'safe_to_continue': True}
if not save_complete:
return {'status': 'FAIL', 'error_code': 'SAVE_NOT_CONFIRMED',
'stderr': '保存/关闭未完成', 'safe_to_continue': True}
if not pcb_exited:
return {'status': 'FAIL', 'error_code': 'PCB_EXIT_NOT_CONFIRMED',
'stderr': '保存后未确认 PCB 退出', 'safe_to_continue': True}
return {'status': 'PASS', 'stdout': 'Project Integration 已同步;保存、关闭和 PCB 退出均已确认。'}
@@ -0,0 +1,77 @@
"""Read-only observations while Library Manager invokes Verify."""
from __future__ import annotations
from pathlib import Path
def invoke_with_evidence(invoke, emit, metadata):
emit({'stage': 'verify_invoke', **metadata})
invoke()
emit({'stage': 'verify_invoke_returned', **metadata})
def build_snapshot(processes, windows, expected_pcb, preexisting_pids):
from .mentor_adapter import is_reusable_circuit_pcb
expected = str(expected_pcb).casefold()
return {
'processes': [
{
'pid': int(pid), 'name': str(name), 'executable': str(executable),
'command': str(command), 'preexisting': int(pid) in preexisting_pids,
'target_path_in_command': expected in str(command).casefold(),
'matches_current_filter': is_reusable_circuit_pcb(executable, command, expected_pcb),
}
for pid, name, executable, command in processes
],
'windows': list(windows),
}
def _related_processes():
import win32com.client
service = win32com.client.GetObject('winmgmts:')
query = ("SELECT ProcessId, Name, ExecutablePath, CommandLine FROM Win32_Process "
"WHERE Name='LibraryManager.exe' OR Name LIKE '%PCB%' OR Name LIKE '%Xtreme%'")
return [(int(p.ProcessId), str(p.Name or ''), str(p.ExecutablePath or ''),
str(p.CommandLine or '')) for p in service.ExecQuery(query)]
def _private_windows(desktop, related_pids):
import win32gui
import win32process
windows = []
for hwnd in desktop.EnumDesktopWindows():
try:
pid = int(win32process.GetWindowThreadProcessId(hwnd)[1])
if pid not in related_pids or not win32gui.IsWindowVisible(hwnd):
continue
class_name = win32gui.GetClassName(hwnd)
title = win32gui.GetWindowText(hwnd)
owner = int(win32gui.GetWindow(hwnd, 4) or 0)
texts = []
if owner or class_name in ('#32770', 'GXWND', 'TaskDialog'):
children = []
win32gui.EnumChildWindows(hwnd, lambda child, _: children.append(child) or True, None)
for child in children[:32]:
value = win32gui.GetWindowText(child)
if value:
texts.append(value)
windows.append({'pid': pid, 'hwnd': int(hwnd), 'class_name': class_name,
'title': title, 'owner_hwnd': owner, 'texts': texts})
except Exception:
# A window may close between enumeration and inspection.
continue
return windows
def observe_post_verify(desktop, expected_pcb, preexisting_pids, lm_pid):
processes = _related_processes()
related_pids = {pid for pid, _, _, _ in processes}
if lm_pid is not None:
related_pids.add(int(lm_pid))
return build_snapshot(processes, _private_windows(desktop, related_pids),
Path(expected_pcb), preexisting_pids)
+33
View File
@@ -0,0 +1,33 @@
from pathlib import Path
import sys
import hashlib
def configure(root: Path):
try:
from dx_productivity.trial_task_center.logging_setup import configure_logging, install_exception_hooks
context = configure_logging(root); install_exception_hooks(context)
# Reuse the mature rotating/UTC logger implementation, but keep product identity CBB-specific.
context.logger.name = "cbb_refresh_verify." + hashlib.sha256(str(root.resolve()).encode("utf-8")).hexdigest()[:16]
context.logger.info("cbb_logging_configured root=%s application_log=%s", context.root, context.application_log_path)
for handler in context.logger.handlers: handler.flush()
return context
except ImportError:
import logging
from logging.handlers import RotatingFileHandler
root.mkdir(parents=True, exist_ok=True); (root/'logs').mkdir(exist_ok=True)
logger=logging.getLogger('cbb_refresh_verify'); logger.handlers.clear(); logger.setLevel(logging.INFO)
# Keep the standalone fallback bounded as well. The packaged build
# normally uses the replacement tool's rotating logger, but a target
# machine may intentionally omit that optional dependency.
logger.addHandler(RotatingFileHandler(
root/'logs'/'application.log', maxBytes=10 * 1024 * 1024,
backupCount=5, encoding='utf-8'))
return type('Context',(),{'root':root,'logger':logger,'application_log_path':root/'logs'/'application.log'})()
def capture(context, *, operation, returncode, stdout, stderr):
try:
from dx_productivity.trial_task_center.logging_setup import capture_subprocess_output
capture_subprocess_output(context, operation=operation, returncode=returncode, stdout=stdout, stderr=stderr)
except ImportError:
context.logger.info('operation=%s returncode=%s stdout=%s stderr=%s', operation, returncode, stdout.rstrip(), stderr.rstrip())
for handler in context.logger.handlers: handler.flush()
+117
View File
@@ -0,0 +1,117 @@
"""Measured run durations, not estimates derived from wall-clock log timestamps."""
import math
import time
ACTION_KEYS = {
'ForwardAnnotate': 'forward_annotation', 'SynchCES': 'synch_ces',
'LoadCES': 'load_ces', 'BackAnnotate': 'back_annotation',
}
def parse_save_progress(text):
markers, durations = [], {}
for line in text.splitlines():
line = line.strip()
if not line:
continue
if not line.startswith('TIMING|'):
markers.append(line)
continue
parts = line.split('|')
if len(parts) != 3:
continue
try:
seconds = float(parts[2])
except ValueError:
continue
if math.isfinite(seconds) and seconds >= 0:
durations[parts[1]] = seconds
return {'markers': markers, 'timings_seconds': durations}
class RunTimings:
def __init__(self, *, clock=None):
self.clock = clock or time.monotonic
self.started = self.clock()
self.elapsed = {}
self.running = {}
self._action_totals = {}
self._save_markers = set()
def begin(self, name, at=None):
self.running.setdefault(name, self.clock() if at is None else at)
def end(self, name, at=None):
started = self.running.pop(name, None)
if started is not None:
self.elapsed[name] = self.elapsed.get(name, 0.0) + max(
0.0, (self.clock() if at is None else at) - started)
def record(self, event):
now = event.get('monotonic_seconds')
if now is None:
now = self.clock()
stage = event.get('stage')
if stage in ('lm_launch', 'pcb_launch'):
self.end('worker_setup', now)
self.begin('pcb_startup', now)
elif stage == 'identity_verified':
self.end('pcb_startup', now)
self.begin('integration', now)
elif stage == 'integration_action':
key = ACTION_KEYS.get(event.get('action'))
if key:
self.begin(key, now)
elif stage == 'integration_action_complete':
key = ACTION_KEYS.get(event.get('action'))
if key:
self.end(key, now)
# These are measured inside the worker and include COM blocking,
# independent of delayed supervisor polling or disk writes.
if 'elapsed_seconds' in event:
# Replace the just-observed span with the worker's duration.
# Keep repeat actions as separate accumulated work.
prior = self._action_totals.get(key, 0.0)
self._action_totals[key] = prior + float(event['elapsed_seconds'])
self.elapsed[key] = self._action_totals[key]
if 'call_elapsed_seconds' in event:
call = key + '_call'
self.elapsed[call] = self.elapsed.get(call, 0.0) + float(event['call_elapsed_seconds'])
elif stage == 'integration_complete':
self.end('integration', now)
elif stage == 'save_start':
self.begin('save_close', now)
elif stage == 'save_progress':
boundaries = {
'VALIDATE_START': ('begin', 'validate'), 'LICENSE_OK': ('end', 'validate'),
'SAVE_START': ('begin', 'save'), 'SAVE_OK': ('end', 'save'),
'POST_SAVE_CHECK': ('begin', 'post_save_check'),
'POST_SAVE_SYNCHRONIZED': ('end', 'post_save_check'),
'CLOSE_START': ('begin', 'close'), 'CLOSE_OK': ('end', 'close'),
}
for marker in event.get('markers', ()):
if marker in self._save_markers:
continue
self._save_markers.add(marker)
if marker in boundaries:
operation, name = boundaries[marker]
getattr(self, operation)(name, now)
measured = event.get('timings_seconds', {})
for name in measured:
# A helper duration proves the COM call returned, even if its
# Boolean result was false and no success marker followed.
self.running.pop(name, None)
self.elapsed.update(measured)
elif stage == 'saved_and_closed':
self.end('save_close', now)
self.begin('pcb_exit', now)
elif stage == 'complete':
self.end('pcb_exit', now)
def snapshot(self):
now = self.clock()
values = dict(self.elapsed)
for name, started in self.running.items():
values[name] = values.get(name, 0.0) + max(0.0, now - started)
values['total'] = max(0.0, now - self.started)
return {key: round(value, 6) for key, value in values.items()}, tuple(self.running)
@@ -0,0 +1,58 @@
Option Explicit
Dim app, doc, pi, licensing, token, expected, attempt, stable, measuredStart, operationOK
expected = WScript.Arguments(0)
Set app = GetObject(, "MGCPCB.Application")
Set doc = app.ActiveDocument
Set pi = doc.ProjectIntegration
If LCase(pi.ProjectFile) <> LCase(expected) Then WScript.Quit 2
If pi.ForwardAnnotationStatus <> 2 Or pi.SynchCESStatus <> 2 Or pi.LoadCESStatus <> 2 Or pi.BackAnnotationStatus <> 2 Then WScript.Quit 3
WScript.Echo "VALIDATE_START"
measuredStart = Timer
Set licensing = CreateObject("MGCPCBAutomationLicensing.Application")
token = licensing.GetToken(doc.Validate(0))
doc.Validate token
LogElapsed "validate", measuredStart
WScript.Echo "LICENSE_OK"
WScript.Echo "SAVE_START"
measuredStart = Timer
operationOK = doc.Save()
LogElapsed "save", measuredStart
If Not operationOK Then WScript.Quit 4
WScript.Echo "SAVE_OK"
measuredStart = Timer
operationOK = doc.IsSaved()
LogElapsed "is_saved", measuredStart
If Not operationOK Then WScript.Quit 5
WScript.Echo "IS_SAVED"
stable = False
WScript.Echo "POST_SAVE_CHECK"
measuredStart = Timer
For attempt = 1 To 50
Set pi = doc.ProjectIntegration
If pi.ForwardAnnotationStatus = 2 And pi.SynchCESStatus = 2 And pi.LoadCESStatus = 2 And pi.BackAnnotationStatus = 2 Then
stable = True
Exit For
End If
WScript.Sleep 200
Next
LogElapsed "post_save_check", measuredStart
If Not stable Then WScript.Quit 7
WScript.Echo "POST_SAVE_SYNCHRONIZED"
If Not doc.IsSaved() Then WScript.Quit 8
WScript.Echo "CLOSE_START"
measuredStart = Timer
operationOK = doc.Close(True)
LogElapsed "close", measuredStart
If Not operationOK Then WScript.Quit 6
WScript.Echo "CLOSE_OK"
measuredStart = Timer
app.Quit
LogElapsed "quit", measuredStart
WScript.Echo "QUIT_OK"
Sub LogElapsed(phaseName, started)
Dim elapsed
elapsed = Timer - started
If elapsed < 0 Then elapsed = elapsed + 86400
WScript.Echo "TIMING|" & phaseName & "|" & Replace(CStr(Round(elapsed, 3)), ",", ".")
End Sub
+329
View File
@@ -0,0 +1,329 @@
"""Optional read-only Mentor Verify status bridge client.
The Mentor EE 7.9 libraries are 32-bit MFC binaries. This module deliberately
does not load them from Python. It talks to a separately compiled x86 helper
over one JSON line at a time and treats a missing or malformed helper as an
unavailable authoritative source.
"""
from __future__ import annotations
from dataclasses import dataclass
import json
import ntpath
import os
from pathlib import Path
import subprocess
import queue
import sys
import threading
from typing import Any, Sequence
from uuid import uuid4
from .network_path import absolute_preserving_drive
class BridgeResponseError(RuntimeError):
"""The helper returned a response that cannot prove Verify state."""
class BridgeUnavailable(RuntimeError):
"""The optional x86 helper is not available on this machine."""
def __init__(self, path: Path, detail: str = "未找到可用的 32-bit Mentor 状态桥") -> None:
self.path = Path(path)
super().__init__(f"{detail}: {self.path}")
@dataclass(frozen=True)
class BridgeResult:
status: str
source: str
raw_status: int | str | None = None
detail: str = ""
response: dict[str, Any] | None = None
request_id: str = ""
block_name: str = ""
lmc_file: str = ""
def _normalized_path(value: str | Path) -> str:
raw = str(value).strip().replace("/", "\\")
if raw.startswith("\\\\"):
raw = "\\\\" + "\\".join(
part for part in raw.lstrip("\\").split("\\") if part
)
return ntpath.normcase(ntpath.normpath(raw))
def parse_bridge_response(
line: str,
*,
expected_request_id: str | None = None,
expected_block: str | None = None,
expected_lmc: str | Path | None = None,
) -> BridgeResult:
"""Parse one bridge response and require an authoritative status.
``UNKNOWN`` is intentionally rejected here. The caller can represent a
missing bridge separately, but a helper must never claim success without a
concrete Mentor status source.
"""
try:
payload = json.loads(line)
except (TypeError, ValueError) as error:
raise BridgeResponseError(f"状态桥返回非法 JSON: {error}") from error
if not isinstance(payload, dict):
raise BridgeResponseError("状态桥响应不是 JSON 对象")
if not payload.get("ok"):
raise BridgeResponseError(str(payload.get("error") or "状态桥调用失败"))
request_id = str(payload.get("request_id") or "")
block_name = str(payload.get("block_name") or "")
lmc_file = str(payload.get("mentor_lmc_file") or payload.get("lmc_file") or "")
if expected_request_id is not None and request_id != expected_request_id:
raise BridgeResponseError(
f"状态桥请求标识不匹配: expected={expected_request_id!r}, actual={request_id!r}"
)
if expected_block is not None and block_name != expected_block:
raise BridgeResponseError(
f"状态桥 CBB 标识不匹配: expected={expected_block!r}, actual={block_name!r}"
)
if expected_lmc is not None and (
not lmc_file or _normalized_path(lmc_file) != _normalized_path(expected_lmc)
):
raise BridgeResponseError(
f"状态桥中心库路径不匹配: expected={str(expected_lmc)!r}, actual={lmc_file!r}"
)
status = str(payload.get("status") or "").upper()
source = str(payload.get("source") or "").strip()
if status not in {"READY", "PENDING"} or not source:
raise BridgeResponseError(
"状态桥未返回 authoritative Verify 状态"
)
return BridgeResult(
status=status,
source=source,
raw_status=payload.get("raw_status"),
detail=str(payload.get("detail") or ""),
response=payload,
request_id=request_id,
block_name=block_name,
lmc_file=lmc_file,
)
def default_bridge_path() -> Path:
configured = os.environ.get("CBB_STATUS_BRIDGE", "").strip()
if configured:
return Path(configured).expanduser()
package_root = Path(__file__).resolve().parent
frozen_root = Path(getattr(sys, "_MEIPASS", package_root))
candidates = (
package_root / "status_bridge32.exe",
package_root / "bridge" / "CbbStatusBridge32.exe",
Path(sys.executable).resolve().parent / "tools" / "status_bridge" / "bin" / "CbbStatusBridge32.exe",
frozen_root / "tools" / "status_bridge" / "bin" / "CbbStatusBridge32.exe",
package_root.parent.parent / "tools" / "status_bridge" / "bin" / "CbbStatusBridge32.exe",
)
for candidate in candidates:
if candidate.is_file():
return candidate
return candidates[0]
class StatusBridgeClient:
"""Query a compiled x86 bridge without importing Mentor DLLs in Python."""
def __init__(self, executable: Path | None = None, *, env: dict[str, str] | None = None) -> None:
self.executable = Path(executable) if executable is not None else default_bridge_path()
self.env = dict(env or {})
def query(
self,
lmc_file: Path,
block_name: str,
*,
block_type: str = "RULP",
timeout_seconds: float = 10,
) -> BridgeResult:
if not self.executable.is_file():
raise BridgeUnavailable(self.executable)
request_id = uuid4().hex
resolved_lmc = str(absolute_preserving_drive(lmc_file))
request = {
"op": "is_verified",
"request_id": request_id,
"lmc_file": resolved_lmc,
"block_name": str(block_name),
"block_type": str(block_type),
}
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
child_env = os.environ.copy()
child_env.update(self.env)
try:
process = subprocess.Popen(
[str(self.executable)],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding="utf-8",
errors="replace",
creationflags=creationflags,
env=child_env,
)
except OSError as error:
raise BridgeUnavailable(self.executable, f"无法启动 32-bit Mentor 状态桥: {error}") from error
try:
stdout, stderr = process.communicate(
json.dumps(request, ensure_ascii=False) + "\n",
timeout=max(0.1, float(timeout_seconds)),
)
except subprocess.TimeoutExpired as error:
try:
process.kill()
except OSError:
pass
try:
process.communicate(timeout=5)
except subprocess.TimeoutExpired:
pass
raise BridgeResponseError("状态桥响应超时") from error
if process.returncode not in (0, None):
detail = (stderr or stdout).strip() or f"退出码 {process.returncode}"
raise BridgeResponseError(f"状态桥进程失败: {detail}")
line = next((item.strip() for item in stdout.splitlines() if item.strip()), "")
if not line:
raise BridgeResponseError("状态桥没有返回 JSON 响应")
return parse_bridge_response(
line,
expected_request_id=request_id,
expected_block=str(block_name),
expected_lmc=resolved_lmc,
)
class StatusBridgeServer:
"""Persistent JSONL bridge process with per-request deadlines."""
def __init__(self, executable: Path | None = None, *, env: dict[str, str] | None = None,
extra_args: Sequence[str] = ()) -> None:
self.executable = Path(executable) if executable is not None else default_bridge_path()
self.env = dict(env or {})
self.extra_args = tuple(extra_args)
self.process: subprocess.Popen[str] | None = None
self._responses: queue.Queue[str | BaseException | None] = queue.Queue()
self._reader: threading.Thread | None = None
self.restart_count = 0
self._warmup = False
def _command(self) -> list[str]:
if self.executable.suffix.casefold() == ".py":
return [sys.executable, str(self.executable), "--server", *self.extra_args]
return [str(self.executable), "--server", *self.extra_args]
def start(self) -> None:
if self.process is not None and self.process.poll() is None:
return
if not self.executable.is_file():
raise BridgeUnavailable(self.executable)
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
child_env = os.environ.copy()
child_env.update(self.env)
try:
self.process = subprocess.Popen(
self._command(), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace",
bufsize=1, creationflags=creationflags, env=child_env,
)
except OSError as error:
raise BridgeUnavailable(self.executable, f"无法启动常驻状态桥: {error}") from error
self._responses = queue.Queue()
self._warmup = True
self._reader = threading.Thread(target=self._read_responses, daemon=True)
self._reader.start()
def _read_responses(self) -> None:
process = self.process
responses = self._responses
if process is None or process.stdout is None:
return
try:
for line in process.stdout:
responses.put(line.strip())
except BaseException as error: # the supervisor converts this to one item failure
responses.put(error)
finally:
responses.put(None)
def query(self, lmc_file: Path, block_name: str, *, block_type: str = "RULP",
timeout_seconds: float = 10) -> BridgeResult:
self.start()
process = self.process
if process is None or process.stdin is None:
raise BridgeUnavailable(self.executable, "状态桥进程未运行")
request_id = uuid4().hex
resolved_lmc = str(absolute_preserving_drive(lmc_file))
request = {
"op": "is_verified", "request_id": request_id, "lmc_file": resolved_lmc,
"block_name": str(block_name), "block_type": str(block_type),
}
try:
process.stdin.write(json.dumps(request, ensure_ascii=False) + "\n")
process.stdin.flush()
except (OSError, ValueError) as error:
raise BridgeResponseError(f"状态桥写入失败: {error}") from error
try:
deadline = max(0.1, float(timeout_seconds))
# Process startup is outside the item operation. Give a freshly
# spawned Python/x86 helper a small one-time warm-up allowance so
# a short item deadline cannot turn interpreter startup into a
# false timeout.
if self._warmup:
deadline = max(deadline, 2.0)
response = self._responses.get(timeout=deadline)
except queue.Empty as error:
self.close()
raise BridgeResponseError("状态桥响应超时") from error
if response is None:
detail = f"退出码 {process.poll()}"
self.close()
raise BridgeResponseError(f"状态桥进程提前退出: {detail}")
if isinstance(response, BaseException):
self.close()
raise BridgeResponseError(f"状态桥读取失败: {response}") from response
self._warmup = False
return parse_bridge_response(
response,
expected_request_id=request_id,
expected_block=str(block_name),
expected_lmc=resolved_lmc,
)
def restart(self) -> None:
self.close()
self.restart_count += 1
self.start()
def close(self) -> None:
process, self.process = self.process, None
if process is None:
return
try:
if process.stdin is not None:
process.stdin.close()
except OSError:
pass
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=2)
except subprocess.TimeoutExpired:
try:
process.kill()
except OSError:
pass
try:
process.wait(timeout=2)
except subprocess.TimeoutExpired:
pass
Whitespace-only changes.
+427
View File
@@ -0,0 +1,427 @@
from pathlib import Path
from threading import Event
import os
import time
from collections import Counter
from PySide6.QtCore import QObject, QThreadPool, Signal, Qt
from PySide6.QtGui import QColor, QIcon
from PySide6.QtWidgets import (QWidget, QLineEdit, QPushButton, QFormLayout,
QTextEdit, QFileDialog, QHBoxLayout, QLabel, QSpinBox, QMessageBox, QToolButton,
QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox)
from PySide6.QtWidgets import QStyle
try:
from dx_productivity.trial_task_center.ui.workers import ServiceWorker
except ImportError:
from cbb_refresh_verify.ui.workers import ServiceWorker
from cbb_refresh_verify.library_reader import read_library_fast, scan_open_library_status
from cbb_refresh_verify.batch_status import authoritative_status_map
from cbb_refresh_verify.defaults import DEFAULT_TIMEOUT_SECONDS
from cbb_refresh_verify.network_path import LibraryPathLease, select_library_file
from cbb_refresh_verify.verify_runner import (VerifyRequest, preflight_skip_reason, run_verify,
run_batch, write_batch_report, failure_report_path,
native_lm_verify_enabled)
class ProgressSignals(QObject):
event = Signal(object)
STATUS_LABELS = {
'READY': '绿色 / Ready',
'PENDING': '待校验',
'UNKNOWN': '未知 / 需确认',
'UNAVAILABLE': '状态桥不可用',
'ERROR': '状态读取失败',
'TIMEOUT': '状态读取超时',
'MALFORMED': '状态桥协议错误',
'CRASHED': '状态桥崩溃',
}
def application_icon_path():
return Path(__file__).resolve().parents[1] / 'assets' / 'cbb_refresh_verify.ico'
class MainWindow(QWidget):
def __init__(self, reader=None, verifier=None, logging_context=None, data_root=None,
authoritative_status=True, path_lease_factory=None):
super().__init__()
self.setWindowTitle('CBB 刷新校验')
icon_path = application_icon_path()
if icon_path.is_file():
self.setWindowIcon(QIcon(str(icon_path)))
self.resize(850, 560)
self.verifier = verifier
self.logging_context = logging_context
self.path_lease_factory = path_lease_factory or LibraryPathLease.acquire
self.library_lease = None
self.mentor_lmc_path = None
self.data_root = Path(data_root or (logging_context.root if logging_context else Path(os.environ.get('LOCALAPPDATA', '.'))/'CbbRefreshVerify'))
if reader is not None:
self.reader = reader
elif authoritative_status and os.environ.get('CBB_STATUS_BRIDGE_MODE', 'authoritative').casefold() != 'legacy':
self.reader = lambda path: read_library_fast(
path,
status_reader=lambda p, names: authoritative_status_map(
names, p, self.data_root / 'status-scan.jsonl'),
)
else:
# Legacy icon/filesystem reader remains opt-in until the bridge is
# accepted on the target Mentor installation. It cannot override
# the authoritative path when that path is enabled explicitly.
self.reader = lambda path: read_library_fast(
path,
status_reader=lambda p, names: scan_open_library_status(
p, names, mapping_store=self.data_root/'image-status-map.json'),
)
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
self.busy = False; self.loaded_path = None; self.stop = Event(); self.ready_names = set()
self._row_by_name = {}
self.skipped_names = set(); self.skip_reasons = {}
self.signals = ProgressSignals(self); self.signals.event.connect(self._progress)
self.lmc_edit = QLineEdit()
self.libspec_edit = QLineEdit(os.environ.get('CBB_LIBSPEC', 'EE7.9'))
self.dms_edit = QLineEdit(os.environ.get('CBB_DMS_LOGIN_CONFIG', ''))
self.mentor_bin_edit = QLineEdit(os.environ.get('SDD_LM_BIN', ''))
self.native_lm_verify_check = QCheckBox('使用 Library Manager 原生 Verify(Win10 兼容测试)')
self.native_lm_verify_check.setChecked(native_lm_verify_enabled())
self.native_lm_verify_check.setToolTip(
'仅在 Win10 兼容测试时启用;默认仍使用已验证的 ReusableCircuit 直接流程。')
self.advanced_toggle = QToolButton(); self.advanced_toggle.setText('高级设置')
self.advanced_toggle.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_TitleBarUnshadeButton))
self.advanced_toggle.setCheckable(True); self.advanced_toggle.setChecked(False)
self.advanced_panel = QWidget()
advanced_layout = QFormLayout(self.advanced_panel)
advanced_layout.addRow('LibSpec', self.libspec_edit)
advanced_layout.addRow('DMS 登录配置', self.dms_edit)
advanced_layout.addRow('Mentor bin', self.mentor_bin_edit)
advanced_layout.addRow('触发方式', self.native_lm_verify_check)
self.advanced_panel.setVisible(False)
self.advanced_toggle.toggled.connect(self.advanced_panel.setVisible)
self.cbb_table = QTableWidget(0, 4)
self.cbb_table.setHorizontalHeaderLabels(['CBB 名称', '分区', '状态', '环境检查'])
self.cbb_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
for column in (1, 2, 3):
self.cbb_table.horizontalHeader().setSectionResizeMode(column, QHeaderView.ResizeToContents)
self.cbb_table.setSelectionBehavior(QTableWidget.SelectRows)
self.cbb_table.setMinimumHeight(150)
self.cbb_table.itemChanged.connect(lambda _item: self._update())
self.timeout_spin = QSpinBox(); self.timeout_spin.setRange(30, 1800); self.timeout_spin.setValue(DEFAULT_TIMEOUT_SECONDS); self.timeout_spin.setSuffix(' 秒 / 无进展')
self.load_button = QPushButton('读取 CBB'); self.load_button.clicked.connect(self.load_library)
self.browse_button = QPushButton('选择'); self.browse_button.clicked.connect(self.choose_library)
self.selected_batch_button = QPushButton('批量校验已选'); self.selected_batch_button.clicked.connect(self.verify_selected)
self.batch_button = QPushButton('批量校验全部 CBB'); self.batch_button.clicked.connect(self.verify_all)
self.stop_button = QPushButton('当前项完成后停止'); self.stop_button.clicked.connect(self.request_stop)
self.logs_button = QPushButton('打开日志目录'); self.logs_button.clicked.connect(self.open_logs)
self.recovery_button = QPushButton('打开异常证据'); self.recovery_button.setEnabled(False)
style = self.style()
self.load_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_BrowserReload))
self.browse_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_DirOpenIcon))
self.selected_batch_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_ArrowRight))
self.batch_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_MediaPlay))
self.stop_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_MediaStop))
self.logs_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_DirOpenIcon))
self.recovery_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_MessageBoxWarning))
self.recovery_button.setToolTip('打开当前异常 CBB 的证据目录,不切换 Windows 桌面。')
self.recovery_button.clicked.connect(self.recover)
self.recovery_path = None
self.status_label = QLabel('请选择并读取中心库。校验期间可以使用其他前台应用。')
self.status_label.setWordWrap(True)
self.output = QTextEdit(); self.output.setReadOnly(True)
# Integration emits repeated status snapshots. Keep the visible
# diagnostic buffer bounded so a 3,000-CBB run cannot grow the GUI
# document without limit.
self.output.document().setMaximumBlockCount(2000)
layout = QFormLayout(self)
row = QHBoxLayout(); row.addWidget(self.lmc_edit); row.addWidget(self.browse_button); row.addWidget(self.load_button)
layout.addRow('中心库 .lmc', row); layout.addRow(self.advanced_toggle); layout.addRow(self.advanced_panel)
layout.addRow('CBB 清单(勾选后可批量)', self.cbb_table); layout.addRow('超时', self.timeout_spin)
layout.addRow(QLabel('逐个刷新:命令行启动 ReusableCircuit PCB → Project Integration → 保存并关闭,全程不切换桌面、不移动鼠标。'
'填写 LibSpec 与 DMS 登录配置后,会先执行一次 ReuseBlockImporter 内容检查。'))
controls = QHBoxLayout()
for widget in (self.selected_batch_button, self.batch_button, self.stop_button, self.logs_button): controls.addWidget(widget)
layout.addRow(controls); layout.addRow(self.status_label); layout.addRow(self.output)
layout.addRow(self.recovery_button)
self.lmc_edit.textChanged.connect(self._invalidate)
for field in (self.libspec_edit, self.dms_edit, self.mentor_bin_edit):
field.textChanged.connect(lambda _text: self._update())
self.native_lm_verify_check.toggled.connect(lambda _checked: self._update())
self._update()
def _invalidate(self):
if self.loaded_path is not None and self.lmc_edit.text() != self.loaded_path:
self._release_library_lease()
self.loaded_path = None; self.mentor_lmc_path = None; self.cbb_table.setRowCount(0); self._row_by_name = {}
self.ready_names = set(); self.skipped_names = set(); self.skip_reasons = {}; self._update()
def _release_library_lease(self):
lease, self.library_lease = self.library_lease, None
if lease is None:
return
try:
lease.close()
except Exception as error:
if self.logging_context:
self.logging_context.logger.warning('library_lease_release_failed error=%s', error)
def _update(self):
# The refresh flow needs only the library and a CBB; LibSpec/DMS config
# are optional and only enable the extra contents check.
ready = not self.busy and self.loaded_path == self.lmc_edit.text() and self.cbb_table.rowCount() > 0
self.batch_button.setEnabled(ready and any(self.cbb_table.item(row, 0).text() not in self.ready_names
and self.cbb_table.item(row, 0).text() not in self.skipped_names
for row in range(self.cbb_table.rowCount())))
self.selected_batch_button.setEnabled(ready and bool(self._selected_names()))
for widget in (self.lmc_edit, self.browse_button, self.load_button, self.cbb_table,
self.timeout_spin, self.advanced_toggle, self.advanced_panel):
widget.setEnabled(not self.busy)
self.stop_button.setEnabled(self.busy and self.loaded_path is not None and not self.stop.is_set())
def choose_library(self):
path = QFileDialog.getOpenFileName(self, '选择中心库', '', 'LMC (*.lmc)')[0]
if path: self.lmc_edit.setText(path); self.load_library()
def _start(self, action, callback):
self.busy = True; self._update()
self.worker = ServiceWorker(action)
self.worker.signals.succeeded.connect(callback)
self.worker.signals.failed.connect(self._failed)
self.worker.signals.finished.connect(self._finished)
self.pool.start(self.worker)
def load_library(self):
if self.busy or not self.lmc_edit.text(): return
self._release_library_lease()
self.loaded_path = None; self.cbb_table.setRowCount(0); self._row_by_name = {}; self.ready_names = set()
self.skipped_names = set(); self.skip_reasons = {}
path = self.lmc_edit.text()
self.status_label.setText('正在读取中心库…')
def read():
import pythoncom
started = time.monotonic()
if self.logging_context:
self.logging_context.logger.info('library_load_start path=%s', path)
pythoncom.CoInitialize()
try:
lease = self.path_lease_factory(Path(path))
mentor_path = (select_library_file(lease.mentor_path)
if lease.mentor_path.is_dir() else lease.mentor_path)
if self.logging_context:
self.logging_context.logger.info(
'library_path_lease display=%s mentor=%s drive=%s remote=%s created=%s',
lease.display_path, mentor_path, lease.drive or '-',
lease.remote_root or '-', lease.created)
result = self.reader(mentor_path)
if self.logging_context:
statuses = Counter(record.status for record in result.records)
unknown = [record.name for record in result.records if record.status in {'UNKNOWN', 'UNAVAILABLE'}]
self.logging_context.logger.info(
'library_scan_result records=%s elapsed_ms=%s statuses=%s unknown_sample=%s',
len(result.records), int((time.monotonic() - started) * 1000),
dict(statuses), unknown[:20])
skip_reasons = {}
if not result.error:
for record in result.records:
if record.status != 'READY':
reason = preflight_skip_reason(mentor_path, record.name)
if reason:
skip_reasons[record.name] = reason
return result, skip_reasons, lease, mentor_path
except Exception:
if 'lease' in locals():
lease.close()
raise
finally: pythoncom.CoUninitialize()
def loaded(payload):
result, skip_reasons, lease, mentor_path = payload
if path != self.lmc_edit.text():
lease.close()
return
if result.error:
lease.close()
self.status_label.setText(result.error); return
self.library_lease = lease
self.mentor_lmc_path = mentor_path
self.loaded_path = path
self.cbb_table.setRowCount(0)
self.ready_names = {r.name for r in result.records if r.status == 'READY'}
self.skip_reasons = dict(skip_reasons)
self.skipped_names = set(skip_reasons)
# Populating a large library emits itemChanged for every cell.
# Block those signals and refresh controls once after the batch;
# otherwise _update() repeatedly scans the growing table (O(n^2)).
self.cbb_table.blockSignals(True)
self.cbb_table.setUpdatesEnabled(False)
try:
self.cbb_table.setRowCount(len(result.records))
for row, record in enumerate(result.records):
self._row_by_name[record.name] = row
item = QTableWidgetItem(record.name)
if record.status == 'READY' or record.name in self.skipped_names:
# Already green: nothing left to verify, so it cannot be queued.
item.setFlags(item.flags() & ~Qt.ItemIsUserCheckable)
else:
item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
item.setCheckState(Qt.Unchecked)
self.cbb_table.setItem(row, 0, item)
self.cbb_table.setItem(row, 1, QTableWidgetItem(record.partition_name))
status_text = STATUS_LABELS.get(record.status, record.status)
if record.name in self.skipped_names:
status_text = '跳过:缺少工程/PCB'
self.cbb_table.setItem(row, 2, QTableWidgetItem(status_text))
# Preflight touches each CBB's project and was previously run
# synchronously in this GUI callback, making large libraries
# appear frozen. The verify worker performs it when queued.
self.cbb_table.setItem(row, 3, QTableWidgetItem('未检查'))
if record.status == 'READY':
self._mark_row_ready(row)
elif record.name in self.skipped_names:
self.cbb_table.item(row, 0).setToolTip(self.skip_reasons[record.name])
self.cbb_table.item(row, 2).setToolTip(self.skip_reasons[record.name])
self.cbb_table.item(row, 3).setText('跳过')
for column in range(self.cbb_table.columnCount()):
cell = self.cbb_table.item(row, column)
if cell is not None:
cell.setBackground(QColor('#FFF8E1'))
finally:
self.cbb_table.setUpdatesEnabled(True)
self.cbb_table.blockSignals(False)
ready_count = len(self.ready_names)
unavailable_count = sum(record.status == 'UNAVAILABLE' for record in result.records)
read_error_count = sum(record.status in {'ERROR', 'TIMEOUT', 'MALFORMED', 'CRASHED'}
for record in result.records)
suffix = ''
if unavailable_count:
suffix += f' 状态桥不可用 {unavailable_count} 个。'
if read_error_count:
suffix += f' 状态读取失败 {read_error_count} 个。'
self.status_label.setText(
f'已读取 {len(result.records)} 个 CBB,其中 Ready {ready_count} 个,'
f'缺文件跳过 {len(self.skipped_names)} 个。{suffix}')
self._start(read, loaded)
def _request(self, name):
return VerifyRequest(Path(self.mentor_lmc_path or self.loaded_path), name, self.data_root/'evidence',
libspec=self.libspec_edit.text().strip(),
dms_login_config=self.dms_edit.text().strip(),
mentor_bin=self.mentor_bin_edit.text().strip(),
mapped_drive=getattr(self.library_lease, 'drive', ''),
mapped_remote_root=getattr(self.library_lease, 'remote_root', ''),
timeout_seconds=self.timeout_spin.value(), logging_context=self.logging_context,
native_lm_verify=self.native_lm_verify_check.isChecked())
def _selected_names(self):
names = []
for row in range(self.cbb_table.rowCount()):
item = self.cbb_table.item(row, 0)
if item and item.checkState() == Qt.Checked and (item.flags() & Qt.ItemIsUserCheckable):
names.append(item.text())
return names
def verify_selected(self):
self._run(self._selected_names())
def verify_all(self):
names = [self.cbb_table.item(row, 0).text() for row in range(self.cbb_table.rowCount())]
self._run([name for name in names if name not in self.ready_names and name not in self.skipped_names])
def _run(self, names):
if self.busy or not self.loaded_path: return
names = [name for name in names if name not in self.ready_names and name not in self.skipped_names]
if not names:
self.status_label.setText('没有需要校验的 CBB(全部已经是绿色 / Ready)。')
self._update()
return
requests = [self._request(name) for name in names]
self.stop.clear(); self.recovery_path = None; self.recovery_button.setEnabled(False)
self.output.clear(); self.status_label.setText(f'正在校验:共 {len(names)} 个 CBB')
def action():
from cbb_refresh_verify.verify_runner import read_library_flag_if_available, run_verify
verifier = self.verifier or (lambda req: run_verify(
req, progress=lambda e: self.signals.event.emit(e),
flag_reader=read_library_flag_if_available))
results = run_batch(requests, verifier=verifier, stop=self.stop,
progress=lambda name, result: self.signals.event.emit({'block': name, 'stage': result.status, 'detail': result.stderr, 'evidence': str(result.evidence_path or '')}))
report = write_batch_report(requests, results, self.data_root/'reports')
return results, report
self._start(action, self._batch_done)
def _progress(self, event):
line = f"{event.get('block', '')} | {event.get('stage', '')}"
for key in ('detail', 'error', 'action', 'statuses', 'evidence'):
if event.get(key): line += f' | {event[key]}'
self.output.append(line)
block = event.get('block'); stage = event.get('stage')
if block and stage in {'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT', 'SKIPPED'}:
row = self._row_by_name.get(block)
if row is not None:
if stage == 'PASS':
self.cbb_table.item(row, 2).setText('绿色 / Ready')
self.cbb_table.item(row, 3).setText('PASS')
self.ready_names.add(block)
self._mark_row_ready(row)
else:
detail = str(event.get('detail') or event.get('error') or '').strip()
label = str(stage) if not detail else f'{stage}: {detail[:96]}'
self.cbb_table.item(row, 3).setText(label)
if detail:
self.cbb_table.item(row, 3).setToolTip(detail)
if self.logging_context: self.logging_context.logger.info('cbb_progress %s', line)
def _mark_row_ready(self, row):
"""Make a verified row visibly complete and remove it from the queue."""
name_item = self.cbb_table.item(row, 0)
if name_item is None:
return
name_item.setCheckState(Qt.Unchecked)
name_item.setFlags(name_item.flags() & ~Qt.ItemIsUserCheckable)
for column in range(self.cbb_table.columnCount()):
cell = self.cbb_table.item(row, column)
if cell is not None:
cell.setBackground(QColor('#E8F5E9'))
def _batch_done(self, outcome):
results, report = outcome
for result in results:
if not result.safe_to_continue and result.evidence_path:
self.recovery_path = result.evidence_path.parent
self.recovery_button.setEnabled(self.recovery_path.is_dir())
passed = sum(r.status == 'PASS' for r in results)
skipped = sum(r.status == 'SKIPPED' for r in results)
failed = len(results)-passed-skipped
text = (f'已结束:成功 {passed},失败 {failed},预检跳过 {len(self.skipped_names)},'
f'队列未执行 {skipped}。\n完整日志:{report}\n仅失败日志:{failure_report_path(report)}')
self.status_label.setText(text); self.output.append(text)
self.summary = QMessageBox(self)
self.summary.setWindowTitle('CBB 校验结果'); self.summary.setText(text)
self.summary.setIcon(QMessageBox.Warning if failed else QMessageBox.Information)
# Modeless notification: do not force activation or steal keyboard focus.
from PySide6.QtCore import Qt
self.summary.setAttribute(Qt.WA_ShowWithoutActivating)
self.summary.show()
def request_stop(self):
self.stop.set(); self.status_label.setText('已请求停止;当前 CBB 完成或超时后停止队列。'); self._update()
def _failed(self, error):
self.status_label.setText(str(error)); self.output.append(str(error))
if self.logging_context: self.logging_context.logger.error('cbb_worker_failed %s', error)
def _finished(self):
self.busy = False; self._update()
def open_logs(self):
self.data_root.mkdir(parents=True, exist_ok=True); os.startfile(str(self.data_root))
def recover(self):
if not self.recovery_path: return
try: os.startfile(str(self.recovery_path))
except Exception as error: self._failed(error)
def closeEvent(self, event):
if self.busy:
self.request_stop(); event.ignore()
else:
self._release_library_lease()
event.accept()
+32
View File
@@ -0,0 +1,32 @@
"""Small local fallback for the replacement tool's reusable Qt worker."""
from __future__ import annotations
from collections.abc import Callable
from typing import Any
from PySide6.QtCore import QObject, QRunnable, Signal, Slot
class WorkerSignals(QObject):
succeeded = Signal(object)
failed = Signal(object)
finished = Signal()
class ServiceWorker(QRunnable):
"""Run one callable on a QThreadPool when the shared worker is unavailable."""
def __init__(self, action: Callable[[], Any]) -> None:
super().__init__()
self.action = action
self.signals = WorkerSignals()
@Slot()
def run(self) -> None:
try:
self.signals.succeeded.emit(self.action())
except Exception as error:
self.signals.failed.emit(error)
finally:
self.signals.finished.emit()
@@ -0,0 +1,149 @@
"""Bounded, diagnostic-only snapshots for a native Mentor Verify failure.
Only known paths are inspected. No database/lock repair, recursive traversal,
or sustained file handles are allowed here. The parent repeats log collection
once after cleanup if the worker was killed while a native file was open.
"""
from pathlib import Path
import json
import os
import stat
import tempfile
import subprocess
import sys
import time
NATIVE_LOG_MAX_BYTES = 128 * 1024
def _write_record(path, record):
try:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
except OSError as error:
record['evidence_error'] = str(error)
return record
def _path_metadata(path, *, directory=False):
item = {'path': str(path), 'exists': None}
try:
info = path.stat()
item.update(exists=True, size_bytes=info.st_size, mtime_ns=info.st_mtime_ns)
if directory:
item['is_directory'] = stat.S_ISDIR(info.st_mode)
else:
item['readable'] = False
if not stat.S_ISREG(info.st_mode):
item['error'] = 'expected a regular file'
else:
with path.open('rb') as stream:
stream.read(1)
item['readable'] = True
except FileNotFoundError:
item['exists'] = False
except OSError as error:
item['error'] = str(error)
return item
def collect_preflight_diagnostics(pcb_path, evidence_root):
"""One-shot metadata/readability and unique scratch-file writability probe.
Layout_Temp is generated by Mentor. Its absence is never a preflight gate.
This runs in the supervised worker BEFORE Mentor starts, never in polling.
"""
directory = Path(pcb_path).parent
paths = [_path_metadata(directory, directory=True)]
paths.extend(_path_metadata(directory/relative) for relative in (
'Layout/JobPrefsDB.jpf', 'Layout_Temp/JobPrefsDB.jpf',
'Work/Layout_Temp/JobPrefsDB.jpf'))
warnings = [f"{item['path']}: {item.get('error') or 'absent (may be generated by Mentor)'}"
for item in paths if item['exists'] is not True or item.get('error')]
record = {'non_blocking': True, 'paths': paths, 'warnings': warnings,
'directory_writable': False,
'note': 'Missing temporary JobPrefs paths are diagnostic only; no files repaired.'}
# tempfile uses exclusive creation and delete-on-close for this new file;
# never construct a deletion path or touch an existing library-side file.
try:
with tempfile.NamedTemporaryFile(mode='wb', prefix='.cbb-verify-write-probe-',
suffix='.tmp', dir=directory):
pass
record['directory_writable'] = True
except OSError as error:
record['directory_write_error'] = str(error)
warnings.append(f'{directory}: create/close write probe failed: {error}')
return _write_record(Path(evidence_root)/'diagnostics/preflight.json', record)
def collect_native_failure_logs(pcb_path, evidence_root, *, max_bytes=NATIVE_LOG_MAX_BYTES):
"""Copy the last bounded bytes of known logs, preserving native multi-line text.
Evidence is binary so native ANSI/UTF-16 encodings are not damaged. Each
original path/size/truncation/error is recorded in a UTF-8 JSON manifest.
Native sources are opened read-only and promptly closed, never modified.
"""
pcb_directory = Path(pcb_path).parent
destination = Path(evidence_root)/'diagnostics/native-logs'
record = {'non_blocking': True, 'collected_at': time.strftime('%Y-%m-%d %H:%M:%S'),
'max_bytes_per_file': max(1, min(int(max_bytes), 256 * 1024)), 'files': []}
try:
destination.mkdir(parents=True, exist_ok=True)
except OSError as error:
record['evidence_error'] = str(error)
return record
sources = [('pcb-logfiles', pcb_directory/'LogFiles'/name)
for name in ('PCBLogFile.txt', 'ForwardAnnotation.txt', 'PartPkg.log',
'MsgBoxResponse.log', 'ReusableBlock.txt')]
sources.extend((('pcb-root', pcb_directory/'PCBLogFile.txt'),
('pcb-root', pcb_directory/'ReusableBlock.txt'),
('work-root', pcb_directory.parent/'ReusableBlock.txt')))
for label, source in sources:
item = {'source': str(source), 'exists': None}
record['files'].append(item)
try:
with source.open('rb') as stream:
stream.seek(0, os.SEEK_END)
size = stream.tell()
item['mtime_ns'] = os.fstat(stream.fileno()).st_mtime_ns
stream.seek(max(0, size-record['max_bytes_per_file']))
data = stream.read(record['max_bytes_per_file'])
item.update(exists=True, original_size_bytes=size,
truncated=size > record['max_bytes_per_file'])
target = destination/(label+'-'+source.name)
target.write_bytes(data)
item.update(evidence=str(target), copied_bytes=len(data))
except FileNotFoundError:
item['exists'] = False
except OSError as error:
item['error'] = str(error)
return _write_record(destination.parent/'native-logs.json', record)
def failure_logs_main(request_path):
job = json.loads(Path(request_path).read_text(encoding='utf-8'))
collect_native_failure_logs(job['pcb'], job['root'])
return 0
def capture_failure_logs_with_timeout(request_path, *, timeout_seconds=8):
"""Post-cleanup retry in a killable helper, not a potentially stuck SMB thread."""
request_path = Path(request_path)
command = ([sys.executable] if getattr(sys, 'frozen', False) else
[sys.executable, '-m', 'cbb_refresh_verify'])
command += ['--collect-failure-logs', str(request_path)]
record = {'status': 'ERROR', 'timeout_seconds': timeout_seconds}
try:
outcome = subprocess.run(command, capture_output=True, timeout=timeout_seconds,
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
record.update(status='COMPLETE' if outcome.returncode == 0 else 'ERROR',
exit_code=outcome.returncode)
if outcome.stderr:
record['error'] = outcome.stderr[-4096:].decode('utf-8', errors='replace')
except subprocess.TimeoutExpired:
# subprocess.run kills and reaps this child; it never launches children.
record.update(status='TIMEOUT', error='Native log collection budget exceeded; original Verify result unchanged.')
except OSError as error:
record['error'] = str(error)
return _write_record(request_path.parent/'diagnostics/native-log-capture.json', record)
+156
View File
@@ -0,0 +1,156 @@
"""Read-only probe for Mentor's private CBB Verify exports.
The probe deliberately stops at export discovery. It never calls
``VerifyReuseBlock`` or ``UnVerifyReuseBlock`` because those functions use a
private 32-bit MFC ``CFilename`` ABI that has not been reconstructed safely.
"""
from __future__ import annotations
from dataclasses import dataclass
import json
import os
from pathlib import Path
import subprocess
import sys
from typing import Any, Mapping
KNOWN_EXPORTS = (
"IsVerifiedReuseBlock",
"GetStatusRBInContextOfCL",
"VerifyReuseBlock",
"UnVerifyReuseBlock",
"GetReusableCircuitVerificationStatus",
)
class ProbeResponseError(ValueError):
"""The helper returned a response outside the probe contract."""
@dataclass(frozen=True)
class ExportInfo:
name: str
found: bool
address: str
@dataclass(frozen=True)
class ExportProbeResult:
dll_path: str
architecture: str
exports: tuple[ExportInfo, ...]
write_enabled: bool
write_reason: str
response: Mapping[str, Any]
def export(self, name: str) -> ExportInfo:
for item in self.exports:
if item.name == name:
return item
raise KeyError(name)
def _require_mapping(value: Any, label: str) -> Mapping[str, Any]:
if not isinstance(value, Mapping):
raise ProbeResponseError(f"探测响应字段 {label} 不是对象")
return value
def parse_export_probe(raw: str) -> ExportProbeResult:
try:
payload = json.loads(raw)
except json.JSONDecodeError as error:
raise ProbeResponseError(f"探测响应不是 JSON: {error}") from error
payload = _require_mapping(payload, "root")
if payload.get("ok") is not True or payload.get("probe") != "exports":
raise ProbeResponseError(str(payload.get("error") or "导出探测失败"))
architecture = str(payload.get("architecture") or "").lower()
if architecture != "x86":
raise ProbeResponseError(f"导出探测桥架构异常: {architecture or 'empty'}")
dll_path = str(payload.get("dll_path") or "").strip()
if not dll_path:
raise ProbeResponseError("导出探测未返回 DLL 路径")
write_call = _require_mapping(payload.get("write_call"), "write_call")
enabled = write_call.get("enabled")
if enabled is not False:
raise ProbeResponseError("写接口探测桥不能启用写调用")
reason = str(write_call.get("reason") or "").strip()
if not reason:
raise ProbeResponseError("写接口探测必须说明未启用原因")
raw_exports = _require_mapping(payload.get("exports"), "exports")
exports: list[ExportInfo] = []
for name in KNOWN_EXPORTS:
item = _require_mapping(raw_exports.get(name), f"exports.{name}")
found = item.get("found")
if not isinstance(found, bool):
raise ProbeResponseError(f"导出 {name} 的 found 字段非法")
address = str(item.get("address") or "")
if found and not address:
raise ProbeResponseError(f"导出 {name} 已找到但没有地址")
exports.append(ExportInfo(name=name, found=found, address=address))
return ExportProbeResult(
dll_path=dll_path,
architecture=architecture,
exports=tuple(exports),
write_enabled=False,
write_reason=reason,
response=dict(payload),
)
def default_probe_path() -> Path:
configured = os.environ.get("CBB_VERIFY_PROBE", "").strip()
if configured:
return Path(configured).expanduser()
package_root = Path(__file__).resolve().parent
frozen_root = Path(getattr(sys, "_MEIPASS", package_root))
candidates = (
package_root / "verify_probe32.exe",
package_root / "bridge" / "VerifyProbe32.exe",
Path(sys.executable).resolve().parent / "tools" / "status_bridge" / "bin" / "VerifyProbe32.exe",
frozen_root / "tools" / "status_bridge" / "bin" / "VerifyProbe32.exe",
package_root.parent.parent / "tools" / "status_bridge" / "bin" / "VerifyProbe32.exe",
)
for candidate in candidates:
if candidate.is_file():
return candidate
return candidates[0]
def probe_exports(
executable: Path | None = None,
*,
env: Mapping[str, str] | None = None,
timeout_seconds: float = 10,
) -> ExportProbeResult:
helper = Path(executable) if executable is not None else default_probe_path()
if not helper.is_file():
raise FileNotFoundError(f"找不到 Verify 导出探测桥: {helper}")
child_env = os.environ.copy()
child_env.update(dict(env or {}))
try:
process = subprocess.run(
[str(helper), "--probe-exports"],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=max(0.1, float(timeout_seconds)),
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
env=child_env,
check=False,
)
except subprocess.TimeoutExpired as error:
raise ProbeResponseError("导出探测桥响应超时") from error
lines = [line.strip() for line in process.stdout.splitlines() if line.strip()]
if process.returncode != 0:
detail = (process.stderr or process.stdout).strip() or f"退出码 {process.returncode}"
raise ProbeResponseError(f"导出探测桥失败: {detail}")
if not lines:
raise ProbeResponseError("导出探测桥没有返回 JSON")
return parse_export_probe(lines[0])
+970
View File
@@ -0,0 +1,970 @@
"""Serial Verify supervisor.
Each CBB gets one isolated, bounded automation worker on a private Windows
desktop. The worker reproduces the observed refresh flow: invoke the CBB's
native Library Manager Verify action, bind the resulting ReusableCircuit PCB,
verify the document identity, run Project Integration, save the Reusable Block
cell and close. Optionally the official
``ReuseBlockImporter.exe -chkContents`` check runs first when a LibSpec and a
DMS login configuration are supplied.
Nothing here injects mouse or keyboard input or edits the central library. The
native menu invocation happens on the worker's private desktop.
"""
from dataclasses import asdict, dataclass, field, replace
from pathlib import Path
import json
import os
import platform
import re
import struct
import subprocess
import sys
import time
from uuid import uuid4
from .network_path import absolute_preserving_drive
from .runtime_timing import RunTimings
from .defaults import DEFAULT_TIMEOUT_SECONDS
SUCCESS_TEXT = re.compile(r'content checking completed successfully', re.IGNORECASE)
ERROR_TEXT = re.compile(r'failed|error|cannot connect|bad data', re.IGNORECASE)
INVALID_NAME_CHARS = '\\/:*?"<>|'
@dataclass(frozen=True)
class VerifyRequest:
lmc_file: Path
block_name: str
evidence_dir: Path
libspec: str = ''
dms_login_config: str = ''
mentor_bin: str = ''
# PCB startup on EE7.9 includes iCDB recovery and COM registration. The
# previous 30-second UI default was shorter than the observed startup
# window on this machine and caused a false timeout before document attach.
timeout_seconds: int = DEFAULT_TIMEOUT_SECONDS
logging_context: object | None = None
# The production default stays on an isolated desktop. The explicit
# interactive mode is reserved for a real-input compatibility test on
# machines where EE7.9 cannot dispatch the tree menu on a private desktop.
interactive_input: bool = False
# The native Library Manager menu route is opt-in until a machine's menu
# dispatch has been proven. The flag is serialized to the worker so a
# Win10 compatibility run can select it explicitly.
native_lm_verify: bool = False
# A reserved iCDB range is a host-wide prerequisite failure. Do not
# launch a PCB that is guaranteed to time out; batch orchestration will
# record this item and continue with the next one.
strict_port_check: bool = True
# A mapped drive can be invisible to an elevated/private worker on Win10.
# Preserve the parent session's mapping identity so the worker can restore
# it before launching Library Manager/PCB.
mapped_drive: str = ''
mapped_remote_root: str = ''
@dataclass(frozen=True)
class VerifyResult:
status: str
stderr: str = ''
stdout: str = ''
evidence_path: Path | None = None
safe_to_continue: bool = True
library_flag: str = 'UNKNOWN'
library_flag_detail: str = ''
report_path: Path | None = None
content_check_exit_code: int | None = None
error_category: str = ""
error_stage: str = ""
bridge_attempts: tuple[dict, ...] = ()
timings_seconds: dict[str, float] = field(default_factory=dict)
incomplete_timing_phases: tuple[str, ...] = ()
def resolve_importer(mentor_bin: str | None = None) -> Path:
"""Configured bin first, then the EE7.9.5 environment defaults."""
candidates = []
if mentor_bin:
configured = Path(mentor_bin)
if configured.is_file() and configured.name.casefold() == 'reuseblockimporter.exe':
candidates.append(configured.parent)
else:
candidates.append(configured)
if configured.name.casefold() == 'sdd_home':
candidates.append(configured / 'lm' / 'win32' / 'bin')
from .mentor_paths import discover_sdd_home
discovered = discover_sdd_home(mentor_bin)
if discovered is not None:
candidates.append(discovered / 'lm' / 'win32' / 'bin')
for variable in ('SDD_LM_BIN', 'SDD_HOME'):
value = os.environ.get(variable)
if not value:
continue
root = Path(value)
candidates.append(root if root.name.lower() == 'bin' else root/'lm'/'win32'/'bin')
candidates.append(Path(r'D:\Mentor\7.9.5EE\SDD_HOME\lm\win32\bin'))
for candidate in candidates:
executable = candidate/'ReuseBlockImporter.exe'
if executable.is_file():
return executable
raise ValueError('ReuseBlockImporter.exe 未找到;请设置 SDD_LM_BIN')
def build_content_check_command(request, executable) -> tuple[str, ...]:
"""The documented Logical-Physical contents check invocation."""
return (str(executable), '-lmcFile', str(request.lmc_file), '-blockName', request.block_name,
'-logicalType', 'LP', '-chkContents', '-libSpec', str(request.libspec),
'-dmsLoginConfig', str(request.dms_login_config))
def contents_report_path(lmc_file, block_name) -> Path:
safe_name = re.sub(f'[{re.escape(INVALID_NAME_CHARS)}]', '_', str(block_name))
return Path(lmc_file).parent/'LogFiles'/f'restorerb_RULP_{safe_name}_contents.log'
def classify_output(exit_code: int | None, output: str, *, timed_out: bool = False) -> str:
"""Never invent success: PASS needs the success text and no error marker."""
if timed_out:
return 'TIMEOUT'
if SUCCESS_TEXT.search(output) and not ERROR_TEXT.search(output):
return 'PASS'
if ERROR_TEXT.search(output):
return 'FAIL'
if exit_code not in (None, 0):
return 'FAIL'
return 'UNKNOWN'
def preflight(request):
"""Validate the library entry and its ReusableCircuit sources before launch."""
library = absolute_preserving_drive(request.lmc_file)
name = request.block_name
if not name or name in ('.', '..') or any(character in name for character in INVALID_NAME_CHARS):
raise ValueError('CBB 名称非法')
if not library.is_file():
raise ValueError(f'中心库不存在: {library}')
work = library.parent/'ReusableBlocksLP'/name/'Work'
projects = list(work.glob('*.prj'))
if len(projects) != 1:
raise ValueError(f'{name}: 缺少或无法唯一确定 Work 下的工程 PRJ')
project = absolute_preserving_drive(projects[0])
content = project.read_text(encoding='utf-8', errors='replace')
refs = re.findall(r'^KEY PCBDesignPath "([^"]+)"', content, re.M)
if not refs:
raise ValueError(f'{name}: 工程没有 PCBDesignPath')
pcb = absolute_preserving_drive(project.parent/refs[0])
if not pcb.is_relative_to(absolute_preserving_drive(work)):
raise ValueError(f'{name}: PCB 引用越出当前 CBB,停止操作: {pcb}')
if not pcb.is_file() or not (pcb.parent/'Layout'/'LayoutDB.lyt').is_file():
raise ValueError(f'{name}: 缺少 PCB 或布局数据库: {pcb}')
return project, pcb
def preflight_skip_reason(lmc_file, block_name):
"""Return a user-facing skip reason for an import-incomplete CBB.
This is intentionally narrower than ``preflight``: only local source
structure problems are excluded before a batch starts. Runtime failures
such as ports, DMS, COM, or Project Integration remain normal per-item
failures and are still attempted when the user queues them.
"""
library = absolute_preserving_drive(lmc_file)
if not library.is_file():
return ''
work = library.parent / 'ReusableBlocksLP' / str(block_name) / 'Work'
if not work.is_dir():
return ''
request = VerifyRequest(library, str(block_name), library.parent / '.cbb-preflight-evidence')
try:
preflight(request)
except Exception as error:
detail = str(error)
if any(marker in detail for marker in ('缺少或无法唯一确定 Work 下的工程 PRJ',
'工程没有 PCBDesignPath',
'缺少 PCB 或布局数据库')):
return detail
return ''
def _run_process(command, timeout_seconds, cwd):
"""Run the importer, draining both pipes while it works (no pipe deadlock)."""
process = subprocess.Popen(command, cwd=str(cwd), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
try:
stdout, stderr = process.communicate(timeout=timeout_seconds)
return process.returncode, stdout.decode('utf-8', errors='replace'), stderr.decode('utf-8', errors='replace'), False
except subprocess.TimeoutExpired:
# A timed-out importer may have spawned a child that still owns the
# pipes. Bound both tree termination and the final drain so a hung
# helper cannot turn a 30-second item timeout into an unbounded wait.
try:
subprocess.run(['taskkill', '/PID', str(process.pid), '/T', '/F'],
capture_output=True, timeout=5,
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
except (OSError, subprocess.TimeoutExpired):
pass
try:
process.kill()
except OSError:
pass
try:
stdout, stderr = process.communicate(timeout=5)
except subprocess.TimeoutExpired:
stdout, stderr = b'', b''
return None, stdout.decode('utf-8', errors='replace'), stderr.decode('utf-8', errors='replace'), True
def _stop_worker(process, *, timeout=5):
"""Best-effort worker tree termination that never masks the item result."""
try:
process.kill()
except Exception:
pass
try:
process.wait(timeout=timeout)
except Exception:
pass
def _normalize_bridge_result(probe):
from .status_bridge import BridgeResult
if not isinstance(probe, BridgeResult):
detail = str(probe[1]) if isinstance(probe, tuple) and len(probe) > 1 else str(probe)
return BridgeResult('MALFORMED', '', None,
'BRIDGE_RESULT_INVALID: 非权威桥接器结果;' + detail)
if probe.status in {'READY', 'PENDING'} and (
probe.source != 'IsVerifiedReuseBlock'
or probe.raw_status != (1 if probe.status == 'READY' else 0)):
return BridgeResult('MALFORMED', probe.source, probe.raw_status,
'BRIDGE_RESULT_INVALID: status/source/raw_status 不一致')
return probe
def read_library_flag_with_retry(reader, library, block_name, *, attempts=3,
delays=(0.0, 3.0, 5.0), sleep=None, on_attempt=None):
"""Bounded read-only bridge retries; never repeat Verify or promote PENDING."""
from .status_bridge import BridgeResult
sleep = sleep or time.sleep
last = BridgeResult('UNAVAILABLE', '', None, '状态桥没有返回结果')
for index in range(max(1, int(attempts))):
if index > 0:
delay = delays[min(index, len(delays)-1)] if delays else 0
sleep(max(0.0, float(delay)))
started = time.monotonic()
try:
last = _normalize_bridge_result(reader(library, block_name))
except Exception as error:
last = BridgeResult('UNAVAILABLE', '', None, 'BRIDGE_UNAVAILABLE: ' + str(error))
if on_attempt:
on_attempt({'attempt': index + 1, 'status': last.status,
'source': last.source, 'raw_status': last.raw_status,
'detail': last.detail,
'query_seconds': round(time.monotonic()-started, 6)})
if last.status in {'READY', 'MALFORMED'}:
return last
return last
def classify_failure_category(detail):
text = str(detail or '')
lower = text.casefold()
if 'tf_floatinglangbar_wndtitle' in lower or 'cicerouiwndframe' in lower:
return 'TOOL_FALSE_DIALOG'
if 'could not load job preferences db' in lower or 'unable to create local cell library' in lower:
return 'MENTOR_LOCAL_CELL_LIBRARY'
if ('database_load_failed' in lower
or 'problem encountered while opening one of the database files' in lower
or 'database load is being terminated' in lower):
return 'MENTOR_DATABASE_LOAD_FAILED'
if 'project integration error' in lower or 'project_integration_failed' in lower:
return 'MENTOR_PROJECT_INTEGRATION'
if 'save_reusable_block_failed' in lower or 'error saving the reusable block' in lower:
return 'MENTOR_SAVE_FAILED'
if 'design_server_failed' in lower or 'could not run server' in lower or 'could not bring it alive' in lower:
return 'ENVIRONMENT_DESIGN_SERVER'
if 'bridge_unavailable' in lower or '权威状态读取失败' in text:
return 'BRIDGE_UNAVAILABLE'
if 'bridge_result_invalid' in lower:
return 'BRIDGE_RESULT_INVALID'
if 'pending' in lower and 'isverifiedreuseblock' in lower:
return 'MENTOR_VERIFY_NOT_COMMITTED'
if 'cert' in lower and ('incomplete' in lower or '成果' in text):
return 'TOOL_CERT_DIAGNOSTIC'
if 'unknown_dialog' in lower or 'dialog' in lower:
return 'TOOL_DIALOG_SUPERVISOR'
if 'timeout' in lower or '超时' in text:
return 'TOOL_TIMEOUT'
return 'UNCLASSIFIED'
def read_library_flag_if_available(library, block_name):
"""Read the authoritative Mentor Verify state through the x86 bridge.
Unit tests replace this external boundary; production never accepts Cert
files or legacy tree readers as a substitute for this gold standard.
"""
from .status_bridge import StatusBridgeClient
return StatusBridgeClient(
env={'CBB_STATUS_BRIDGE_ALLOW_PRIVATE': '1'}
).query(Path(library), block_name)
def apply_post_verify_status(result, bridge_result):
"""Only the authoritative bridge can confirm READY, never a Cert/tuple/icon."""
if result.status != 'PASS':
return result # a pre-existing READY cannot erase a real execution error
bridge_result = _normalize_bridge_result(bridge_result)
if bridge_result.status == 'READY':
return replace(result, library_flag='GREEN', library_flag_detail=(
f'READY ({bridge_result.source}, raw={bridge_result.raw_status})'))
detail = bridge_result.detail or (
f'执行已完成,但权威状态仍为 {bridge_result.status} '
f'({bridge_result.source}, raw={bridge_result.raw_status})')
pending = bridge_result.status == 'PENDING'
return replace(result, status='FAIL',
stderr='\n'.join(part for part in (result.stderr, detail) if part),
library_flag='NOT_GREEN' if pending else 'UNKNOWN', library_flag_detail=detail,
error_category=('MENTOR_VERIFY_NOT_COMMITTED' if pending else
'BRIDGE_RESULT_INVALID' if bridge_result.status == 'MALFORMED' else 'BRIDGE_UNAVAILABLE'),
error_stage='library_flag', safe_to_continue=True)
def worker_command(request_path):
if getattr(sys, 'frozen', False):
return [sys.executable, '--verify-worker', str(request_path)]
return [sys.executable, '-m', 'cbb_refresh_verify', '--verify-worker', str(request_path)]
def phase_for_event(event, current=None):
from .dialog_models import DialogPhase
stage = str(event.get('stage', ''))
mapping = {
'lm_launch': DialogPhase.PCB_STARTING,
'lm_started': DialogPhase.PCB_STARTING,
'lm_ready': DialogPhase.PCB_STARTING,
'lm_session_ready': DialogPhase.PCB_STARTING,
'verify_invoke': DialogPhase.PCB_STARTING,
'verify_invoke_returned': DialogPhase.PCB_STARTING,
'pcb_launch': DialogPhase.PCB_STARTING,
'pcb_started': DialogPhase.PCB_STARTING,
'com_wait': DialogPhase.DOCUMENT_ATTACH,
'identity_wait': DialogPhase.DOCUMENT_ATTACH,
'identity_verified': DialogPhase.IDENTITY_CHECK,
'license_key_requested': DialogPhase.LICENSE_ACQUISITION,
'license_token_received': DialogPhase.LICENSE_ACQUISITION,
'document_validated': DialogPhase.VALIDATE,
'integration_status': DialogPhase.PROJECT_INTEGRATION,
'integration_action': DialogPhase.PROJECT_INTEGRATION,
'integration_error': DialogPhase.PROJECT_INTEGRATION,
'save_start': DialogPhase.SAVE,
'save_helper': DialogPhase.SAVE,
'save_progress': DialogPhase.SAVE,
'save_quit_recovered': DialogPhase.CLOSE,
'saved_and_closed': DialogPhase.CLOSE,
'pcb_exit_recovered': DialogPhase.CLOSE,
'complete': DialogPhase.CLOSE,
}
return mapping.get(stage, current or DialogPhase.PCB_STARTING)
def classify_verify_dispatch(*, verify_invoked, invoke_returned, target_pid, observation):
"""Classify a returned Verify command that never started its PCB.
UI Automation can report a successful ``InvokePattern`` call even when
Library Manager only closed the popup and did not dispatch its native MFC
command. A returned menu call is therefore not a success signal. Keep
this predicate small and evidence based so the supervisor can distinguish
a dispatch failure from a generic inactivity timeout without changing the
underlying automation route.
"""
if not (verify_invoked and invoke_returned) or target_pid is not None:
return None
return (
'FAIL',
'VERIFY_DISPATCH_FAILED: LMC Verify 菜单调用已返回,但未启动目标 ReusableCircuit PCB',
)
def _write_failure_windows(root, snapshots):
if not snapshots:
return
records = [dict(time=time.strftime('%Y-%m-%d %H:%M:%S'), **snapshot.to_record())
for snapshot in snapshots]
(root/'window_snapshots.jsonl').write_text(
''.join(json.dumps(record, ensure_ascii=False) + '\n' for record in records), encoding='utf-8')
def _write_process_tree(root, process, target_pid):
record = {
'time': time.strftime('%Y-%m-%d %H:%M:%S'),
'worker_pid': getattr(process, 'pid', None),
'companion_pids': list(getattr(process, 'companion_pids', ())),
'pcb_pid': target_pid,
}
temporary = root/'process_tree.json.tmp'
temporary.write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
temporary.replace(root/'process_tree.json')
def runtime_fingerprint(mentor_bin=''):
"""Return host/runtime facts needed to compare Win10 and Win11 runs."""
result = {
'platform': platform.platform(),
'system': platform.system(),
'release': platform.release(),
'version': platform.version(),
'machine': platform.machine(),
'python_version': platform.python_version(),
'python_bitness': struct.calcsize('P') * 8,
'mentor_bin': str(mentor_bin or ''),
'uia_backend': 'pywinauto.win32',
}
if os.name == 'nt':
try:
import winreg
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
r'SOFTWARE\Microsoft\Windows NT\CurrentVersion') as key:
for name, output_name in (
('ProductName', 'windows_product_name'),
('CurrentBuild', 'windows_current_build'),
('UBR', 'windows_ubr'),
):
try:
result[output_name] = winreg.QueryValueEx(key, name)[0]
except OSError:
pass
except (ImportError, OSError):
pass
result['windows_build_family'] = windows_build_family(
result.get('windows_current_build'))
from .mentor_paths import describe_installation, discover_sdd_home
result['mentor_installation'] = describe_installation(
discover_sdd_home(mentor_bin))
return result
def windows_build_family(build):
"""Classify Windows from the build number, not ProductName.
Windows 11 commonly keeps ``ProductName=Windows 10 Pro`` for
compatibility. The first public Windows 11 build is 22000, so the build
number is the stable discriminator for compatibility reports.
"""
try:
number = int(str(build or '').split('.', 1)[0])
except (TypeError, ValueError):
return 'unknown'
if number >= 22000:
return 'Windows 11'
if number >= 10240:
return 'Windows 10'
return 'unknown'
def native_lm_verify_enabled():
"""Read the explicit compatibility switch for the native LM route."""
return os.environ.get('CBB_NATIVE_LM_VERIFY', '').strip().casefold() in {
'1', 'true', 'yes', 'on',
}
def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline,
progress=None):
"""Reap Mentor processes after the worker can no longer run its ``finally``.
The outer supervisor owns the worker lifetime. A timeout or an unknown
dialog may therefore terminate the worker while its child LMC/PCB processes
remain alive. Delegate the same target-filtered cleanup used by the worker
and persist its events before the batch advances.
"""
from .mentor_adapter import cleanup_verify_processes
event_path = Path(root) / 'events.jsonl'
def emit(**event):
event = {
'time': time.strftime('%Y-%m-%d %H:%M:%S'),
'source': 'supervisor_cleanup',
**event,
}
try:
with event_path.open('a', encoding='utf-8') as stream:
stream.write(json.dumps(event, ensure_ascii=False) + '\n')
except OSError:
pass
if progress:
progress(event)
cleanup_verify_processes(
lm_pid,
target_pid,
None,
expected_pcb=pcb,
baseline_pids=pcb_baseline,
emit=emit,
)
def run_verify(request, *, progress=None, flag_reader=None, process_runner=None, port_check=None,
dialog_supervisor_factory=None):
timing = RunTimings()
result = _run_verify(request, timing=timing, progress=progress, flag_reader=flag_reader,
process_runner=process_runner, port_check=port_check,
dialog_supervisor_factory=dialog_supervisor_factory)
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'} and result.evidence_path:
job_path = result.evidence_path.with_name('request.json')
if job_path.is_file():
timing.begin('failure_diagnostics')
try:
from .verify_diagnostics import capture_failure_logs_with_timeout
capture_failure_logs_with_timeout(job_path)
except Exception:
# Never replace the underlying Mentor/bridge/timeout failure.
pass
finally:
timing.end('failure_diagnostics')
durations, unfinished = timing.snapshot()
result = replace(result, timings_seconds=durations, incomplete_timing_phases=unfinished,
error_category=(result.error_category or classify_failure_category(result.stderr)
if result.status not in {"PASS", "SKIPPED"} else ""),
error_stage=(result.error_stage or (unfinished[-1] if unfinished else 'execution')
if result.status not in {"PASS", "SKIPPED"} else ""))
if result.evidence_path:
result.evidence_path.write_text(json.dumps(
{'block_name': request.block_name, **asdict(result)},
ensure_ascii=False, default=str, indent=2), encoding='utf-8')
result.evidence_path.with_name('performance.json').write_text(json.dumps({
'block_name': request.block_name, 'status': result.status,
'unit': 'seconds', 'timings_seconds': durations,
'incomplete_timing_phases': unfinished,
'clock': 'monotonic; save helper subphases: VBScript Timer (midnight adjusted)',
'notes': 'phase totals overlap action/call subphases; skipped phases are absent',
}, ensure_ascii=False, indent=2), encoding='utf-8')
if progress:
progress({'stage': 'performance', 'block': request.block_name,
'timings_seconds': durations, 'incomplete_timing_phases': unfinished,
'detail': ' '.join(f'{key}={value:.3f}s' for key, value in durations.items())})
if request.logging_context:
request.logging_context.logger.info('operation=cbb_verify block=%s status=%s flag=%s evidence=%s error=%s timings_seconds=%s',
request.block_name, result.status, result.library_flag, result.evidence_path, result.stderr, durations)
return result
def _run_verify(request, *, timing, progress=None, flag_reader=None, process_runner=None, port_check=None,
dialog_supervisor_factory=None):
"""Refresh one CBB and record its evidence.
``flag_reader`` is a read-only probe returning an authoritative ``BridgeResult``.
After successful execution, only IsVerifiedReuseBlock READY/raw=1 confirms
PASS/GREEN; Cert or icon observations never substitute for it. ``port_check`` is injectable so tests do
not depend on the host's port reservations.
"""
root = Path(request.evidence_dir).resolve()/('verify-' + uuid4().hex[:12])
root.mkdir(parents=True, exist_ok=False)
fingerprint = runtime_fingerprint(request.mentor_bin)
(root/'runtime.json').write_text(
json.dumps(fingerprint, ensure_ascii=False, indent=2), encoding='utf-8')
if progress:
progress({'stage': 'runtime_fingerprint', 'block': request.block_name,
**fingerprint})
result_path = root/'result.json'
runner = process_runner or _run_process
def finish(result):
# Backups are transient protection for the active worker. Keep the
# small, actionable evidence files but reclaim the copied CBB tree so
# large libraries do not accumulate tens of megabytes per item.
try:
from .mentor_adapter import cleanup_evidence_backup
cleanup_evidence_backup(root)
except Exception:
# Cleanup must never hide or change the verification result.
pass
return replace(result, evidence_path=result_path)
timing.begin('preflight')
try:
project, pcb = preflight(request)
except Exception as error:
return finish(VerifyResult('BLOCKED', stderr=str(error)))
finally:
timing.end('preflight')
content_check_enabled = bool(str(request.libspec).strip() and str(request.dms_login_config).strip())
if content_check_enabled:
try:
executable = resolve_importer(request.mentor_bin)
except Exception as error:
return finish(VerifyResult('BLOCKED', stderr=str(error)))
command = build_content_check_command(request, executable)
if progress:
progress({'stage': 'content_check_start', 'block': request.block_name,
'detail': ' '.join(command)})
timing.begin('content_check')
try:
exit_code, stdout, stderr, timed_out = runner(command, request.timeout_seconds, Path(request.lmc_file).parent)
finally:
timing.end('content_check')
combined = '\n'.join(part for part in (stdout, stderr) if part)
report = contents_report_path(request.lmc_file, request.block_name)
try:
report.parent.mkdir(parents=True, exist_ok=True)
report.write_text(combined, encoding='utf-8')
except Exception as error:
stderr = f'{stderr}\n无法写入内容检查报告 {report}: {error}'
status = classify_output(exit_code, combined, timed_out=timed_out)
if status != 'PASS':
# A contents failure or an unusable DMS must block before touching the PCB.
return finish(VerifyResult(status if status in ('FAIL', 'TIMEOUT') else 'BLOCKED',
stderr=combined.strip() or f'内容检查结果未知(退出码 {exit_code})',
stdout=stdout, report_path=report, content_check_exit_code=exit_code))
if progress:
progress({'stage': 'content_check_done', 'block': request.block_name, 'status': 'PASS'})
# The design server needs a port in 10000-10100; a system reservation there
# blocks every item, so fail fast with the fix instead of timing out.
from .mentor_adapter import icdb_ports_bindable
check_ports = port_check or icdb_ports_bindable
ports_ok, ports_detail = check_ports()
if not ports_ok:
if progress:
progress({'stage': 'port_warning', 'block': request.block_name, 'detail': ports_detail})
if request.strict_port_check:
return finish(VerifyResult('BLOCKED', stderr=ports_detail))
job = {'lmc_file': str(absolute_preserving_drive(request.lmc_file)), 'block_name': request.block_name,
'project': str(project), 'pcb': str(pcb), 'root': str(root), 'timeout': request.timeout_seconds,
'mentor_bin': str(request.mentor_bin or ''),
'mapped_drive': str(request.mapped_drive or ''),
'mapped_remote_root': str(request.mapped_remote_root or ''),
'interactive_input': bool(request.interactive_input),
'native_lm_verify': bool(request.native_lm_verify),
'desktop': 'CbbVerify_' + uuid4().hex[:12],
'start_gate': str(root/'start-worker.signal')}
job_path = root/'request.json'
job_path.write_text(json.dumps(job, ensure_ascii=False), encoding='utf-8')
events = root/'events.jsonl'
offset = 0
target_pid = None
lm_pid = None
verify_invoked = False
invoke_returned = False
pcb_baseline = set()
last_observation = 0.0
last_post_verify_observation = {}
from .mentor_adapter import ActivityDeadline, pcb_startup_timeout_seconds
from .desktop_worker import DesktopWorker
from .dialog_supervisor import AgentDialogBackend, DialogSupervisor, Win32DialogBackend
from .dialog_models import DialogPhase
import win32event, win32con
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
lock_status = win32event.WaitForSingleObject(mutex, 0)
if lock_status not in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED):
mutex.Close()
return finish(VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行,请等待结束。', safe_to_continue=False))
try:
timing.begin('worker_setup')
with (root/'worker.log').open('w', encoding='utf-8') as log:
if request.interactive_input:
process = DesktopWorker(
worker_command(job_path), None, interactive_input=True)
else:
process = DesktopWorker(worker_command(job_path), job['desktop'])
deadline = ActivityDeadline(request.timeout_seconds)
last_activity_key = None
phase = DialogPhase.PCB_STARTING
dialog_agent = None
latest_snapshots = ()
if dialog_supervisor_factory is None:
if hasattr(process, 'start_companion'):
from .dialog_agent import DialogAgentClient
from .dialog_rules import default_rules_path, load_rules
dialog_agent = DialogAgentClient.start(process, root/'dialog-agent')
dialog_supervisor = DialogSupervisor(
AgentDialogBackend(dialog_agent),
rules=load_rules(default_rules_path()),
)
else:
dialog_supervisor = DialogSupervisor(Win32DialogBackend(
lambda: ({value for value in (target_pid, lm_pid) if value is not None}),
desktop=process.desktop,
))
else:
dialog_supervisor = dialog_supervisor_factory(
desktop=process.desktop,
pids=lambda: ({value for value in (target_pid, lm_pid) if value is not None}),
)
Path(job['start_gate']).touch()
while process.poll() is None:
if events.exists():
with events.open(encoding='utf-8') as stream:
stream.seek(offset)
while line := stream.readline():
try:
event = json.loads(line)
except json.JSONDecodeError:
break
timing.record(event)
if event.get('pcb_pid'): target_pid = event['pcb_pid']
if event.get('lm_pid'): lm_pid = event['lm_pid']
stage = event.get('stage')
if stage == 'verify_invoke': verify_invoked = True
if stage == 'verify_invoke_returned': invoke_returned = True
if stage == 'pcb_baseline': pcb_baseline = set(event.get('pids', ()))
phase = phase_for_event(event, phase)
activity_key = (stage, json.dumps(event.get('statuses'), sort_keys=True),
json.dumps(event.get('markers'), sort_keys=True),
event.get('action'), event.get('detail'))
# Repeated integration_status snapshots are normal
# polling, not progress. Only a changed state or
# a new stage/marker extends the inactivity window.
if activity_key != last_activity_key:
if stage in ('lm_started', 'lm_ready', 'verify_invoke',
'verify_invoke_returned', 'lm_session_ready',
'pcb_started', 'pcb_worker_started'):
deadline.timeout_seconds = pcb_startup_timeout_seconds(
request.timeout_seconds)
elif stage == 'identity_verified':
deadline.timeout_seconds = max(
0.1, float(request.timeout_seconds))
deadline.touch()
last_activity_key = activity_key
if progress: progress(event)
offset = stream.tell()
if verify_invoked and target_pid is None and time.monotonic() - last_observation >= .5:
from .post_verify_diagnostics import observe_post_verify
last_observation = time.monotonic()
try:
observation = observe_post_verify(process.desktop, pcb, pcb_baseline, lm_pid)
except Exception as error:
observation = {'error': str(error)}
last_post_verify_observation = observation
if dialog_agent is not None and target_pid is None:
# The Library Manager Verify route starts its own window
# before it launches Expedition PCB. Do not feed that
# large MFC main window to the PCB dialog probe; it can
# exhaust the UIA observation deadline before Verify has
# even produced a target process.
from .dialog_supervisor import DialogPollResult
dialog_result = DialogPollResult(activity=False)
elif dialog_agent is not None:
dialog_result = dialog_supervisor.poll(phase)
elif dialog_supervisor_factory is not None:
try:
dialog_result = dialog_supervisor.poll(phase)
except TypeError:
# Compatibility for injected legacy test supervisors only.
dialog_result = dialog_supervisor.poll()
else:
dialog_result = dialog_supervisor.poll()
# Normal progress stays in memory. Only actions/errors and the
# last failure snapshots are persisted, not every elapsed tick.
latest_snapshots = dialog_result.observed_snapshots
if dialog_result.snapshot is not None and (
dialog_result.action_sent or dialog_result.error_code):
snapshot_record = (dialog_result.snapshot.to_record()
if hasattr(dialog_result.snapshot, 'to_record')
else dialog_result.snapshot.as_log_record())
record = {
'time': time.strftime('%Y-%m-%d %H:%M:%S'),
**snapshot_record,
'action': dialog_result.action,
'rule_id': dialog_result.rule_id,
'channel': dialog_result.channel,
'accepted_control': list(dialog_result.accepted_controls),
'error_code': dialog_result.error_code,
'detail': dialog_result.detail,
}
with (root/'dialogs.jsonl').open('a', encoding='utf-8') as stream:
stream.write(json.dumps(record, ensure_ascii=False) + '\n')
if dialog_result.activity:
deadline.touch()
if dialog_result.error_code:
_write_failure_windows(root, latest_snapshots)
_write_process_tree(root, process, target_pid)
_stop_worker(process)
return finish(VerifyResult(
'FAIL',
stderr=f'{dialog_result.error_code}: {dialog_result.detail}',
error_stage=phase.value,
safe_to_continue=True,
))
if deadline.expired():
_write_failure_windows(root, latest_snapshots)
# Kills the worker's whole job: worker, PCB and cscript helper.
_write_process_tree(root, process, target_pid)
if last_post_verify_observation:
(root/'post_verify_observations.jsonl').write_text(json.dumps({
'time': time.strftime('%Y-%m-%d %H:%M:%S'),
'invoke_returned': invoke_returned,
**last_post_verify_observation,
}, ensure_ascii=False) + '\n', encoding='utf-8')
dispatch_failure = classify_verify_dispatch(
verify_invoked=verify_invoked,
invoke_returned=invoke_returned,
target_pid=target_pid,
observation=last_post_verify_observation,
)
_stop_worker(process)
if dispatch_failure is not None:
status, detail = dispatch_failure
if progress:
progress({
'stage': 'verify_dispatch_failed',
'block': request.block_name,
'detail': detail,
'observation': last_post_verify_observation,
})
return finish(VerifyResult(status, stderr=detail, safe_to_continue=True))
return finish(VerifyResult('TIMEOUT', stderr='操作超时;已记录现场,跳过当前 CBB。', error_stage=phase.value, safe_to_continue=True))
time.sleep(.2)
worker_result = root/'outcome.json'
if not worker_result.exists():
return finish(VerifyResult('FAIL', stderr=f'执行器异常退出 ({process.returncode}),见 worker.log', safe_to_continue=False))
outcome = json.loads(worker_result.read_text(encoding='utf-8'))
if outcome.get('status') == 'PASS' and process.returncode != 0:
return finish(VerifyResult('FAIL', stderr='执行器异常退出,不能确认成功', safe_to_continue=False))
result = VerifyResult(**outcome)
except Exception as error:
if 'process' in locals() and process.poll() is None:
_stop_worker(process)
return finish(VerifyResult('FAIL', stderr=str(error), safe_to_continue=False))
finally:
if 'dialog_agent' in locals() and dialog_agent is not None:
dialog_agent.close()
if 'process' in locals(): process.close()
if 'process' in locals():
try:
_cleanup_session_processes(
root,
lm_pid=lm_pid,
target_pid=target_pid,
pcb=pcb,
pcb_baseline=pcb_baseline,
progress=progress,
)
except Exception:
# Cleanup is best effort; the original Verify result remains
# authoritative and the evidence directory records everything
# that was successfully reaped.
pass
# Drain the timing tail even when the worker exited before a poll.
# This is optional telemetry: an unreadable log must not mask failure
# or prevent releasing the serial-operation mutex.
try:
if events.is_file():
with events.open(encoding='utf-8') as stream:
stream.seek(offset)
for line in stream:
try:
timing.record(json.loads(line))
except (json.JSONDecodeError, ValueError):
continue
except OSError:
pass
finally:
win32event.ReleaseMutex(mutex)
mutex.Close()
if result.status == 'PASS':
timing.begin('library_flag')
bridge_records = []
def record_attempt(record):
bridge_records.append(record)
if progress:
progress({'stage': 'library_flag_probe', 'block': request.block_name, **record})
try:
probe = read_library_flag_with_retry(
flag_reader or read_library_flag_if_available, Path(request.lmc_file),
request.block_name, on_attempt=record_attempt)
result = apply_post_verify_status(result, probe)
result = replace(result, bridge_attempts=tuple(bridge_records))
(root/'bridge-status.json').write_text(json.dumps(bridge_records, ensure_ascii=False, indent=2), encoding='utf-8')
if progress:
progress({'stage': 'library_flag', 'block': request.block_name,
'library_flag': result.library_flag, 'detail': result.library_flag_detail})
finally:
timing.end('library_flag')
return finish(result)
def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None):
"""Run CBBs serially; one item's failure never aborts the queue."""
if max_workers != 1:
raise ValueError('Only serial Verify is supported for the shared Library Manager session')
if verifier is None:
verifier = lambda request: run_verify(request, flag_reader=read_library_flag_if_available) # noqa: E731
results = []
queue_stop = False
for request in requests:
if queue_stop or (stop is not None and stop.is_set()):
result = VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
else:
try:
result = verifier(request)
except Exception as error:
# An unexpected worker exception is a failed item, not a batch abort.
result = VerifyResult('FAIL', stderr=str(error), safe_to_continue=False)
results.append(result)
# Failure status and safe_to_continue describe this item, not the batch;
# the queue is skipped only after an explicit stop signal.
queue_stop = queue_stop or result.status == 'QUEUE_STOP'
if result.status == 'QUEUE_STOP' and stop is not None:
stop.set()
if progress: progress(request.block_name, result)
return results
def failure_report_path(batch_report):
batch_report = Path(batch_report)
return batch_report.with_name(batch_report.name.replace('batch-', 'failures-', 1))
def _report_field(value):
# One CBB per row; full native multi-line text remains in evidence files.
return str(value).replace('\r', r'\r').replace('\n', r'\n').replace('\t', r'\t')
def write_failure_report(requests, results, root, *, path=None):
requests, results = tuple(requests), tuple(results)
if len(requests) != len(results):
raise ValueError('requests/results 长度不一致,不能生成遗漏条目的报告')
root = Path(root); root.mkdir(parents=True, exist_ok=True)
path = Path(path) if path else root/('failures-' + time.strftime('%Y%m%d-%H%M%S') + '-' + uuid4().hex[:6] + '.log')
failed = [(req, result) for req, result in zip(requests, results)
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'}]
passed = sum(result.status == 'PASS' for result in results)
skipped = len(results)-passed-len(failed)
lines = ['CBB Verify 失败清单', f'总数: {len(results)} 成功: {passed} 失败: {len(failed)} 未执行: {skipped}',
'CBB\t状态\t错误分类\t失败阶段\t桥状态\t原始错误\t证据\t实际耗时(秒)']
for req, result in failed:
timings = ' '.join(f'{key}={value:.3f}s' +
('(unfinished)' if key in result.incomplete_timing_phases else '')
for key, value in result.timings_seconds.items())
lines.append(f'{req.block_name}\t{result.status}\t{result.error_category or classify_failure_category(result.stderr)}\t'
f'{result.error_stage or "unknown"}\t{result.library_flag}\t{_report_field(result.stderr or result.stdout.strip()[:200])}\t{result.evidence_path or ""}\t{timings}')
if not failed:
lines.append('本批次没有失败项。')
path.write_text('\n'.join(lines) + '\n', encoding='utf-8-sig')
return path
def write_batch_report(requests, results, root):
requests, results = tuple(requests), tuple(results)
if len(requests) != len(results):
raise ValueError('requests/results 长度不一致,不能生成遗漏条目的报告')
root = Path(root); root.mkdir(parents=True, exist_ok=True)
path = root/('batch-' + time.strftime('%Y%m%d-%H%M%S') + '-' + uuid4().hex[:6] + '.log')
lines = ['CBB Verify 批量结果',
'流程: LMC 原生 Verify / ReusableCircuit PCB -> Project Integration -> Save/Close -> IsVerifiedReuseBlock READY(金标准)']
for req, result in zip(requests, results):
detail = _report_field(result.stderr or result.stdout.strip()[:200])
seconds = ' '.join(f'{key}={value:.3f}s' +
('(unfinished)' if key in result.incomplete_timing_phases else '')
for key, value in result.timings_seconds.items())
lines.append(f'{req.block_name}\t{result.status}\t{result.library_flag}\t{detail}\t{result.evidence_path or ""}\t{seconds}')
path.write_text('\n'.join(lines) + '\n', encoding='utf-8-sig')
write_failure_report(requests, results, root, path=failure_report_path(path))
return path
+35
View File
@@ -0,0 +1,35 @@
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$root = Split-Path $PSScriptRoot -Parent
Import-Module (Join-Path $root 'CBBRefresh.Core.psm1') -Force
function Assert-Equal {
param($Expected, $Actual, [string]$Message)
if ($Expected -ne $Actual) { throw "$Message (expected '$Expected', got '$Actual')" }
}
$before = Read-CbbRefreshStatus -Path (Join-Path $root 'examples\library-verify-before.json')
$next = Get-CbbRefreshNextAction -Status $before
Assert-Equal 'verify_result' $next.State 'yellow Verify state is selected first'
Assert-Equal 'run_cbb_verify' $next.Action 'Verify action is mapped'
if (Test-CbbRefreshAllGreen -Status $before) { throw 'before status must not be all green' }
$green = Read-CbbRefreshStatus -Path (Join-Path $root 'examples\library-verify-green.json')
if (-not (Test-CbbRefreshAllGreen -Status $green)) { throw 'green fixture must be all green' }
$verification = New-CbbRefreshVerification -Status $green -Observations @($green.observations)
Assert-Equal 'PASS' $verification.result 'all green status passes'
Assert-Equal $null $verification.nextAction 'all green status has no next action'
$importer = Get-CbbReuseBlockImporterPath -MentorBin $env:SDD_LM_BIN
if ([IO.Path]::GetFileName($importer) -ne 'ReuseBlockImporter.exe') {
throw 'ReuseBlockImporter path did not resolve to the expected executable.'
}
$threw = $false
try {
Invoke-CbbReuseBlockContentCheck -LmcFile (Join-Path $root 'fixtures\cloned-library\mentor_lib.lmc') `
-BlockName '1GPHY_RTL8211F_A' -LibSpec 'EE7.9' -DmsLoginConfig '' -MentorBin $env:SDD_LM_BIN
}
catch { $threw = $true }
if (-not $threw) { throw 'Empty DMS login configuration must be rejected before launching the checker.' }
Write-Output 'CBB refresh core tests passed.'
+83
View File
@@ -0,0 +1,83 @@
from pathlib import Path
def test_smoke_arguments_exit_zero_and_write_lifecycle_log(tmp_path: Path):
import subprocess, sys
result = subprocess.run([sys.executable, '-m', 'cbb_refresh_verify', '--smoke-test', '--data-root', str(tmp_path)], timeout=30)
assert result.returncode == 0
text = (tmp_path / "logs" / "application.log").read_text(encoding="utf-8")
assert "application_start" in text
assert "application_clean_shutdown" in text
assert "gui_smoke_window_created" in text
def test_module_entrypoint_propagates_main_exit_code():
import subprocess, sys
code = (
"import cbb_refresh_verify.application as a; a.main=lambda: 7; "
"import runpy; runpy.run_module('cbb_refresh_verify.__main__', run_name='__main__')"
)
result = subprocess.run([sys.executable, '-c', code], capture_output=True, text=True)
assert result.returncode == 7
def test_batch_cli_acquires_unc_lease_before_directory_scan(tmp_path, monkeypatch):
import cbb_refresh_verify.application as application
import cbb_refresh_verify.library_reader as library_reader
import cbb_refresh_verify.network_path as network_path
events = []
class Lease:
display_path = r'\\server\share\library'
mentor_path = tmp_path
drive = 'Z:'
remote_root = r'\\server\share'
created = True
def __enter__(self):
events.append('enter')
return self
def __exit__(self, *_args):
events.append('exit')
def close(self):
events.append('close')
class Library:
error = 'stop after path setup'
records = ()
monkeypatch.setattr(application, 'configure', lambda *_args: type('C', (), {
'root': tmp_path,
'logger': type('L', (), {'info': lambda *a, **k: None,
'exception': lambda *a, **k: None,
'handlers': ()})(),
})())
monkeypatch.setattr(network_path, 'LibraryPathLease', type('LP', (), {
'acquire': staticmethod(lambda path: (events.append(('acquire', path)) or Lease()))
}))
monkeypatch.setattr(network_path, 'select_library_file', lambda path: (
events.append(('select', path)) or path
))
# The command exits after the fake reader reports an empty/error library;
# ordering is the contract under test.
monkeypatch.setattr(library_reader, 'read_library_fast', lambda path, **kwargs: Library())
result = application.main(['--batch-lmc', r'\\server\share\library'])
assert result == 1
assert events[:3] == [('acquire', Path(r'\\server\share\library')), 'enter',
('select', tmp_path)]
def test_native_log_helper_mode_does_not_load_ui_or_mgcpcb(tmp_path, monkeypatch):
import json
import cbb_refresh_verify.application as application
request = tmp_path/'request.json'
pcb = tmp_path/'Work/PCB/test.pcb'
pcb.parent.mkdir(parents=True)
request.write_text(json.dumps({'root': str(tmp_path), 'pcb': str(pcb)}), encoding='utf-8')
monkeypatch.setattr(application, 'configure', lambda *_: (_ for _ in ()).throw(
AssertionError('log capture must not create a GUI/logger session')))
result = application.main(['--collect-failure-logs', str(request)])
assert result == 0
assert (tmp_path/'diagnostics/native-logs.json').is_file()
+61
View File
@@ -0,0 +1,61 @@
import pytest
from cbb_refresh_verify.pcb_bridge import AutomationLicenseError, validate_document
class FakeDocument:
def __init__(self):
self.validate_calls = []
def Validate(self, value):
self.validate_calls.append(value)
return 1234 if value == 0 else True
class FakeLicenseApp:
def __init__(self):
self.keys = []
def GetToken(self, key):
self.keys.append(key)
return 5678
def test_validate_uses_official_automation_token_without_logging_token():
document = FakeDocument()
license_app = FakeLicenseApp()
events = []
validate_document(document, lambda: license_app, emit=lambda **event: events.append(event))
assert document.validate_calls == [0, 5678]
assert license_app.keys == [1234]
assert [event['stage'] for event in events] == [
'license_key_requested', 'license_token_received', 'document_validated'
]
assert '5678' not in repr(events)
def test_unregistered_licensing_server_allows_ui_fallback():
class ComFailure(Exception):
hresult = -2147221164 # REGDB_E_CLASSNOTREG
with pytest.raises(AutomationLicenseError) as raised:
validate_document(FakeDocument(), lambda: (_ for _ in ()).throw(ComFailure('missing')))
assert raised.value.fallback_allowed is True
assert raised.value.error_code == 'AUTOMATION_LICENSE_UNAVAILABLE'
def test_rejected_license_token_is_fatal_not_ui_fallback():
class RejectingDocument(FakeDocument):
def Validate(self, value):
if value:
raise RuntimeError('token rejected')
return super().Validate(value)
with pytest.raises(AutomationLicenseError) as raised:
validate_document(RejectingDocument(), lambda: FakeLicenseApp())
assert raised.value.fallback_allowed is False
assert raised.value.error_code == 'AUTOMATION_LICENSE_REJECTED'
+174
View File
@@ -0,0 +1,174 @@
from pathlib import Path
from cbb_refresh_verify.batch_status import (BatchCheckpoint, BatchStatusSession,
fingerprint_library)
from cbb_refresh_verify.status_bridge import BridgeResponseError, BridgeResult
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_fingerprint_preserves_mapped_drive_without_resolve(tmp_path, monkeypatch):
lmc = tmp_path / 'mentor_lib.lmc'
lmc.write_bytes(b'library')
monkeypatch.setattr(
Path,
'resolve',
lambda self: (_ for _ in ()).throw(AssertionError(f'resolve called: {self}')),
)
assert fingerprint_library(lmc).sha256
def test_fingerprint_changes_when_top_level_block_set_changes(tmp_path):
lmc = tmp_path / "mentor_lib.lmc"
lmc.write_bytes(b"library")
root = tmp_path / "ReusableBlocksLP"
(root / "CBB_A").mkdir(parents=True)
first = fingerprint_library(lmc)
(root / "CBB_B").mkdir()
second = fingerprint_library(lmc)
assert first.sha256 != second.sha256
def test_fingerprint_does_not_walk_cbb_descendants(tmp_path, monkeypatch):
import cbb_refresh_verify.batch_status as batch_status
lmc = tmp_path / "mentor_lib.lmc"
lmc.write_bytes(b"library")
root = tmp_path / "ReusableBlocksLP"
(root / "CBB_A" / "Work").mkdir(parents=True)
real_scandir = batch_status.os.scandir
def guarded_scandir(path):
if Path(path) != root:
raise AssertionError(f"descendant scan: {path}")
return real_scandir(path)
monkeypatch.setattr(batch_status.os, "scandir", guarded_scandir)
assert fingerprint_library(lmc).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"}
class FakeBridge:
def __init__(self, timeout_name=None):
self.requests = []
self.timeout_name = timeout_name
def query(self, lmc_file, block_name, *, block_type="RULP", timeout_seconds=10):
self.requests.append(block_name)
if block_name == self.timeout_name:
raise BridgeResponseError("状态桥响应超时")
return BridgeResult("READY" if block_name == "A" else "PENDING", "fake")
def test_scan_reuses_checkpoint_and_queries_only_missing(tmp_path):
lmc = tmp_path / "mentor_lib.lmc"
lmc.write_bytes(b"library")
checkpoint = tmp_path / "scan.jsonl"
fingerprint = fingerprint_library(lmc).sha256
checkpoint.write_text(
'{"block_name":"A","status":"READY","fingerprint":"' + fingerprint + '"}\n',
encoding="utf-8",
)
bridge = FakeBridge()
records = BatchStatusSession(bridge).scan(["A", "B"], lmc, checkpoint)
assert bridge.requests == ["B"]
assert {record.block_name for record in records} == {"A", "B"}
def test_timeout_isolated_and_later_item_continues(tmp_path):
lmc = tmp_path / "mentor_lib.lmc"
lmc.write_bytes(b"library")
bridge = FakeBridge(timeout_name="A")
records = BatchStatusSession(bridge, timeout_seconds=0.1).scan(
["A", "B"], lmc, tmp_path / "scan.jsonl")
assert records[0].status == "TIMEOUT"
assert records[1].status == "PENDING"
def test_protocol_path_mismatch_stops_repeating_same_global_failure(tmp_path):
class BrokenProtocolBridge:
def __init__(self):
self.requests = []
def query(self, lmc_file, block_name, **kwargs):
self.requests.append(block_name)
raise BridgeResponseError('状态桥中心库路径不匹配')
lmc = tmp_path / 'mentor_lib.lmc'
lmc.write_bytes(b'library')
bridge = BrokenProtocolBridge()
records = BatchStatusSession(bridge).scan(
['A', 'B', 'C'], lmc, tmp_path / 'scan.jsonl'
)
assert bridge.requests == ['A']
assert [record.status for record in records] == ['MALFORMED'] * 3
def test_authoritative_status_map_marks_missing_bridge_unavailable(tmp_path, monkeypatch):
import cbb_refresh_verify.batch_status as batch_status
from cbb_refresh_verify.status_bridge import BridgeUnavailable
class MissingBridge:
def __init__(self, *args, **kwargs):
pass
def start(self):
raise BridgeUnavailable(tmp_path / "missing.exe")
def restart(self):
raise BridgeUnavailable(tmp_path / "missing.exe")
def close(self):
pass
monkeypatch.setattr(batch_status, "StatusBridgeServer", MissingBridge)
lmc = tmp_path / "mentor_lib.lmc"
lmc.write_bytes(b"library")
result = batch_status.authoritative_status_map(
["A", "B"], lmc, tmp_path / "scan.jsonl")
assert result == {"A": "UNAVAILABLE", "B": "UNAVAILABLE"}
def test_authoritative_status_map_never_reuses_previous_scan_status(tmp_path, monkeypatch):
import cbb_refresh_verify.batch_status as batch_status
calls = []
class Bridge:
def __init__(self, *args, **kwargs):
pass
def start(self):
pass
def restart(self):
pass
def close(self):
pass
def query(self, lmc_file, block_name, **kwargs):
calls.append(block_name)
status = 'PENDING' if len(calls) == 1 else 'READY'
return BridgeResult(status, 'fake')
monkeypatch.setattr(batch_status, 'StatusBridgeServer', Bridge)
lmc = tmp_path / 'mentor_lib.lmc'
lmc.write_bytes(b'library')
checkpoint = tmp_path / 'scan.jsonl'
first = batch_status.authoritative_status_map(['A'], lmc, checkpoint)
second = batch_status.authoritative_status_map(['A'], lmc, checkpoint)
assert first == {'A': 'PENDING'}
assert second == {'A': 'READY'}
assert calls == ['A', 'A']
+86
View File
@@ -0,0 +1,86 @@
import json
import sys
import textwrap
from cbb_refresh_verify.batch_status import BatchStatusSession, fingerprint_library
from cbb_refresh_verify.status_bridge import StatusBridgeServer
def make_bridge_script(tmp_path, body):
script = tmp_path / "fault_bridge.py"
script.write_text(textwrap.dedent(body), encoding="utf-8")
return script
def test_malformed_response_does_not_stop_later_item(tmp_path):
script = make_bridge_script(tmp_path, '''
import json, sys
for line in sys.stdin:
item = json.loads(line)
if item["block_name"] == "BAD":
print("not-json", flush=True)
else:
print(json.dumps({"ok": True, "request_id": item["request_id"],
"block_name": item["block_name"], "lmc_file": item["lmc_file"],
"status": "PENDING", "source": "fake"}), flush=True)
''')
lmc = tmp_path / "x.lmc"; lmc.write_bytes(b"x")
bridge = StatusBridgeServer(script)
records = BatchStatusSession(bridge).scan(["BAD", "GOOD"], lmc, tmp_path / "scan.jsonl")
assert records[0].status == "ERROR"
assert records[1].status == "PENDING"
def test_bridge_exit_does_not_stop_later_item(tmp_path):
script = make_bridge_script(tmp_path, '''
import json, sys
for line in sys.stdin:
item = json.loads(line)
if item["block_name"] == "EXIT":
sys.exit(7)
print(json.dumps({"ok": True, "request_id": item["request_id"],
"block_name": item["block_name"], "lmc_file": item["lmc_file"],
"status": "READY", "source": "fake"}), flush=True)
''')
lmc = tmp_path / "x.lmc"; lmc.write_bytes(b"x")
records = BatchStatusSession(StatusBridgeServer(script)).scan(
["EXIT", "GOOD"], lmc, tmp_path / "scan.jsonl")
assert records[0].status == "ERROR"
assert records[1].status == "READY"
def test_timeout_on_item_seventeen_continues(tmp_path):
script = make_bridge_script(tmp_path, '''
import json, sys, time
for line in sys.stdin:
item = json.loads(line)
if item["block_name"] == "N17":
time.sleep(0.5)
print(json.dumps({"ok": True, "request_id": item["request_id"],
"block_name": item["block_name"], "lmc_file": item["lmc_file"],
"status": "PENDING", "source": "fake"}), flush=True)
''')
lmc = tmp_path / "x.lmc"; lmc.write_bytes(b"x")
names = [f"N{i}" for i in range(1, 18)] + ["N18"]
records = BatchStatusSession(StatusBridgeServer(script), timeout_seconds=0.1).scan(
names, lmc, tmp_path / "scan.jsonl")
assert records[16].status == "TIMEOUT"
assert records[17].status == "PENDING"
def test_fingerprint_change_does_not_reuse_checkpoint(tmp_path):
lmc = tmp_path / "x.lmc"; lmc.write_bytes(b"one")
checkpoint = tmp_path / "scan.jsonl"
first = fingerprint_library(lmc).sha256
checkpoint.write_text(json.dumps({"block_name": "A", "status": "READY",
"fingerprint": first}) + "\n", encoding="utf-8")
lmc.write_bytes(b"two")
class Bridge:
def __init__(self): self.requests = []
def query(self, lmc_file, block_name, **kwargs):
self.requests.append(block_name)
from cbb_refresh_verify.status_bridge import BridgeResult
return BridgeResult("PENDING", "fake")
bridge = Bridge()
BatchStatusSession(bridge).scan(["A"], lmc, checkpoint)
assert bridge.requests == ["A"]
+447
View File
@@ -0,0 +1,447 @@
import threading
from cbb_refresh_verify import application
from cbb_refresh_verify.dialog_agent import (
ActionResult,
DialogActionExecutor,
DialogAgentClient,
DialogAgentServer,
)
from cbb_refresh_verify.dialog_models import (
ControlSnapshot,
DialogPhase,
WindowSnapshot,
stable_fingerprint,
compatible_window_identity,
)
def snapshot(title="Prompt"):
return WindowSnapshot(
hwnd=10,
pid=20,
process_name="ExpeditionPCB.exe",
process_role="pcb",
window_class="GXWND",
title=title,
phase=DialogPhase.PCB_STARTING,
controls=(ControlSnapshot(11, 1, "Button", "OK", control_type="Button"),),
)
class FakeProbe:
def __init__(self, value):
self.value = value
def capture(self, phase):
return (self.value,) if self.value is not None else ()
def capture_one(self, hwnd, phase):
return self.value if self.value is not None and self.value.hwnd == hwnd else None
class FakeExecutor:
def __init__(self):
self.calls = []
def perform(self, snapshot_value, action):
self.calls.append((snapshot_value, action))
return ActionResult(channel="uia_invoke", accepted_controls=(1,))
def running_protocol(tmp_path, probe, executor=None):
client = DialogAgentClient.prepare(tmp_path, desktop_name="test", timeout_seconds=2)
server = DialogAgentServer.from_config(client.paths.config, probe=probe, executor=executor)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
return client, server, thread
def test_agent_correlates_observe_response_by_request_id(tmp_path):
client, server, thread = running_protocol(tmp_path, FakeProbe(snapshot()))
try:
reply = client.observe(DialogPhase.PCB_STARTING)
finally:
client.close()
thread.join(timeout=2)
assert reply[0].window_class == "GXWND"
assert server.requests[0]["request_id"] == server.responses[0]["request_id"]
assert server.responses[0]["sequence"] == 1
def test_agent_rejects_stale_action_fingerprint(tmp_path):
executor = FakeExecutor()
client, _server, thread = running_protocol(tmp_path, FakeProbe(snapshot("Changed")), executor)
try:
result = client.perform(
hwnd=10,
fingerprint=stable_fingerprint(snapshot("Old")),
action={"channels": ["uia_invoke"], "action": "confirm"},
phase=DialogPhase.PCB_STARTING,
)
finally:
client.close()
thread.join(timeout=2)
assert result.error_code == "STALE_DIALOG"
assert executor.calls == []
def test_agent_perform_uses_observed_snapshot_when_refresh_probe_blocks(tmp_path):
class BlockingRefreshProbe(FakeProbe):
def capture_one(self, hwnd, phase):
raise RuntimeError("refresh probe blocked by native license dialog")
executor = FakeExecutor()
value = snapshot()
client, server, thread = running_protocol(
tmp_path, BlockingRefreshProbe(value), executor
)
try:
observed = client.observe(DialogPhase.PCB_STARTING)
result = client.perform(
hwnd=value.hwnd,
fingerprint=stable_fingerprint(observed[0]),
action={"channels": ["uia_invoke"], "action": "confirm"},
phase=DialogPhase.PCB_STARTING,
)
finally:
client.close()
thread.join(timeout=2)
assert result.accepted_controls == (1,)
assert executor.calls == [(value, {"channels": ["uia_invoke"], "action": "confirm"})]
def test_window_identity_allows_control_tree_changes_during_initialization():
original = snapshot('')
changed = WindowSnapshot(
hwnd=original.hwnd,
pid=original.pid,
process_name=original.process_name,
process_role=original.process_role,
window_class=original.window_class,
title=original.title,
phase=original.phase,
controls=original.controls + (
ControlSnapshot(12, 2, 'Button', 'Cancel', control_type='Button'),
),
)
assert compatible_window_identity(original, changed)
def test_hidden_agent_route_runs_before_qt(monkeypatch, tmp_path):
called = []
monkeypatch.setattr(
"cbb_refresh_verify.dialog_agent.dialog_agent_main",
lambda path: called.append(path) or 17,
)
code = application.main(["--dialog-agent", str(tmp_path / "agent.json")])
assert code == 17
assert called == [tmp_path / "agent.json"]
def test_desktop_worker_companion_uses_same_desktop_and_job(monkeypatch):
import cbb_refresh_verify.desktop_worker as module
starts = []
assignments = []
class Startup:
lpDesktop = ""
class Handle:
def Close(self):
pass
monkeypatch.setattr(module.win32process, "STARTUPINFO", Startup)
monkeypatch.setattr(
module.win32process,
"CreateProcess",
lambda *args: starts.append(args) or (Handle(), Handle(), 321, 1),
)
monkeypatch.setattr(
module.win32job,
"AssignProcessToJobObject",
lambda job, handle: assignments.append((job, handle)),
)
worker = module.DesktopWorker.__new__(module.DesktopWorker)
worker.name = "PrivateDesk"
worker.job = object()
worker.job_bound = True
worker.companions = []
pid = worker.start_companion(["python", "--dialog-agent", "config.json"])
assert pid == 321
assert starts[0][-1].lpDesktop == "winsta0\\PrivateDesk"
assert assignments and len(worker.companions) == 1
def test_license_action_selects_unique_uia_license_before_ok():
selected = []
class Wrapper:
def select(self): selected.append('license')
controls = (
ControlSnapshot(11, 1522, 'GXWND', 'Product license', control_type='ListItem',
patterns=('SelectionItem',)),
ControlSnapshot(12, 1, 'Button', 'OK', control_type='Button', patterns=('Invoke',)),
)
value = snapshot()
value = WindowSnapshot(**{**value.__dict__, 'controls': controls})
executor = DialogActionExecutor(uia_wrapper=lambda _handle: Wrapper())
result = executor.perform(value, {
'action': 'accept_license',
'channels': ['uia_select', 'uia_invoke', 'win32_button_click'],
})
assert result.channel == 'uia_select'
assert result.accepted_controls == (1522,)
assert selected == ['license']
def test_license_action_invokes_ok_only_after_selection():
invoked = []
class Wrapper:
def invoke(self): invoked.append('ok')
controls = (
ControlSnapshot(11, 1522, 'GXWND', 'Product license', control_type='ListItem',
selected=True, patterns=('SelectionItem',)),
ControlSnapshot(12, 1, 'Button', 'OK', control_type='Button', patterns=('Invoke',)),
)
value = snapshot()
value = WindowSnapshot(**{**value.__dict__, 'controls': controls})
executor = DialogActionExecutor(uia_wrapper=lambda _handle: Wrapper())
result = executor.perform(value, {
'action': 'accept_license',
'channels': ['uia_select', 'uia_invoke', 'win32_button_click'],
})
assert result.channel == 'uia_invoke'
assert result.accepted_controls == (1,)
assert invoked == ['ok']
def test_license_selector_can_use_targeted_private_window_message():
messages = []
class Gui:
def PostMessage(self, hwnd, message, wparam, lparam):
messages.append((hwnd, message, wparam, lparam))
value = snapshot('')
controls = (
ControlSnapshot(11, 5225, 'Button', 'Select the desired product license',
control_type='Button'),
ControlSnapshot(12, 1, 'Button', 'OK', control_type='Button'),
)
value = WindowSnapshot(**{**value.__dict__, 'controls': controls})
executor = DialogActionExecutor(win32gui=Gui(), uia_wrapper=lambda _handle: (_ for _ in ()).throw(RuntimeError('uia unavailable')))
result = executor.perform(value, {
'action': 'accept_license',
'channels': ['win32_mouse_click'],
})
assert result.channel == 'win32_mouse_click'
assert result.accepted_controls == (1,)
assert [item[0] for item in messages] == [12, 12]
def test_license_selector_sends_center_click_and_parent_command_for_custom_button():
posted = []
sent = []
class Gui:
def GetWindowRect(self, hwnd):
assert hwnd == 12
return (100, 200, 180, 240)
def PostMessage(self, hwnd, message, wparam, lparam):
posted.append((hwnd, message, wparam, lparam))
def SendMessage(self, hwnd, message, wparam, lparam):
sent.append((hwnd, message, wparam, lparam))
value = snapshot('')
controls = (
ControlSnapshot(11, 5225, 'Button', 'Select the desired product license',
control_type='Button'),
ControlSnapshot(12, 1, 'Button', 'OK', control_type='Button'),
)
value = WindowSnapshot(**{**value.__dict__, 'hwnd': 99, 'controls': controls})
executor = DialogActionExecutor(win32gui=Gui(), uia_wrapper=lambda _handle: (_ for _ in ()).throw(RuntimeError('uia unavailable')))
result = executor.perform(value, {
'action': 'accept_license',
'channels': ['win32_mouse_click'],
})
assert result.channel == 'win32_mouse_click'
assert result.accepted_controls == (1,)
assert posted == []
assert sent == [(12, 0x0201, 1, (20 << 16) | 40),
(12, 0x0202, 0, (20 << 16) | 40),
(99, 0x0111, 1, 12)]
def test_license_action_targets_ok_when_license_pane_has_no_selectable_item():
controls = (
ControlSnapshot(11, 5225, 'Button', 'Select the desired product license',
control_type='Group'),
ControlSnapshot(12, 1522, 'GXWND', 'Select the desired product license',
control_type='Pane'),
ControlSnapshot(13, 1, 'Button', 'OK', control_type='Button'),
)
value = snapshot('')
value = WindowSnapshot(**{**value.__dict__, 'controls': controls})
executor = DialogActionExecutor(
win32gui=type('Gui', (), {'PostMessage': lambda *_args: None})(),
uia_wrapper=lambda _handle: (_ for _ in ()).throw(RuntimeError('uia unavailable')),
)
result = executor.perform(value, {
'action': 'accept_license',
'channels': ['win32_mouse_click'],
})
assert result.accepted_controls == (1,)
def test_license_ok_button_prefers_nonblocking_win32_button_click():
class Gui:
def __init__(self):
self.messages = []
def PostMessage(self, hwnd, message, wparam, lparam):
self.messages.append((hwnd, message, wparam, lparam))
value = snapshot('')
controls = (
ControlSnapshot(11, 5225, 'Button', 'Select the desired product license',
control_type='Button'),
ControlSnapshot(12, 1, 'Button', 'OK', control_type='Button'),
)
value = WindowSnapshot(**{**value.__dict__, 'controls': controls})
gui = Gui()
executor = DialogActionExecutor(
win32gui=gui,
uia_wrapper=lambda _handle: (_ for _ in ()).throw(RuntimeError('uia unavailable')),
)
result = executor.perform(value, {
'action': 'accept_license',
'channels': ['interface', 'uia_select', 'uia_invoke',
'win32_button_click', 'win32_mouse_click'],
})
assert result.channel == 'win32_button_click'
assert result.accepted_controls == (1,)
assert gui.messages and gui.messages[0][0] == 12
def test_database_restoration_selects_last_user_saved_before_ok():
selected = []
posted = []
class Wrapper:
def select(self):
selected.append('last-saved')
class Gui:
def PostMessage(self, hwnd, message, wparam, lparam):
posted.append((hwnd, message, wparam, lparam))
controls = (
ControlSnapshot(11, 6213, 'Button',
'Load the last user saved database dated 2026/9/24 22:52.',
control_type='RadioButton', patterns=('SelectionItem',)),
ControlSnapshot(12, 6206, 'Button',
'Load the autosave database dated 2026/9/24 22:52.',
control_type='RadioButton', selected=True,
patterns=('SelectionItem',)),
ControlSnapshot(13, 1, 'Button', 'OK', control_type='Button',
patterns=('Invoke',)),
)
value = snapshot('Database Restoration')
value = WindowSnapshot(**{**value.__dict__, 'controls': controls})
executor = DialogActionExecutor(win32gui=Gui(), uia_wrapper=lambda _handle: Wrapper())
result = executor.perform(value, {
'action': 'restore_last_saved',
'channels': ['uia_select', 'win32_button_click', 'uia_invoke'],
})
assert result.channel == 'win32_button_click'
assert result.accepted_controls == (6213,)
assert selected == []
assert posted and posted[0][0] == 11
def test_agent_polling_does_not_write_request_response_capture_files(tmp_path):
client, server, thread = running_protocol(tmp_path, FakeProbe(snapshot()))
try:
for _ in range(80):
assert client.observe(DialogPhase.PCB_STARTING)[0].hwnd == 10
assert not list(tmp_path.glob('*.jsonl'))
assert len(server.requests) <= 1
assert len(server.responses) <= 1
finally:
client.close()
thread.join(timeout=2)
assert not thread.is_alive()
def test_agent_start_failure_releases_listener(tmp_path):
import pytest
class FailedWorker:
name = 'test'
def start_companion(self, command):
raise RuntimeError('cannot create companion')
with pytest.raises(RuntimeError, match='cannot create companion'):
DialogAgentClient.start(FailedWorker(), tmp_path)
def test_memory_channel_timeout_is_bounded_and_partial_packets_survive():
import socket
import pytest
from cbb_refresh_verify.dialog_agent import JsonChannel
a, b = socket.socketpair()
channel = JsonChannel(a)
try:
b.sendall(b'{"value":')
with pytest.raises(TimeoutError):
channel.receive(.05)
b.sendall(b'17}\n')
assert channel.receive(.5) == {'value': 17}
b.close()
with pytest.raises(EOFError):
channel.receive(.5)
finally:
channel.close()
b.close()
def test_loopback_connection_rejects_wrong_agent_token(tmp_path):
import socket
import pytest
from cbb_refresh_verify.dialog_agent import JsonChannel, DialogAgentProtocolError
client = DialogAgentClient.prepare(tmp_path, desktop_name='test', timeout_seconds=.3)
wrong = JsonChannel(socket.create_connection(('127.0.0.1', client.paths.port), timeout=1))
try:
wrong.send({'token': 'not-the-agent'})
with pytest.raises(DialogAgentProtocolError, match='authentication failed'):
client.observe(DialogPhase.PCB_STARTING)
finally:
wrong.close()
client.close()
+53
View File
@@ -0,0 +1,53 @@
from cbb_refresh_verify.dialog_models import (
ControlSnapshot,
DialogPhase,
WindowSnapshot,
stable_fingerprint,
)
def snapshot(*, hwnd=10, pid=20, text="Elapsed time 11 C:\\A\\x.pcb",
control_types=("Button",)):
controls = tuple(
ControlSnapshot(
handle=100 + index,
control_id=index + 1,
class_name=control_type,
name=text if index == 0 else control_type,
control_type=control_type,
)
for index, control_type in enumerate(control_types)
)
return WindowSnapshot(
hwnd=hwnd,
pid=pid,
process_name="ExpeditionPCB.exe",
process_role="pcb",
window_class="#32770",
title="Expedition PCB",
phase=DialogPhase.PROJECT_INTEGRATION,
controls=controls,
)
def test_fingerprint_ignores_handle_pid_paths_and_elapsed_numbers():
first = snapshot(hwnd=10, pid=20, text="Elapsed time 11 C:\\A\\x.pcb")
second = snapshot(hwnd=99, pid=77, text="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"))
)
def test_snapshot_json_round_trip_preserves_original_evidence():
original = snapshot(text="数据库恢复 C:\\Work\\A.pcb")
restored = WindowSnapshot.from_record(original.to_record())
assert restored == original
assert restored.controls[0].name == "数据库恢复 C:\\Work\\A.pcb"
+169
View File
@@ -0,0 +1,169 @@
import pywintypes
from cbb_refresh_verify.dialog_models import DialogPhase
from cbb_refresh_verify.dialog_probe import WindowProbe
PHASE = DialogPhase.PCB_STARTING
class FakeDesktop:
def __init__(self, handles=()):
self.handles = tuple(handles)
def EnumDesktopWindows(self):
return self.handles
class FakeGui:
def __init__(self, windows, children=None, disappearing=()):
self.windows = windows
self.children = children or {}
self.disappearing = set(disappearing)
self.callback_results = []
def IsWindowVisible(self, hwnd):
return self.windows[hwnd].get("visible", True)
def GetClassName(self, hwnd):
return self.windows[hwnd].get("class_name", "")
def GetWindowText(self, hwnd):
if hwnd in self.disappearing:
raise pywintypes.error(1400, "GetWindowText", "invalid window")
return self.windows[hwnd].get("text", "")
def GetDlgCtrlID(self, hwnd):
return self.windows[hwnd].get("control_id", 0)
def IsWindowEnabled(self, hwnd):
return self.windows[hwnd].get("enabled", True)
def GetWindow(self, hwnd, _command):
return self.windows[hwnd].get("owner", 0)
def EnumChildWindows(self, hwnd, callback, context):
for child in self.children.get(hwnd, ()):
self.callback_results.append(callback(child, context))
def SendMessage(self, *_args):
return 0
class FakeProcess:
@staticmethod
def GetWindowThreadProcessId(hwnd):
return 1, 1000 + hwnd
class FakeUia:
def __init__(self, records=None, error=None):
self.records = records or {}
self.error = error
def controls(self, hwnd):
if self.error:
raise self.error
return self.records.get(hwnd, ())
def make_probe(gui, handles, uia=None):
return WindowProbe(
desktop=FakeDesktop(handles),
win32gui=gui,
win32process=FakeProcess(),
process_name_reader=lambda pid: f"proc-{pid}.exe",
uia=uia or FakeUia(),
)
def test_probe_keeps_visible_non_dialog_classes():
gui = FakeGui({10: {"class_name": "GXWND", "text": "License chooser"}})
snapshots = make_probe(gui, (10,)).capture(PHASE)
assert [item.window_class for item in snapshots] == ["GXWND"]
assert snapshots[0].process_name == "proc-1010.exe"
def test_disappearing_window_is_skipped_without_hiding_other_windows():
gui = FakeGui({
10: {"class_name": "GXWND", "text": "gone"},
20: {"class_name": "#32770", "text": "still here"},
}, disappearing=(10,))
snapshots = make_probe(gui, (10, 20)).capture(PHASE)
assert [item.hwnd for item in snapshots] == [20]
def test_uia_enrichment_records_patterns_and_automation_id():
gui = FakeGui({10: {"class_name": "GXWND", "text": "License chooser"}})
uia = FakeUia({10: ({
"handle": 101,
"control_id": 1522,
"class_name": "GXWND",
"name": "Product license",
"automation_id": "licenseList",
"control_type": "ListItem",
"enabled": True,
"selected": True,
"checked": False,
"patterns": ("SelectionItem",),
},)})
control = make_probe(gui, (10,), uia).capture(PHASE)[0].controls[0]
assert control.automation_id == "licenseList"
assert control.patterns == ("SelectionItem",)
assert control.selected is True
def test_uia_failure_keeps_win32_evidence_and_adds_diagnostic():
windows = {
10: {"class_name": "#32770", "text": "Prompt"},
11: {"class_name": "Button", "text": "OK", "control_id": 1},
}
gui = FakeGui(windows, children={10: (11,)})
snapshot = make_probe(gui, (10,), FakeUia(error=RuntimeError("uia down"))).capture(PHASE)[0]
assert snapshot.controls[0].name == "OK"
assert snapshot.diagnostics == ("UIA_ERROR: uia down",)
assert gui.callback_results == [True]
def test_empty_private_desktop_winerror_two_is_transient():
class EmptyDesktop:
@staticmethod
def EnumDesktopWindows():
raise pywintypes.error(2, "EnumDesktopWindows", "file not found")
probe = WindowProbe(
desktop=EmptyDesktop(), win32gui=object(), win32process=object(),
process_name_reader=lambda _pid: "", uia=FakeUia(),
)
assert probe.capture(PHASE) == ()
def test_probe_ignores_input_indicator_afx_and_hidden_ie_windows():
gui = FakeGui({
10: {"class_name": "UAC_InputIndicatorOverlayWnd", "text": ""},
20: {"class_name": "UAC Input Indicator", "text": ""},
30: {"class_name": "Afx:00400000:0:00010003:00000000:00000000", "text": ""},
35: {"class_name": "Internet Explorer_Hidden", "text": ""},
40: {"class_name": "#32770", "text": "real dialog"},
})
snapshots = make_probe(gui, (10, 20, 30, 35, 40)).capture(PHASE)
assert [item.hwnd for item in snapshots] == [40]
def test_probe_skips_project_integration_panel_during_com_phase():
gui = FakeGui({10: {"class_name": "#32770", "text": "Project Integration"}})
snapshots = make_probe(gui, (10,)).capture(DialogPhase.PROJECT_INTEGRATION)
assert snapshots == ()
+246
View File
@@ -0,0 +1,246 @@
import json
from pathlib import Path
import pytest
from cbb_refresh_verify.dialog_models import ControlSnapshot, DialogPhase, WindowSnapshot
from cbb_refresh_verify.dialog_rules import (
DialogRule,
RuleConfigError,
decide,
load_rules,
)
ASSETS = Path(__file__).resolve().parents[1] / "src" / "cbb_refresh_verify" / "assets"
def prompt(text, *, phase=DialogPhase.PCB_STARTING, window_class="#32770",
control_types=("Text", "Button")):
controls = tuple(
ControlSnapshot(
handle=100 + index,
control_id=index,
class_name=control_type,
name=text if index == 0 else "OK",
control_type=control_type,
patterns=("Invoke",) if control_type == "Button" else (),
)
for index, control_type in enumerate(control_types)
)
return WindowSnapshot(
hwnd=10,
pid=20,
process_name="ExpeditionPCB.exe",
process_role="pcb",
window_class=window_class,
title="Expedition PCB",
phase=phase,
controls=controls,
)
def matching_rule(rule_id, priority):
return DialogRule(
rule_id=rule_id,
priority=priority,
category="OBSERVE_PROGRESS",
phases=(DialogPhase.PROJECT_INTEGRATION,),
semantic_all=("task is being processed",),
)
def test_default_save_rule_is_out_of_phase_during_license_acquisition():
rules = load_rules(ASSETS / "dialog_rules.v1.json")
snapshot = prompt(
"Do you want to save the Reusable Block cell?",
phase=DialogPhase.LICENSE_ACQUISITION,
)
decision = decide(snapshot, rules)
assert decision.error_code == "DIALOG_OUT_OF_PHASE"
assert decision.rule_id == "reusable-block-save"
def test_license_selector_is_allowed_after_com_attach_wait():
rules = load_rules(ASSETS / "dialog_rules.v1.json")
snapshot = prompt(
"Select the desired product license",
phase=DialogPhase.DOCUMENT_ATTACH,
window_class="#32770",
control_types=("GXWND", "Button"),
)
decision = decide(snapshot, rules)
assert decision.rule_id == "license-selector"
assert decision.error_code == ""
def test_open_lock_confirmation_is_allowed_during_pcb_starting():
rules = load_rules(ASSETS / "dialog_rules.v1.json")
snapshot = prompt(
"Continue to open the design with read/write access permission?",
phase=DialogPhase.PCB_STARTING,
)
decision = decide(snapshot, rules)
assert decision.rule_id == "open-lock-confirm"
assert decision.error_code == ""
def test_forward_annotation_confirmation_is_accepted_during_document_attach():
rules = load_rules(ASSETS / "dialog_rules.v1.json")
snapshot = prompt(
"New changes are ready for Forward Annotation. Do you want to Forward Annotate now?",
phase=DialogPhase.DOCUMENT_ATTACH,
)
decision = decide(snapshot, rules)
assert decision.rule_id == "forward-annotation-confirm"
assert decision.action == "confirm_forward_annotation"
assert decision.error_code == ""
def test_forward_annotation_confirmation_is_accepted_during_pcb_starting():
rules = load_rules(ASSETS / "dialog_rules.v1.json")
snapshot = prompt(
"New changes are ready for Forward Annotation. Do you want to Forward Annotate now?",
phase=DialogPhase.PCB_STARTING,
)
decision = decide(snapshot, rules)
assert decision.rule_id == "forward-annotation-confirm"
assert decision.action == "confirm_forward_annotation"
assert decision.error_code == ""
def test_project_integration_panel_is_observation_only():
rules = load_rules(ASSETS / "dialog_rules.v1.json")
snapshot = prompt(
"&Project file and Design Forward Annotation Required, connectivity changed "
"No pending schematic CES changes to load into PCB",
phase=DialogPhase.PROJECT_INTEGRATION,
)
decision = decide(snapshot, rules)
assert decision.rule_id == "project-integration-panel"
assert decision.category == "OBSERVE_PROGRESS"
assert decision.action == ""
assert decision.error_code == ""
def test_license_selector_prefers_nonblocking_ok_click_before_uia_invoke():
rules = load_rules(ASSETS / "dialog_rules.v1.json")
snapshot = prompt(
"Select the desired product license",
phase=DialogPhase.DOCUMENT_ATTACH,
window_class="#32770",
control_types=("GXWND", "Button"),
)
decision = decide(snapshot, rules)
assert decision.channels.index("win32_button_click") < decision.channels.index("uia_invoke")
def test_tip_of_day_prefers_nonblocking_ok_click_before_uia_invoke():
rules = load_rules(ASSETS / "dialog_rules.v1.json")
decision = decide(prompt("Tip of the Day"), rules)
assert decision.rule_id == "tip-of-day"
assert decision.channels.index("win32_button_click") < decision.channels.index("uia_invoke")
def test_integration_progress_out_of_phase_remains_observation_only():
rules = load_rules(ASSETS / "dialog_rules.v1.json")
decision = decide(
prompt(
"Your task is being processed. Elapsed time 10 seconds",
phase=DialogPhase.SAVE,
),
rules,
)
assert decision.rule_id == "integration-progress"
assert decision.category == "OBSERVE_PROGRESS"
assert decision.error_code == "DIALOG_OUT_OF_PHASE"
def test_equal_priority_matches_are_rejected():
snapshot = prompt(
"Your task is being processed. Elapsed time 10 seconds",
phase=DialogPhase.PROJECT_INTEGRATION,
)
decision = decide(snapshot, (matching_rule("a", 10), matching_rule("b", 10)))
assert decision.error_code == "DIALOG_RULE_CONFLICT"
assert "a" in decision.detail and "b" in decision.detail
def test_override_replaces_rule_by_id(tmp_path):
override = tmp_path / "rules.json"
override.write_text(json.dumps({
"schema_version": 1,
"rules": [{"rule_id": "tip-of-day", "enabled": False}],
}), encoding="utf-8")
rules = load_rules(ASSETS / "dialog_rules.v1.json", override)
assert next(rule for rule in rules if rule.rule_id == "tip-of-day").enabled is False
def test_unknown_schema_is_rejected(tmp_path):
path = tmp_path / "rules.json"
path.write_text(json.dumps({"schema_version": 2, "rules": []}), encoding="utf-8")
with pytest.raises(RuleConfigError, match="schema_version"):
load_rules(path)
def test_negative_semantic_evidence_prevents_match():
rule = DialogRule(
rule_id="continue-not-cancel",
priority=1,
category="SAFE_CONFIRM",
phases=(DialogPhase.PCB_STARTING,),
semantic_any=("continue",),
semantic_none=("destructive",),
action="confirm",
)
decision = decide(prompt("Continue destructive recovery"), (rule,))
assert decision.error_code == "UNKNOWN_DIALOG"
def test_known_ime_language_bar_is_observation_only_not_an_unknown_dialog():
snapshot = WindowSnapshot(hwnd=100, pid=200, process_name='ExpeditionPCB.exe',
process_role='pcb', window_class='CiceroUIWndFrame', title='TF_FloatingLangBar_WndTitle',
phase=DialogPhase.PCB_STARTING, controls=(), owner_hwnd=99)
decision = decide(snapshot, load_rules(ASSETS/'dialog_rules.v1.json'))
assert decision.category == 'OBSERVE_PROGRESS'
assert decision.error_code == ''
assert decision.action == ''
def test_language_bar_filter_does_not_ignore_a_real_dialog_with_same_caption():
snapshot = prompt('TF_FloatingLangBar_WndTitle')
decision = decide(snapshot, load_rules(ASSETS/'dialog_rules.v1.json'))
assert decision.error_code == 'UNKNOWN_DIALOG'
def test_database_open_failure_is_classified_and_declines_log_view():
snapshot = prompt('Problem encountered while opening one of the database files. '
'See PCBLogFile.txt for details. Loading of the job has failed. '
'Do you wish to view the log file now?')
decision = decide(snapshot, load_rules(ASSETS/'dialog_rules.v1.json'))
assert decision.category == 'FATAL_ACK'
assert decision.error_code == 'MENTOR_DATABASE_LOAD_FAILED'
assert dict(decision.target)['control_id'] == 7 # IDNO, never launch another log viewer
+475
View File
@@ -0,0 +1,475 @@
from cbb_refresh_verify.dialog_supervisor import (
AgentDialogBackend,
DialogControl,
DialogObservationError,
DialogSnapshot,
DialogSupervisor,
Win32DialogBackend,
)
from cbb_refresh_verify.dialog_agent import ActionResult
from cbb_refresh_verify.dialog_models import (
ControlSnapshot as EvidenceControl,
DialogPhase,
WindowSnapshot,
)
from cbb_refresh_verify.dialog_rules import load_rules
from pathlib import Path
def dialog(text, *, title="Expedition PCB", hwnd=100, pid=200, buttons=("OK", "Cancel")):
controls = [DialogControl(1000, 0, "Static", text, True)]
controls.extend(
DialogControl(1100 + index, control_id, "Button", caption, True)
for index, (control_id, caption) in enumerate(zip((1, 2, 6, 7), buttons))
)
return DialogSnapshot(hwnd, pid, title, tuple(controls))
def license_dialog():
return dialog("Select the desired product license", title="", buttons=("OK", "Cancel"))
def save_error_dialog():
return dialog("Error saving the Reusable Block. See log file, ReusableBlock.txt.",
buttons=("OK",))
class FakeDialogs:
def __init__(self, observations):
self.observations = list(observations)
self.actions = []
def observe(self):
if not self.observations:
return ()
return tuple(self.observations.pop(0))
def perform(self, snapshot, action):
self.actions.append((snapshot.hwnd, action))
return (1,)
def test_click_is_not_resolved_until_dialog_disappears():
backend = FakeDialogs([[license_dialog()], [license_dialog()], []])
supervisor = DialogSupervisor(backend, retry_seconds=0, max_attempts=3)
first = supervisor.poll()
second = supervisor.poll()
third = supervisor.poll()
assert first.action_sent
assert not first.resolved
assert second.action_sent
assert not second.resolved
assert third.resolved
assert len(backend.actions) == 2
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()
result = supervisor.poll()
assert result.error_code == "DIALOG_STUCK"
assert len(backend.actions) == 2
def test_unknown_dialog_is_recorded_but_not_clicked():
backend = FakeDialogs([[dialog("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():
backend = FakeDialogs([[save_error_dialog()]])
result = DialogSupervisor(backend).poll()
assert result.error_code == "SAVE_REUSABLE_BLOCK_FAILED"
assert backend.actions == [(100, "acknowledge_fatal")]
def test_changed_text_on_reused_handle_is_a_new_dialog_state():
backend = FakeDialogs([
[license_dialog()],
[dialog("Do you want to save the Reusable Block cell?", buttons=("Yes", "No"))],
])
supervisor = DialogSupervisor(backend, retry_seconds=60, max_attempts=3)
assert supervisor.poll().action_sent
result = supervisor.poll()
assert result.action_sent
assert backend.actions == [(100, "accept_license"), (100, "save_reusable_block")]
def test_progress_dialog_with_only_cancel_is_observed_not_clicked():
backend = FakeDialogs([[dialog("Your task is being processed. Elapsed time 10 seconds",
buttons=("Cancel",))]])
result = DialogSupervisor(backend).poll()
assert not result.action_sent
assert not result.error_code
assert backend.actions == []
def test_progress_dialog_text_change_counts_as_activity_without_clicking():
backend = FakeDialogs([
[dialog("Your task is being processed. Elapsed time 10 seconds", buttons=("Cancel",))],
[dialog("Your task is being processed. Elapsed time 11 seconds", buttons=("Cancel",))],
])
supervisor = DialogSupervisor(backend)
first = supervisor.poll()
second = supervisor.poll()
assert first.activity
assert second.activity
assert backend.actions == []
def test_win32_enumeration_callbacks_always_continue():
callback_results = []
class FakeGui:
def EnumWindows(self, callback, context):
callback_results.extend((callback(10, context), callback(20, context)))
def IsWindowVisible(self, hwnd):
return True
def GetClassName(self, hwnd):
return "#32770" if hwnd == 10 else "Other"
def EnumChildWindows(self, hwnd, callback, context):
callback_results.extend((callback(101, context), callback(102, context)))
def GetWindowText(self, hwnd):
return {10: "", 101: "Select the desired product license", 102: "OK"}.get(hwnd, "")
def GetDlgCtrlID(self, hwnd):
return 1 if hwnd == 102 else 0
def IsWindowEnabled(self, hwnd):
return True
def SendMessage(self, hwnd, message, wparam, lparam):
return 0
class FakeProcess:
@staticmethod
def GetWindowThreadProcessId(hwnd):
return 1, 200
snapshots = Win32DialogBackend(
{200}, win32gui=FakeGui(), win32process=FakeProcess(), win32con=object()
).observe()
assert callback_results == [True, True, True, True]
assert len(snapshots) == 1
assert snapshots[0].pid == 200
def test_database_restoration_selects_choice_before_confirming():
clicks = []
class Gui:
@staticmethod
def PostMessage(hwnd, *_args):
clicks.append(hwnd)
backend = Win32DialogBackend(
set(), win32gui=Gui(), win32process=object(), win32con=object()
)
choice = DialogControl(10, 6213, 'Button', 'Load the last user saved database', True)
ok = DialogControl(11, 1, 'Button', 'OK', True)
snapshot = DialogSnapshot(1, 2, 'Database Restoration', (choice, ok))
assert backend.perform(snapshot, 'restore_last_saved') == (6213,)
selected = DialogControl(10, 6213, 'Button', 'Load the last user saved database', True,
checked=True)
snapshot = DialogSnapshot(1, 2, 'Database Restoration', (selected, ok))
assert backend.perform(snapshot, 'restore_last_saved') == (1,)
assert clicks == [10, 11]
def test_license_waits_for_list_selection_before_clicking_ok():
clicks = []
class Gui:
@staticmethod
def PostMessage(hwnd, *_args):
clicks.append(hwnd)
backend = Win32DialogBackend(
set(), win32gui=Gui(), win32process=object(), win32con=object()
)
ok = DialogControl(11, 1, 'Button', 'OK', True)
unselected = DialogControl(12, 20, 'ComboBox', '', True, selected=False)
selected = DialogControl(12, 20, 'ComboBox', '', True, selected=True)
assert backend.perform(DialogSnapshot(1, 2, '', (unselected, ok)), 'accept_license') == ()
assert backend.perform(DialogSnapshot(1, 2, '', (selected, ok)), 'accept_license') == (1,)
assert clicks == [11]
def test_license_dialog_opens_product_selector_before_waiting_for_selection():
clicks = []
class Gui:
@staticmethod
def PostMessage(hwnd, *_args):
clicks.append(hwnd)
backend = Win32DialogBackend(
set(), win32gui=Gui(), win32process=object(), win32con=object()
)
selector = DialogControl(10, 5225, 'Button', 'Select the desired product license', True)
custom_list = DialogControl(11, 1522, 'GXWND', '', True)
ok = DialogControl(12, 1, 'Button', 'OK', True)
snapshot = DialogSnapshot(1, 2, '', (selector, custom_list, ok))
assert backend.perform(snapshot, 'accept_license') == (5225,)
assert clicks == [10]
def test_window_enumeration_failure_is_structured_not_silent():
class BrokenGui:
@staticmethod
def EnumWindows(_callback, _context):
raise RuntimeError('enum failed')
class Backend:
@staticmethod
def observe():
raise DialogObservationError('WINDOW_ENUM_ERROR', 'enum failed')
result = DialogSupervisor(Backend()).poll()
assert result.error_code == 'WINDOW_ENUM_ERROR'
backend = Win32DialogBackend(
set(), win32gui=BrokenGui(), win32process=object(), win32con=object()
)
result = DialogSupervisor(backend).poll()
assert result.error_code == 'WINDOW_ENUM_ERROR'
def test_private_desktop_without_windows_is_transient_not_fatal():
class EmptyDesktop:
@staticmethod
def EnumDesktopWindows():
import pywintypes
raise pywintypes.error(2, 'EnumDesktopWindows', 'file not found')
backend = Win32DialogBackend(
set(), desktop=EmptyDesktop(), win32gui=object(),
win32process=object(), win32con=object()
)
assert backend.observe() == ()
def test_private_desktop_access_failure_remains_structured():
class BrokenDesktop:
@staticmethod
def EnumDesktopWindows():
import pywintypes
raise pywintypes.error(5, 'EnumDesktopWindows', 'access denied')
backend = Win32DialogBackend(
set(), desktop=BrokenDesktop(), win32gui=object(),
win32process=object(), win32con=object()
)
result = DialogSupervisor(backend).poll()
assert result.error_code == 'WINDOW_ENUM_ERROR'
RULES = load_rules(
Path(__file__).resolve().parents[1] / 'src' / 'cbb_refresh_verify' / 'assets' /
'dialog_rules.v1.json'
)
def evidence_window(text, *, phase, window_class='#32770', selected=False):
return WindowSnapshot(
hwnd=500,
pid=600,
process_name='ExpeditionPCB.exe',
process_role='pcb',
window_class=window_class,
title='Expedition PCB',
phase=phase,
controls=(
EvidenceControl(501, 0, 'Static', text, control_type='Text'),
EvidenceControl(502, 1, 'Button', 'OK', control_type='Button',
enabled=True, selected=selected, patterns=('Invoke',)),
),
owner_hwnd=400,
)
class PhaseBackend:
def __init__(self, observations):
self.observations = list(observations)
self.actions = []
def observe(self, phase):
if not self.observations:
return ()
return tuple(self.observations.pop(0))
def perform(self, snapshot, action, phase):
self.actions.append((snapshot.hwnd, action, phase))
return ActionResult(channel='uia_invoke', accepted_controls=(1,))
def test_phase_aware_unknown_window_fails_without_action():
backend = PhaseBackend([[
evidence_window('Unrecognized destructive prompt', phase=DialogPhase.PCB_STARTING,
window_class='GXWND')
]])
result = DialogSupervisor(backend, rules=RULES).poll(DialogPhase.PCB_STARTING)
assert result.error_code == 'UNKNOWN_DIALOG'
assert backend.actions == []
def test_phase_aware_action_is_pending_until_window_disappears():
restore = evidence_window(
'Database Restoration - Load the last user saved database',
phase=DialogPhase.DATABASE_RECOVERY,
)
backend = PhaseBackend([[restore], []])
supervisor = DialogSupervisor(backend, rules=RULES, retry_seconds=60)
first = supervisor.poll(DialogPhase.DATABASE_RECOVERY)
second = supervisor.poll(DialogPhase.DATABASE_RECOVERY)
assert first.action_sent and not first.resolved
assert second.resolved
assert len(backend.actions) == 1
def test_phase_aware_changed_content_is_not_window_gone():
first = evidence_window(
'Database Restoration - Load the last user saved database',
phase=DialogPhase.DATABASE_RECOVERY,
)
changed = evidence_window(
'Database Restoration - Load the last user saved database - selected',
phase=DialogPhase.DATABASE_RECOVERY,
selected=True,
)
backend = PhaseBackend([[first], [changed]])
supervisor = DialogSupervisor(backend, rules=RULES, retry_seconds=60)
first_result = supervisor.poll(DialogPhase.DATABASE_RECOVERY)
second_result = supervisor.poll(DialogPhase.DATABASE_RECOVERY)
assert first_result.action_sent and not first_result.resolved
assert not second_result.resolved
def test_phase_aware_fatal_error_cannot_become_success():
fatal = evidence_window(
'There were errors during Project Integration',
phase=DialogPhase.PROJECT_INTEGRATION,
)
backend = PhaseBackend([[fatal]])
result = DialogSupervisor(backend, rules=RULES).poll(DialogPhase.PROJECT_INTEGRATION)
assert result.error_code == 'PROJECT_INTEGRATION_FAILED'
assert result.rule_id == 'integration-error'
assert backend.actions
def test_agent_backend_forwards_phase_fingerprint_and_action():
calls = []
class Client:
def observe(self, phase):
calls.append(('observe', phase))
return ()
def perform(self, **values):
calls.append(('perform', values))
return ActionResult(channel='uia_invoke', accepted_controls=(1,))
backend = AgentDialogBackend(Client())
window = evidence_window('Tip of the Day', phase=DialogPhase.PCB_STARTING)
backend.observe(DialogPhase.PCB_STARTING)
backend.perform(window, {'action': 'dismiss_tip'}, DialogPhase.PCB_STARTING)
assert calls[0] == ('observe', DialogPhase.PCB_STARTING)
assert calls[1][1]['hwnd'] == 500
assert calls[1][1]['fingerprint']
def native_database_open_error():
return DialogSnapshot(100, 200, 'Expedition PCB', (
DialogControl(1000, 0, 'Static',
'Problem encountered while opening one of the database files. '
'See PCBLogFile.txt for details. Loading of the job has failed. '
'Do you wish to view the log file now?', True),
DialogControl(1100, 6, 'Button', 'Yes', True),
DialogControl(1101, 7, 'Button', 'No', True),
))
def test_legacy_native_database_failure_is_classified_and_declines_log_viewer():
backend = FakeDialogs([[native_database_open_error()]])
result = DialogSupervisor(backend).poll()
assert result.error_code == 'MENTOR_DATABASE_LOAD_FAILED'
assert backend.actions == [(100, 'decline_database_log')]
def test_legacy_database_failure_clicks_idno_never_yes():
clicks = []
class Gui:
def PostMessage(self, handle, *args):
clicks.append(handle)
backend = Win32DialogBackend({200}, win32gui=Gui(), win32process=object(), win32con=object())
assert backend.perform(native_database_open_error(), 'decline_database_log') == (7,)
assert clicks == [1101]
only_yes = DialogSnapshot(100, 200, 'Expedition PCB', native_database_open_error().controls[:-1])
assert backend.perform(only_yes, 'decline_database_log') == ()
assert clicks == [1101]
def test_versioned_supervision_ignores_ime_and_still_handles_next_real_dialog():
phase = DialogPhase.PCB_STARTING
ime = WindowSnapshot(hwnd=800, pid=600, process_name='ExpeditionPCB.exe', process_role='pcb',
window_class='CiceroUIWndFrame', title='TF_FloatingLangBar_WndTitle', phase=phase,
owner_hwnd=400, controls=())
from dataclasses import replace
license_prompt = evidence_window('Select the desired product license', phase=phase)
license_prompt = replace(license_prompt, controls=(
replace(license_prompt.controls[0], class_name='GXWND'), license_prompt.controls[1]))
backend = PhaseBackend([[ime, license_prompt]])
result = DialogSupervisor(backend, rules=RULES).poll(phase)
assert not result.error_code
assert result.action_sent
assert len(backend.actions) == 1 and backend.actions[0][0] == license_prompt.hwnd
def test_versioned_database_open_failure_action_targets_no_button():
from dataclasses import replace
window = evidence_window(native_database_open_error().texts[0], phase=DialogPhase.DOCUMENT_ATTACH)
window = replace(window, controls=(window.controls[0],
EvidenceControl(502, 6, 'Button', 'Yes', control_type='Button'),
EvidenceControl(503, 7, 'Button', 'No', control_type='Button')))
backend = PhaseBackend([[window]])
result = DialogSupervisor(backend, rules=RULES).poll(window.phase)
assert result.error_code == 'MENTOR_DATABASE_LOAD_FAILED'
assert dict(backend.actions[0][1]['target']) == {'control_id': 7}
+56
View File
@@ -0,0 +1,56 @@
from pathlib import Path
def test_parse_icdb_server_address_extracts_port_and_hosts(tmp_path):
from cbb_refresh_verify.mentor_adapter import parse_icdb_server_address
address = tmp_path / "sAddress.adr"
address.write_text(
"guid\n127.0.0.1\n192.168.1.10\n10062\n1094\n"
"vt40T8RtWJOG2cE2Nlvc5A\n535943\n",
encoding="ascii",
)
assert parse_icdb_server_address(address) == {
"port": 10062,
"hosts": ["127.0.0.1", "192.168.1.10"],
}
def test_stale_icdb_address_is_moved_to_evidence(tmp_path, monkeypatch):
from cbb_refresh_verify import mentor_adapter
database = tmp_path / "database"
address = database / "cdbsvr" / "sAddress.adr"
address.parent.mkdir(parents=True)
address.write_text("guid\n127.0.0.1\n10062\n1094\n", encoding="ascii")
monkeypatch.setattr(mentor_adapter, "probe_icdb_server", lambda hosts, port: (False, "10062 unreachable"))
events = []
result = mentor_adapter.prepare_icdb_address(
database,
tmp_path / "evidence",
emit=lambda **event: events.append(event),
)
assert result["status"] == "STALE_MOVED"
assert not address.exists()
moved = list((tmp_path / "evidence" / "diagnostics" / "cdbsvr").glob("sAddress.adr.stale-*"))
assert len(moved) == 1
assert moved[0].read_text(encoding="ascii") == "guid\n127.0.0.1\n10062\n1094\n"
assert events[-1]["stage"] == "icdb_address_stale"
def test_live_icdb_address_is_left_in_place(tmp_path, monkeypatch):
from cbb_refresh_verify import mentor_adapter
database = tmp_path / "database"
address = database / "cdbsvr" / "sAddress.adr"
address.parent.mkdir(parents=True)
address.write_text("guid\n127.0.0.1\n10062\n1094\n", encoding="ascii")
monkeypatch.setattr(mentor_adapter, "probe_icdb_server", lambda hosts, port: (True, "127.0.0.1:10062"))
result = mentor_adapter.prepare_icdb_address(database, tmp_path / "evidence")
assert result["status"] == "LIVE"
assert address.is_file()
+570
View File
@@ -0,0 +1,570 @@
from pathlib import Path
import hashlib
import os
import pytest
from cbb_refresh_verify.integration import IntegrationError, refresh_integration
from cbb_refresh_verify.mentor_adapter import (pcb_log_reports_integration_error,
save_log_has_core_markers,
build_backup_command, best_effort_backup,
backup_timeout_seconds,
choose_dialog_action, cleanup_evidence_backup,
ActivityDeadline, cleanup_verify_processes,
ensure_pcb_central_library, is_network_backed_path)
from cbb_refresh_verify.library_manager_verify import (_fresh_library_pids, _menu_click_lparam,
_invoke_interactive_verify)
class FakeProjectIntegration:
ForwardAnnotationStatus = 1
SynchCESStatus = 2
LoadCESStatus = 2
BackAnnotationStatus = 2
IsForwardAnnotationAllowed = True
IsSynchCESAllowed = True
IsLoadCESAllowed = True
IsBackAnnotationAllowed = True
forward_calls = 0
def ForwardAnnotate(self):
self.forward_calls += 1
return True
def test_database_restoration_dialog_selects_last_saved_database():
action = choose_dialog_action(
'Database Restoration',
['Restore Database', 'Load the last user saved database dated 2026/9/3 19:32.',
'Load the autosave database dated 2026/9/3 19:32.', 'OK', 'Cancel'],
)
assert action == 'restore_last_saved'
def test_library_manager_fresh_pid_filter_rejects_stale_sessions():
assert _fresh_library_pids({10, 11}, {10, 11, 12, 13}, 12) == {12, 13}
def test_library_manager_menu_click_lparam_is_relative_to_popup_window():
assert _menu_click_lparam((50, 150, 300, 500), (140, 280, 260, 320)) == (150 << 16) | 150
def test_library_manager_menu_click_lparam_accepts_uia_rect_objects():
class Rect:
left = 140
top = 280
right = 260
bottom = 320
assert _menu_click_lparam((50, 150, 300, 500), Rect()) == (150 << 16) | 150
def test_interactive_verify_focuses_library_manager_before_real_right_click():
calls = []
class Target:
def set_focus(self):
calls.append('focus')
class Item:
def select(self):
calls.append('select')
def click_input(self, *, button):
calls.append(('click', button))
_invoke_interactive_verify(Target(), Item())
assert calls == ['focus', 'select', ('click', 'right')]
def test_cleanup_verify_processes_terminates_worker_parent_and_lm(monkeypatch):
from cbb_refresh_verify import mentor_adapter
terminated = []
monkeypatch.setattr(mentor_adapter, '_terminate_pid',
lambda pid, **_kwargs: terminated.append(int(pid)))
cleanup_verify_processes(101, 202, 303, emit=lambda **event: None)
assert terminated == [202, 303, 101]
def test_cleanup_verify_processes_discovers_unbound_target_pcb_processes(monkeypatch):
from cbb_refresh_verify import mentor_adapter
terminated = []
target = r'S:\Mentor_lib\ReusableBlocksLP\CBB\Work\CBB.pcb'
command = rf'"C:\Mentor\common\ExpeditionPCB.exe" "{target}" -ReusableCircuit'
monkeypatch.setattr(
mentor_adapter,
'_process_details',
lambda _name: [
(202, r'C:\Mentor\wg\ExpeditionPCB.exe', command, 303),
(303, r'C:\Mentor\common\ExpeditionPCB.exe', command, 101),
(204, r'C:\Mentor\wg\ExpeditionPCB.exe', command, 777),
(999, r'C:\Mentor\wg\ExpeditionPCB.exe', command, 0),
],
)
monkeypatch.setattr(mentor_adapter, '_terminate_pid',
lambda pid, **_kwargs: terminated.append(int(pid)))
mentor_adapter.cleanup_verify_processes(
101,
None,
None,
expected_pcb=target,
baseline_pids={999},
emit=lambda **event: None,
)
assert terminated == [202, 303, 204, 101]
def test_verify_cleanup_is_present_on_all_exit_paths():
from cbb_refresh_verify import mentor_adapter
import inspect
source = inspect.getsource(mentor_adapter.execute_job)
assert 'cleanup_verify_processes(' in source
assert 'expected_pcb=job.get(\'pcb\')' in source
def test_real_verify_execution_no_longer_calls_legacy_dialog_handler():
from cbb_refresh_verify import mentor_adapter
import inspect
source = inspect.getsource(mentor_adapter.execute_job)
assert 'handle_known_dialogs(' not in source
assert 'choose_dialog_action(' not in source
def test_real_verify_execution_uses_observed_reusable_circuit_route():
from cbb_refresh_verify import mentor_adapter
import inspect
source = inspect.getsource(mentor_adapter.execute_job)
assert 'native_lm_verify' in source
assert "job['lmc_file']" in source
assert 'build_pcb_launch_command' in source
assert 'launch_pcb_process' in source
def test_real_verify_keeps_licensing_in_32bit_save_helper():
from cbb_refresh_verify import mentor_adapter
import inspect
source = inspect.getsource(mentor_adapter.execute_job)
assert 'validate_document(' not in source
assert "save_verified_block.vbs" in source
def test_unknown_modal_prefers_safe_positive_action():
action = choose_dialog_action('Expedition PCB', ['Continue', 'Cancel'])
assert action == 'positive'
def test_unknown_modal_uses_fallback_action():
action = choose_dialog_action('Expedition PCB', ['Proceed with design recovery', 'Dismiss'])
assert action == 'fallback'
def test_evidence_backup_is_reclaimed(tmp_path):
backup = tmp_path/'backup'
(backup/'CBB'/'Cert').mkdir(parents=True)
(backup/'CBB'/'Cert'/'sample.prj').write_text('x', encoding='utf-8')
cleanup_evidence_backup(tmp_path)
assert not backup.exists()
def test_activity_deadline_is_extended_by_progress(monkeypatch):
now = [100.0]
monkeypatch.setattr('cbb_refresh_verify.mentor_adapter.time.monotonic', lambda: now[0])
deadline = ActivityDeadline(30)
assert not deadline.expired()
now[0] = 120.0
deadline.touch()
now[0] = 129.9
assert not deadline.expired()
assert deadline.remaining() == pytest.approx(20.1, abs=0.1)
now[0] = 149.9
assert not deadline.expired()
now[0] = 150.1
assert deadline.expired()
def test_refresh_integration_stops_on_new_pcb_error_before_action():
pi = FakeProjectIntegration()
with pytest.raises(IntegrationError, match='Job Preferences DB'):
refresh_integration(pi, error_reader=lambda: 'ERROR: Could not load Job Preferences DB')
assert pi.forward_calls == 0
class GreenProjectIntegration:
ForwardAnnotationStatus = 2
SynchCESStatus = 2
LoadCESStatus = 2
BackAnnotationStatus = 2
IsForwardAnnotationAllowed = True
IsSynchCESAllowed = True
IsLoadCESAllowed = True
IsBackAnnotationAllowed = True
def __init__(self):
self.actions = []
def ForwardAnnotate(self):
self.actions.append('ForwardAnnotate')
return True
def SynchCES(self):
self.actions.append('SynchCES')
return True
def LoadCES(self):
self.actions.append('LoadCES')
return True
def BackAnnotate(self):
self.actions.append('BackAnnotate')
return True
def test_refresh_integration_only_refreshes_first_action_when_already_green():
pi = GreenProjectIntegration()
events = []
assert refresh_integration(pi, settle_seconds=0, emit=lambda **e: events.append(e)) == {
'ForwardAnnotation': 2,
'SynchCES': 2,
'LoadCES': 2,
'BackAnnotation': 2,
}
assert pi.actions == ['ForwardAnnotate']
assert [e['action'] for e in events if e['stage'] == 'integration_action'] == pi.actions
def test_refresh_integration_waits_for_action_to_turn_green_before_next_action():
class PendingProjectIntegration(GreenProjectIntegration):
def ForwardAnnotate(self):
super().ForwardAnnotate()
self.ForwardAnnotationStatus = 1
return True
pi = PendingProjectIntegration()
waits = []
def complete_pending_action(_seconds):
assert pi.actions == ['ForwardAnnotate']
waits.append(True)
pi.ForwardAnnotationStatus = 2
refresh_integration(pi, settle_seconds=0, sleep=complete_pending_action)
assert waits
assert pi.actions == ['ForwardAnnotate']
@pytest.mark.parametrize('failure', ['not_allowed', 'returned_false', 'new_error'])
def test_refresh_integration_never_accepts_initial_green_when_refresh_fails(failure):
pi = GreenProjectIntegration()
if failure == 'not_allowed':
pi.ForwardAnnotationStatus = 1
pi.IsForwardAnnotationAllowed = False
elif failure == 'returned_false':
pi.ForwardAnnotate = lambda: False
with pytest.raises(IntegrationError):
refresh_integration(
pi, settle_seconds=0,
error_reader=lambda: 'refresh error' if failure == 'new_error' and pi.actions else '',
)
assert 'SynchCES' not in pi.actions
def test_refresh_integration_attempts_disabled_green_action_once():
pi = GreenProjectIntegration()
pi.IsForwardAnnotationAllowed = False
refresh_integration(pi, settle_seconds=0)
assert pi.actions == ['ForwardAnnotate']
def test_refresh_integration_never_counts_rejected_green_action_as_completed():
class VerifiedProjectIntegration(GreenProjectIntegration):
def _blocked(self, action):
self.actions.append(action)
raise RuntimeError(
f'{action} is not allowed on verified (or once verified) Reusable Blocks.')
def ForwardAnnotate(self): return self._blocked('ForwardAnnotate')
def SynchCES(self): return self._blocked('SynchCES')
def LoadCES(self): return self._blocked('LoadCES')
def BackAnnotate(self): return self._blocked('BackAnnotate')
pi = VerifiedProjectIntegration()
events = []
with pytest.raises(IntegrationError, match='not allowed on verified'):
refresh_integration(pi, settle_seconds=0, emit=lambda **e: events.append(e))
assert pi.actions == ['ForwardAnnotate']
assert not any(e['stage'] == 'integration_complete' for e in events)
def test_refresh_integration_does_not_retry_rejected_action_after_status_changes():
class VerifiedAfterFirstAction(GreenProjectIntegration):
def ForwardAnnotate(self):
self.actions.append('ForwardAnnotate')
self.BackAnnotationStatus = 1
return True
def BackAnnotate(self):
self.actions.append('BackAnnotate')
raise RuntimeError('Back Annotation is not allowed on verified (or once verified) Reusable Blocks.')
pi = VerifiedAfterFirstAction()
with pytest.raises(IntegrationError, match='not allowed on verified'):
refresh_integration(pi, settle_seconds=0, timeout_seconds=None)
assert pi.actions == ['ForwardAnnotate', 'BackAnnotate']
def test_refresh_integration_waits_for_real_state_change_without_internal_timeout():
class SlowProjectIntegration(GreenProjectIntegration):
SynchCESStatus = 2
LoadCESStatus = 2
BackAnnotationStatus = 2
IsForwardAnnotationAllowed = True
def __init__(self):
super().__init__()
self.reads = 0
self.forward_calls = 0
@property
def ForwardAnnotationStatus(self):
self.reads += 1
return 2 if self.reads >= 6 else 1
def ForwardAnnotate(self):
self.forward_calls += 1
return True
pi = SlowProjectIntegration()
result = refresh_integration(pi, settle_seconds=0, timeout_seconds=None,
sleep=lambda _seconds: None)
assert result['ForwardAnnotation'] == 2
assert pi.forward_calls == 1
def test_pcb_log_reports_only_new_integration_errors(tmp_path):
pcb = tmp_path / 'Work' / 'PCB' / 'sample.pcb'
log = pcb.parent / 'LogFiles' / 'ForwardAnnotation.txt'
log.parent.mkdir(parents=True)
log.write_text('No errors in Existing Schematic Packaging.\n', encoding='utf-8')
offset = log.stat().st_size
assert pcb_log_reports_integration_error(pcb, offsets={log: offset}) == ''
with log.open('a', encoding='utf-8') as stream:
stream.write('ERROR: Could not load Job Preferences DB\n')
stream.write('ERROR: Unable to create local Cell Library.\n')
stream.write('DataBase Load is being terminated with 2 errors and 0 warnings.\n')
detail = pcb_log_reports_integration_error(pcb, offsets={log: offset})
assert 'Job Preferences DB' in detail
assert 'local Cell Library' in detail
def test_pcb_log_ignores_nonfatal_packager_compatibility_warnings(tmp_path):
pcb = tmp_path / 'Work' / 'PCB' / 'sample.pcb'
log = pcb.parent / 'LogFiles' / 'PartPkg.log'
log.parent.mkdir(parents=True)
log.write_text(
'Unable to determine the Disable Repackage status.\n'
'Unable to successfully read the Property Definition Editor data.\n'
'No errors found. Proceeding with packaging...\n'
'Packager finished successfully.\n'
'!THE iCDB IS UP-TO-DATE!\n',
encoding='utf-8',
)
assert pcb_log_reports_integration_error(pcb, offsets={log: 0}) == ''
def test_pcb_log_reports_rewritten_same_size_log(tmp_path):
pcb = tmp_path / 'Work' / 'PCB' / 'sample.pcb'
log = pcb.parent / 'LogFiles' / 'ForwardAnnotation.txt'
log.parent.mkdir(parents=True)
old = 'No errors in Existing Schematic Packaging..\n'
log.write_text(old, encoding='utf-8')
baseline = {
'size': log.stat().st_size,
'mtime_ns': log.stat().st_mtime_ns,
'digest': hashlib.sha256(log.read_bytes()).hexdigest(),
}
new = 'ERROR: Unable to create local Cell Library.\n'
assert len(new.encode('utf-8')) == len(old.encode('utf-8'))
log.write_text(new, encoding='utf-8')
detail = pcb_log_reports_integration_error(pcb, offsets={log: baseline})
assert 'local Cell Library' in detail
def test_ensure_pcb_central_library_rewrites_stale_mapped_path(tmp_path):
pcb = tmp_path / 'Work' / 'PCB' / 'sample.pcb'
pcb.parent.mkdir(parents=True)
project = pcb.parent / 'pcb.prj'
project.write_text(
'KEY CentralLibrary "S:\\mentor_lib.lmc"\n'
'KEY CentralLibrary "S:\\mentor_lib.lmc"\n',
encoding='utf-8',
)
lmc = tmp_path / 'mentor_lib.lmc'
lmc.write_text('', encoding='utf-8')
evidence = tmp_path / 'evidence'
changed = ensure_pcb_central_library(pcb, lmc, evidence_dir=evidence)
assert changed is True
relative_lmc = os.path.relpath(lmc, project.parent).replace('/', '\\')
assert project.read_text(encoding='utf-8').count(relative_lmc) == 2
assert (evidence / 'pcb.prj.before-central-library').is_file()
def test_save_log_core_markers_allow_quit_recovery():
assert save_log_has_core_markers(
'LICENSE_OK\nSAVE_OK\nIS_SAVED\nPOST_SAVE_SYNCHRONIZED\nCLOSE_OK\n')
assert not save_log_has_core_markers('LICENSE_OK\nSAVE_OK\nIS_SAVED\n')
def test_backup_command_excludes_volatile_logs_and_databases(tmp_path):
command = build_backup_command(tmp_path/'source', tmp_path/'backup')
assert '/XD' in command and 'database' in command and 'logfiles' in command
assert '/XF' in command and '*.log' in command and '*.lck' in command
def test_backup_timeout_is_non_blocking_and_reported(tmp_path, monkeypatch):
source = tmp_path/'source'
source.mkdir()
terminated = []
class HangingProcess:
returncode = None
def wait(self, timeout):
raise __import__('subprocess').TimeoutExpired('robocopy', timeout)
import cbb_refresh_verify.mentor_adapter as adapter
monkeypatch.setattr(adapter.subprocess, 'Popen', lambda *args, **kwargs: HangingProcess())
monkeypatch.setattr(adapter, '_terminate', lambda process, **kwargs: terminated.append(process))
result = best_effort_backup(source, tmp_path/'backup', timeout_seconds=.1)
assert result['status'] == 'TIMEOUT'
assert terminated
def test_backup_timeout_scales_with_workload_and_is_independent_of_verify_timeout(tmp_path):
source = tmp_path/'source'
source.mkdir()
(source/'small.bin').write_bytes(b'x' * (1 * 1024 * 1024))
small = backup_timeout_seconds(source, verify_timeout_seconds=30)
large = tmp_path/'large'
large.mkdir()
for index in range(1200):
(large/f'{index:04d}.bin').write_bytes(b'x' * (64 * 1024))
large_budget = backup_timeout_seconds(large, verify_timeout_seconds=30)
assert small >= 3
assert large_budget > small
assert large_budget <= 30
assert backup_timeout_seconds(source, verify_timeout_seconds=1800) == small
def test_backup_timeout_falls_back_to_minimum_for_unreadable_source(tmp_path):
missing = tmp_path/'missing'
assert backup_timeout_seconds(missing, verify_timeout_seconds=30) == 3
def test_backup_timeout_ignores_volatile_directories_excluded_from_copy(tmp_path):
source = tmp_path/'source'
(source/'stable').mkdir(parents=True)
(source/'logfiles').mkdir()
(source/'stable'/'small.bin').write_bytes(b'x')
for index in range(1500):
(source/'logfiles'/f'{index:04d}.bin').write_bytes(b'x' * 1024)
budget = backup_timeout_seconds(source)
assert budget == pytest.approx(3.003)
def test_backup_timeout_uses_bounded_kill_budget(tmp_path, monkeypatch):
source = tmp_path/'source'
source.mkdir()
observed = {}
class HangingProcess:
returncode = None
def wait(self, timeout):
raise __import__('subprocess').TimeoutExpired('robocopy', timeout)
import cbb_refresh_verify.mentor_adapter as adapter
monkeypatch.setattr(adapter.subprocess, 'Popen', lambda *args, **kwargs: HangingProcess())
def terminate(process, **kwargs):
observed.update(kwargs)
monkeypatch.setattr(adapter, '_terminate', terminate)
result = best_effort_backup(source, tmp_path/'backup', timeout_seconds=3)
assert result['status'] == 'TIMEOUT'
assert observed['grace_seconds'] == 1
assert observed['kill_timeout_seconds'] <= 5
def test_network_backed_path_detects_unc_and_matching_mapped_drive(tmp_path):
assert is_network_backed_path(r'\\server\share\CBB', mapped_drive='Z:')
assert is_network_backed_path(r'Z:\CBB', mapped_drive='Z:')
assert not is_network_backed_path(tmp_path / 'CBB', mapped_drive='Z:')
def test_green_refresh_only_runs_newly_required_actions():
class NeedsBackAnnotation(GreenProjectIntegration):
def ForwardAnnotate(self):
super().ForwardAnnotate()
self.BackAnnotationStatus = 1
return True
def BackAnnotate(self):
super().BackAnnotate()
self.BackAnnotationStatus = 2
return True
pi = NeedsBackAnnotation()
result = refresh_integration(pi, settle_seconds=0)
assert pi.actions == ['ForwardAnnotate', 'BackAnnotate']
assert set(result.values()) == {2}
def test_initial_required_keeps_existing_full_sequence():
class Required(GreenProjectIntegration):
ForwardAnnotationStatus = 1
def ForwardAnnotate(self):
super().ForwardAnnotate()
self.ForwardAnnotationStatus = 2
return True
pi = Required()
refresh_integration(pi, settle_seconds=0)
assert pi.actions == ['ForwardAnnotate', 'SynchCES', 'LoadCES', 'BackAnnotate']
def test_integration_times_actual_call_and_completion_without_wall_clock():
now = [100.0]
events = []
class SlowForward(GreenProjectIntegration):
def ForwardAnnotate(self):
super().ForwardAnnotate()
now[0] += 341
return True
refresh_integration(SlowForward(), settle_seconds=0, clock=lambda: now[0],
emit=lambda **e: events.append(e))
complete = next(e for e in events if e['stage'] == 'integration_action_complete')
assert complete['elapsed_seconds'] == 341
assert complete['call_elapsed_seconds'] == 341
assert len([e for e in events if e['stage'] == 'integration_status']) == 1
+401
View File
@@ -0,0 +1,401 @@
from pathlib import Path
from cbb_refresh_verify.library_reader import read_library
class Obj:
def __init__(self, **kw): self.__dict__.update(kw)
def fake_dispatch(_):
class Collection:
def __init__(self, values): self.values=values; self.Count=len(values)
def Item(self, index): return self.values[index-1]
blocks = Collection([Obj(Name='Z_CBB', PartitionName='LP'), Obj(Name='A_CBB', PartitionName='LP')])
blocks2 = Collection([])
partitions = Collection([blocks, blocks2])
return Obj(OpenLibrary=lambda _: Obj(Partitions=lambda kind: partitions))
def test_reader_filters_and_sorts_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():
result = read_library(Path('fixture.lmc'), dispatch=lambda _: (_ for _ in ()).throw(RuntimeError('DMS')))
assert result.records == () and 'DMS' in result.error
def test_reader_accepts_com_collections_exposing_callable_count():
class Collection:
def __init__(self, values): self.values = values
def Count(self): return len(self.values)
def Item(self, index): return self.values[index - 1]
blocks = Collection([Obj(Name='CALLABLE_CBB', PartitionName='LP')])
partitions = Collection([blocks])
dispatch = lambda _: Obj(OpenLibrary=lambda _: Obj(Partitions=lambda kind: partitions))
result = read_library(Path('fixture.lmc'), dispatch=dispatch)
assert [record.name for record in result.records] == ['CALLABLE_CBB']
def test_reader_fast_scans_reusable_blocks_without_com(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
(tmp_path / 'ReusableBlocksLP' / 'B_CBB').mkdir(parents=True)
(tmp_path / 'ReusableBlocksLP' / 'A_CBB').mkdir()
from cbb_refresh_verify.library_reader import read_library_fast
result = read_library_fast(lmc)
assert [item.name for item in result.records] == ['A_CBB', 'B_CBB']
assert all(item.status == 'UNKNOWN' for item in result.records)
def test_reader_fast_applies_status_reader(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
(tmp_path / 'ReusableBlocksLP' / 'READY_CBB').mkdir(parents=True)
from cbb_refresh_verify.library_reader import read_library_fast
result = read_library_fast(lmc, status_reader=lambda name: 'READY' if name == 'READY_CBB' else 'PENDING')
assert result.records[0].status == 'READY'
def test_reader_fast_bulk_status_reader_is_called_once(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
(tmp_path / 'ReusableBlocksLP' / 'A_CBB').mkdir(parents=True)
(tmp_path / 'ReusableBlocksLP' / 'B_CBB').mkdir()
calls = []
from cbb_refresh_verify.library_reader import read_library_fast
def status_reader(path, names):
calls.append((path, names))
return {'A_CBB': 'READY', 'B_CBB': 'PENDING'}
result = read_library_fast(lmc, status_reader=status_reader)
assert len(calls) == 1
assert [record.status for record in result.records] == ['READY', 'PENDING']
def test_reader_fast_preserves_unavailable_bridge_status(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
(tmp_path / 'ReusableBlocksLP' / 'A_CBB').mkdir(parents=True)
from cbb_refresh_verify.library_reader import read_library_fast
result = read_library_fast(lmc, status_reader=lambda path, names: {'A_CBB': 'UNAVAILABLE'})
assert result.records[0].status == 'UNAVAILABLE'
def test_reader_fast_exposes_status_reader_failure_as_unavailable(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
(tmp_path / 'ReusableBlocksLP' / 'A_CBB').mkdir(parents=True)
from cbb_refresh_verify.library_reader import read_library_fast
result = read_library_fast(lmc, status_reader=lambda path, names: (_ for _ in ()).throw(RuntimeError('bridge down')))
assert result.records[0].status == 'UNAVAILABLE'
def test_filesystem_status_uses_complete_fresh_cert_artifacts(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
root = tmp_path / 'ReusableBlocksLP'
ready = root / 'READY_CBB' / 'Work'
pending = root / 'PENDING_CBB' / 'Work'
for work, name in ((ready, 'READY_CBB'), (pending, 'PENDING_CBB')):
(work / 'PCB' / 'Layout').mkdir(parents=True)
(work / f'{name}.prj').write_text('KEY PCBDesignPath "PCB\\actual.pcb"', encoding='utf-8')
(work / 'PCB' / 'actual.pcb').write_text('pcb', encoding='utf-8')
(work / 'PCB' / 'Layout' / 'LayoutDB.lyt').write_bytes(b'lyt')
cert = root / 'READY_CBB' / 'Cert'
(cert / 'PCB' / 'Layout').mkdir(parents=True)
(cert / 'READY_CBB.prj').write_text('cert', encoding='utf-8')
(cert / 'PCB' / 'actual.pcb').write_text('cert pcb', encoding='utf-8')
(cert / 'PCB' / 'Layout' / 'LayoutDB.lyt').write_bytes(b'cert lyt')
from cbb_refresh_verify.library_reader import read_library_fast, filesystem_status_map
statuses = filesystem_status_map(lmc, ('READY_CBB', 'PENDING_CBB'))
assert statuses == {'READY_CBB': 'READY', 'PENDING_CBB': 'PENDING'}
result = read_library_fast(lmc, status_reader=filesystem_status_map)
assert [record.status for record in result.records] == ['PENDING', 'READY']
def test_reconcile_statuses_uses_persisted_pending_when_tree_is_unavailable():
from cbb_refresh_verify.library_reader import reconcile_statuses
result = reconcile_statuses(
{'A': 'UNKNOWN', 'B': 'READY'},
{'A': 'PENDING', 'B': 'UNKNOWN'},
('A', 'B'),
)
assert result == {'A': 'PENDING', 'B': 'READY'}
def test_reconcile_statuses_prefers_calibrated_tree_sources_on_conflict():
from cbb_refresh_verify.library_reader import reconcile_statuses
result = reconcile_statuses(
{'A': 'READY', 'B': 'PENDING'},
{'A': 'PENDING', 'B': 'READY'},
('A', 'B'),
)
assert result == {'A': 'READY', 'B': 'PENDING'}
def test_reconcile_statuses_keeps_matching_sources():
from cbb_refresh_verify.library_reader import reconcile_statuses
assert reconcile_statuses({'A': 'READY'}, {'A': 'READY'}, ('A',)) == {'A': 'READY'}
def test_context_menu_status_parser_is_removed():
import cbb_refresh_verify.library_reader as reader
assert not hasattr(reader, 'status_from_context_menu')
def test_reconcile_uses_persisted_ready_when_tree_id_is_unavailable():
from cbb_refresh_verify.library_reader import reconcile_statuses
assert reconcile_statuses({'A': 'UNKNOWN'}, {'A': 'READY'}, ('A',)) == {'A': 'READY'}
assert reconcile_statuses({'A': 'READY'}, {'A': 'UNKNOWN'}, ('A',)) == {'A': 'READY'}
def test_reconcile_prefers_calibrated_tree_id_over_stale_persisted_status():
from cbb_refresh_verify.library_reader import reconcile_statuses
assert reconcile_statuses({'A': 'PENDING'}, {'A': 'READY'}, ('A',)) == {'A': 'PENDING'}
def test_tree_image_status_is_calibrated_from_filesystem_evidence():
from cbb_refresh_verify.library_reader import infer_tree_statuses
result = infer_tree_statuses(
{'A': 11, 'B': 11, 'C': 12},
{'A': 'PENDING', 'B': 'PENDING', 'C': 'READY'},
('A', 'B', 'C'),
)
assert result == {'A': 'PENDING', 'B': 'PENDING', 'C': 'READY'}
def test_image_status_map_is_derived_from_current_ids_not_fixed_indices():
from cbb_refresh_verify.library_reader import infer_image_status_map
assert infer_image_status_map(
{'A': 401, 'B': 902},
{'A': 'READY', 'B': 'PENDING'},
('A', 'B'),
) == {401: 'READY', 902: 'PENDING'}
assert infer_image_status_map(
{'A': 401, 'B': 401},
{'A': 'READY', 'B': 'PENDING'},
('A', 'B'),
) == {401: 'PENDING'}
def test_pending_id_overrides_stale_complete_cert_for_same_tree_icon():
from cbb_refresh_verify.library_reader import infer_tree_statuses, reconcile_statuses
tree = infer_tree_statuses(
{'PEF7071_PHY': 10, 'IP101GR': 10},
{'PEF7071_PHY': 'READY', 'IP101GR': 'PENDING'},
('PEF7071_PHY', 'IP101GR'),
)
assert tree == {'PEF7071_PHY': 'PENDING', 'IP101GR': 'PENDING'}
assert reconcile_statuses(tree, {'PEF7071_PHY': 'READY', 'IP101GR': 'PENDING'},
('PEF7071_PHY', 'IP101GR')) == {
'PEF7071_PHY': 'PENDING', 'IP101GR': 'PENDING'}
def test_unseen_tree_id_is_pending_when_ready_id_anchor_exists():
from cbb_refresh_verify.library_reader import infer_tree_statuses
assert infer_tree_statuses(
{'READY_CBB_1': 11, 'READY_CBB_2': 11, 'UNVERIFIED_CBB': 10},
{'READY_CBB_1': 'READY', 'READY_CBB_2': 'READY', 'UNVERIFIED_CBB': 'READY'},
('READY_CBB_1', 'READY_CBB_2', 'UNVERIFIED_CBB'),
) == {'READY_CBB_1': 'READY', 'READY_CBB_2': 'READY', 'UNVERIFIED_CBB': 'PENDING'}
def test_status_log_records_unseen_id_inference(caplog, monkeypatch, tmp_path):
import cbb_refresh_verify.library_reader as reader
caplog.set_level('INFO')
monkeypatch.setattr(reader, 'filesystem_evidence_map', lambda _library, names: {
name: {'status': 'READY', 'project_count': 1}
for name in names
})
result = reader.scan_open_library_status(
tmp_path / 'center.lmc',
('READY_CBB_1', 'READY_CBB_2', 'UNVERIFIED_CBB'),
tree_image_reader=lambda _library, _names: {'READY_CBB_1': 11, 'READY_CBB_2': 11, 'UNVERIFIED_CBB': 10},
)
assert result == {'READY_CBB_1': 'READY', 'READY_CBB_2': 'READY', 'UNVERIFIED_CBB': 'PENDING'}
assert 'unseen_tree_id_vs_ready_anchor' in caplog.text
def test_cached_ready_id_classifies_new_tree_id_as_pending(caplog, monkeypatch, tmp_path):
import json
import cbb_refresh_verify.library_reader as reader
caplog.set_level('INFO')
monkeypatch.setattr(reader, 'filesystem_evidence_map', lambda _library, names: {
name: {'status': 'READY', 'project_count': 1}
for name in names
})
store = tmp_path / 'image-map.json'
store.write_text(json.dumps({'schema_version': 2, 'image_status_map': {'11': 'READY'}}), encoding='utf-8')
result = reader.scan_open_library_status(
tmp_path / 'center.lmc',
('READY_CBB', 'UNVERIFIED_CBB'),
mapping_store=store,
tree_image_reader=lambda _library, _names: {'READY_CBB': 11, 'UNVERIFIED_CBB': 10},
)
assert result == {'READY_CBB': 'READY', 'UNVERIFIED_CBB': 'PENDING'}
assert 'cached_ready_anchor' in caplog.text
def test_cached_ready_id_is_not_downgraded_by_transient_pending_files(caplog, monkeypatch, tmp_path):
"""A post-Verify scan may see Cert files before they are fully written."""
import json
import cbb_refresh_verify.library_reader as reader
caplog.set_level('INFO')
monkeypatch.setattr(reader, 'filesystem_evidence_map', lambda _library, names: {
name: {'status': 'PENDING', 'project_count': 1}
for name in names
})
store = tmp_path / 'image-map.json'
store.write_text(json.dumps({'schema_version': 2, 'image_status_map': {'11': 'READY'}}), encoding='utf-8')
result = reader.scan_open_library_status(
tmp_path / 'center.lmc',
('VERIFIED_CBB',),
mapping_store=store,
tree_image_reader=lambda _library, _names: {'VERIFIED_CBB': 11},
)
assert result == {'VERIFIED_CBB': 'READY'}
assert 'cached_image_id_authoritative' in caplog.text
def test_verified_id_transition_uses_cached_ready_anchor(caplog, monkeypatch, tmp_path):
"""After Verify, a stale file snapshot must not downgrade the new ID."""
import json
import cbb_refresh_verify.library_reader as reader
caplog.set_level('INFO')
monkeypatch.setattr(reader, 'filesystem_evidence_map', lambda _library, names: {
name: {'status': 'PENDING', 'project_count': 1}
for name in names
})
store = tmp_path / 'image-map.json'
store.write_text(json.dumps({'schema_version': 2, 'image_status_map': {'10': 'PENDING', '11': 'READY'}}), encoding='utf-8')
result = reader.scan_open_library_status(
tmp_path / 'center.lmc',
('VERIFIED_CBB',),
mapping_store=store,
tree_image_reader=lambda _library, _names: {'VERIFIED_CBB': 11},
)
assert result == {'VERIFIED_CBB': 'READY'}
assert 'cached_image_id_authoritative' in caplog.text
def test_legacy_unversioned_image_cache_is_ignored(monkeypatch, tmp_path):
import json
import cbb_refresh_verify.library_reader as reader
monkeypatch.setattr(reader, 'filesystem_evidence_map', lambda _library, names: {
name: {'status': 'PENDING', 'project_count': 1}
for name in names
})
store = tmp_path / 'image-map.json'
store.write_text(json.dumps({'image_status_map': {'11': 'READY'}}), encoding='utf-8')
result = reader.scan_open_library_status(
tmp_path / 'center.lmc', ('CBB',), mapping_store=store,
tree_image_reader=lambda _library, _names: {'CBB': 11},
)
assert result == {'CBB': 'PENDING'}
def test_no_hardcoded_green_image_index_is_exposed():
import cbb_refresh_verify.library_reader as reader
import cbb_refresh_verify.mentor_adapter as adapter
assert not hasattr(reader, 'READY_IMAGE_INDEX')
assert not hasattr(adapter, 'GREEN_TREE_IMAGE_INDEX')
def test_unanchored_tree_image_is_unknown_instead_of_guessing():
from cbb_refresh_verify.library_reader import infer_tree_statuses
assert infer_tree_statuses({'A': 11}, {'A': 'UNKNOWN'}, ('A',)) == {'A': 'UNKNOWN'}
def test_unanchored_tree_image_is_not_calibrated_without_persisted_status():
from cbb_refresh_verify.library_reader import infer_tree_statuses
result = infer_tree_statuses(
{'A': 27, 'B': 27},
{'A': 'UNKNOWN', 'B': 'UNKNOWN'},
('A', 'B'),
)
assert result == {'A': 'UNKNOWN', 'B': 'UNKNOWN'}
def test_status_scan_logs_each_cbb_image_id(caplog, tmp_path):
from cbb_refresh_verify.library_reader import scan_open_library_status
caplog.set_level('INFO')
result = scan_open_library_status(
tmp_path / 'center.lmc',
('A', 'B'),
tree_image_reader=lambda _library, _names: {'A': 27, 'B': 28},
)
assert set(result) == {'A', 'B'}
assert 'name=A image_id=27' in caplog.text
assert 'name=B image_id=28' in caplog.text
def test_status_scan_keeps_only_missing_cert_or_project_items_pending(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
root = lmc.parent / 'ReusableBlocksLP'
ready = root / 'READY_CBB' / 'Work'
(ready / 'PCB' / 'Layout').mkdir(parents=True)
(ready / 'READY_CBB.prj').write_text('KEY PCBDesignPath "PCB\\actual.pcb"', encoding='utf-8')
(ready / 'PCB' / 'actual.pcb').write_text('pcb', encoding='utf-8')
(ready / 'PCB' / 'Layout' / 'LayoutDB.lyt').write_bytes(b'lyt')
cert = ready.parent / 'Cert'
(cert / 'PCB' / 'Layout').mkdir(parents=True)
(cert / 'READY_CBB.prj').write_text('cert', encoding='utf-8')
(cert / 'PCB' / 'actual.pcb').write_text('cert pcb', encoding='utf-8')
(cert / 'PCB' / 'Layout' / 'LayoutDB.lyt').write_bytes(b'cert lyt')
pending = root / 'IP101GR' / 'Work'
(pending / 'PCB' / 'Layout').mkdir(parents=True)
(pending / 'IP101GR.prj').write_text('KEY PCBDesignPath "PCB\\actual.pcb"', encoding='utf-8')
(pending / 'PCB' / 'actual.pcb').write_text('pcb', encoding='utf-8')
(pending / 'PCB' / 'Layout' / 'LayoutDB.lyt').write_bytes(b'lyt')
from cbb_refresh_verify.library_reader import scan_open_library_status
result = scan_open_library_status(
lmc,
('READY_CBB', 'IP101GR', 'MISSING_CBB'),
tree_image_reader=lambda _library, _names: {},
)
assert result == {'READY_CBB': 'READY', 'IP101GR': 'PENDING', 'MISSING_CBB': 'PENDING'}
def test_filesystem_evidence_exposes_multiple_persistent_dimensions(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
work = tmp_path / 'ReusableBlocksLP' / 'A_CBB' / 'Work'
(work / 'PCB' / 'Layout').mkdir(parents=True)
(work / 'A_CBB.prj').write_text('KEY PCBDesignPath "PCB\\actual.pcb"', encoding='utf-8')
(work / 'PCB' / 'actual.pcb').write_text('pcb', encoding='utf-8')
(work / 'PCB' / 'Layout' / 'LayoutDB.lyt').write_bytes(b'lyt')
cert = work.parent / 'Cert'
(cert / 'PCB' / 'Layout').mkdir(parents=True)
(cert / 'A_CBB.prj').write_text('cert', encoding='utf-8')
(cert / 'PCB' / 'actual.pcb').write_text('cert pcb', encoding='utf-8')
(cert / 'PCB' / 'Layout' / 'LayoutDB.lyt').write_bytes(b'cert lyt')
from cbb_refresh_verify.library_reader import filesystem_evidence_map
evidence = filesystem_evidence_map(lmc, ('A_CBB',))['A_CBB']
assert evidence['status'] == 'READY'
assert all(evidence[key] for key in (
'work_project', 'work_pcb', 'work_layout',
'cert_project', 'cert_pcb', 'cert_layout'))
def test_filesystem_evidence_preserves_mapped_drive_paths(tmp_path, monkeypatch):
"""Legacy evidence scanning must not resolve a mapped drive back to UNC."""
lmc = tmp_path / 'center.lmc'
lmc.touch()
work = tmp_path / 'ReusableBlocksLP' / 'A_CBB' / 'Work'
(work / 'PCB' / 'Layout').mkdir(parents=True)
(work / 'A_CBB.prj').write_text('KEY PCBDesignPath "PCB\\actual.pcb"', encoding='utf-8')
(work / 'PCB' / 'actual.pcb').write_text('pcb', encoding='utf-8')
(work / 'PCB' / 'Layout' / 'LayoutDB.lyt').write_bytes(b'lyt')
cert = work.parent / 'Cert'
(cert / 'PCB' / 'Layout').mkdir(parents=True)
(cert / 'A_CBB.prj').write_text('cert', encoding='utf-8')
(cert / 'PCB' / 'actual.pcb').write_text('cert pcb', encoding='utf-8')
(cert / 'PCB' / 'Layout' / 'LayoutDB.lyt').write_bytes(b'cert lyt')
monkeypatch.setattr(Path, 'resolve', lambda self: pytest.fail('mapped path was resolved'))
from cbb_refresh_verify.library_reader import filesystem_evidence_map
assert filesystem_evidence_map(lmc, ('A_CBB',))['A_CBB']['status'] == 'READY'
def test_missing_work_project_is_a_pending_calibration_anchor(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
(tmp_path / 'ReusableBlocksLP' / 'IMPORTED_CBB').mkdir(parents=True)
from cbb_refresh_verify.library_reader import filesystem_evidence_map
evidence = filesystem_evidence_map(lmc, ('IMPORTED_CBB',))['IMPORTED_CBB']
assert evidence['project_count'] == 0
assert evidence['status'] == 'PENDING'
+36
View File
@@ -0,0 +1,36 @@
from pathlib import Path
from cbb_refresh_verify.mentor_paths import discover_sdd_home
def _install(root: Path):
sdd = root / 'Mentor' / '7.9.5EE' / 'SDD_HOME'
for relative in (
'lm/win32/bin/LibraryManager.exe',
'lm/win32/bin/ReuseBlockImporter.exe',
'common/win32/bin/ExpeditionPCB.exe',
):
path = sdd / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b'fixture')
return sdd
def test_discover_sdd_home_finds_common_mentor_layout(tmp_path):
expected = _install(tmp_path)
assert discover_sdd_home(environ={}, search_roots=(tmp_path,)) == expected
def test_discover_sdd_home_prefers_explicit_installation(tmp_path):
expected = _install(tmp_path / 'explicit')
_install(tmp_path / 'other')
assert discover_sdd_home(str(expected / 'lm' / 'win32' / 'bin'), environ={},
search_roots=(tmp_path / 'other', tmp_path / 'explicit')) == expected
def test_discover_sdd_home_returns_none_without_known_mentor_binaries(tmp_path):
(tmp_path / 'Mentor' / '7.9.5EE' / 'SDD_HOME').mkdir(parents=True)
assert discover_sdd_home(environ={}, search_roots=(tmp_path,)) is None
+146
View File
@@ -0,0 +1,146 @@
from pathlib import Path
import pytest
from cbb_refresh_verify.network_path import (
LibraryPathLease,
NetworkPathError,
ensure_mapped_drive_visible,
select_library_file,
)
class FakeWNet:
def __init__(self, *, existing=None, used=None):
self.existing = dict(existing or {})
self.used = set(used or self.existing)
self.added = []
self.cancelled = []
def mappings(self):
return dict(self.existing)
def used_drives(self):
return set(self.used)
def add_mapping(self, drive, remote):
self.added.append((drive, remote))
self.existing[drive] = remote
self.used.add(drive)
def cancel_mapping(self, drive):
self.cancelled.append(drive)
self.existing.pop(drive, None)
self.used.discard(drive)
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 lease.created is False
assert backend.added == []
assert backend.cancelled == []
def test_created_mapping_is_released():
backend = FakeWNet(used={"Z:"})
lease = LibraryPathLease.acquire(
r"\\server\share\lib\mentor_lib.lmc", backend=backend
)
assert lease.drive == "Y:"
assert backend.added == [("Y:", r"\\server\share")]
lease.close()
assert backend.cancelled == ["Y:"]
def test_created_mapping_is_not_removed_after_external_retarget():
backend = FakeWNet()
lease = LibraryPathLease.acquire(
r"\\server\share\lib\mentor_lib.lmc", backend=backend
)
backend.existing[lease.drive] = r"\\other\share"
lease.close()
assert backend.cancelled == []
def test_local_path_does_not_touch_wnet(tmp_path):
backend = FakeWNet()
lmc = tmp_path / "mentor_lib.lmc"
with LibraryPathLease.acquire(lmc, backend=backend) as lease:
assert lease.mentor_path == lmc
assert backend.added == []
assert backend.cancelled == []
def test_mapped_drive_records_remote_root_without_rebinding(tmp_path):
backend = FakeWNet(existing={"S:": r"\\server\share"})
lease = LibraryPathLease.acquire(
Path(r"S:\mentor_lib.lmc"), backend=backend
)
assert lease.drive == "S:"
assert lease.remote_root == r"\\server\share"
assert lease.created is False
assert backend.added == []
def test_worker_mapping_is_recreated_when_child_cannot_see_drive():
backend = FakeWNet()
result = ensure_mapped_drive_visible(
"S:", r"\\server\share", backend=backend
)
assert result == {"drive": "S:", "remote_root": r"\\server\share", "created": True}
assert backend.added == [("S:", r"\\server\share")]
def test_worker_mapping_rejects_conflicting_drive():
backend = FakeWNet(existing={"S:": r"\\other\share"})
with pytest.raises(NetworkPathError, match="映射冲突"):
ensure_mapped_drive_visible("S:", r"\\server\share", backend=backend)
def test_forward_slash_unc_is_normalized_and_mapped():
backend = FakeWNet()
lease = LibraryPathLease.acquire(
'//server/share/lib/mentor_lib.lmc', backend=backend
)
assert lease.remote_root == r'\\server\share'
assert lease.mentor_path == Path(r'Z:\lib\mentor_lib.lmc')
lease.close()
def test_single_leading_backslash_is_rejected_as_malformed_unc():
with pytest.raises(NetworkPathError, match='两个反斜杠'):
LibraryPathLease.acquire(r'\192.168.0.252\eda\mentor_lib.lmc', backend=FakeWNet())
def test_library_directory_selects_its_only_lmc(tmp_path):
lmc = tmp_path / 'mentor_lib.lmc'
lmc.touch()
assert select_library_file(tmp_path) == lmc
def test_library_directory_rejects_ambiguous_lmc_files(tmp_path):
(tmp_path / 'one.lmc').touch()
(tmp_path / 'two.lmc').touch()
with pytest.raises(NetworkPathError, match='唯一'):
select_library_file(tmp_path)
+14
View File
@@ -0,0 +1,14 @@
from pathlib import Path
def test_spec_uses_onedir_collect_and_product_name():
text=Path('packaging/CbbRefreshVerify.spec').read_text(encoding='utf-8')
assert 'COLLECT(' in text and '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
def test_spec_packages_adaptive_dialog_rules_and_uia_modules():
text = Path('packaging/CbbRefreshVerify.spec').read_text(encoding='utf-8')
assert 'dialog_rules.v1.json' in text
assert 'pywinauto' in text
+77
View File
@@ -0,0 +1,77 @@
from pathlib import Path
import json
import subprocess
from cbb_refresh_verify.status_bridge import default_bridge_path
def test_packaged_layout_contains_status_bridge_asset():
spec = Path("packaging/CbbRefreshVerify.spec").read_text(encoding="utf-8")
assert "tools/status_bridge/bin" in spec
assert Path("tools/status_bridge/bin/CbbStatusBridge32.exe").is_file()
def test_packaged_layout_contains_read_only_verify_probe_asset():
spec = Path("packaging/CbbRefreshVerify.spec").read_text(encoding="utf-8")
assert "VerifyProbe32.exe" in spec
assert Path("tools/status_bridge/bin/VerifyProbe32.exe").is_file()
def test_frozen_bridge_lookup_includes_internal_onedir_root():
text = Path("src/cbb_refresh_verify/status_bridge.py").read_text(encoding="utf-8")
assert "_MEIPASS" in text
def test_default_bridge_path_does_not_claim_ready_without_bridge(tmp_path, monkeypatch):
monkeypatch.setenv("CBB_STATUS_BRIDGE", str(tmp_path / "missing.exe"))
path = default_bridge_path()
assert not path.exists()
def test_main_window_default_worker_count_is_one():
text = Path("src/cbb_refresh_verify/ui/main_window.py").read_text(encoding="utf-8")
assert "setMaxThreadCount(1)" in text
def test_main_window_defaults_to_authoritative_bridge_status():
text = Path("src/cbb_refresh_verify/ui/main_window.py").read_text(encoding="utf-8")
assert "authoritative_status=True" in text
def test_spec_keeps_dynamic_main_window_import_in_frozen_package():
spec = Path("packaging/CbbRefreshVerify.spec").read_text(encoding="utf-8")
assert "cbb_refresh_verify.ui.main_window" in spec
def test_main_window_module_imports_without_optional_replacement_package():
import os
import subprocess
import sys
env = os.environ.copy()
env["PYTHONPATH"] = str(Path("src").resolve())
result = subprocess.run(
[sys.executable, "-c", "import cbb_refresh_verify.ui.main_window"],
env=env, capture_output=True, text=True, timeout=15,
)
assert result.returncode == 0, result.stderr
def test_compiled_bridge_json_codec_round_trips_unc_path():
bridge = Path('tools/status_bridge/bin/CbbStatusBridge32.exe').resolve()
request = {
'request_id': 'codec-1',
'lmc_file': r'\\192.168.0.252\eda\Mentor_lib\mentor_lib.lmc',
'block_name': 'CBB_TEST',
}
result = subprocess.run(
[str(bridge), '--codec-test'],
input=json.dumps(request, ensure_ascii=False) + '\n',
capture_output=True,
text=True,
encoding='utf-8',
timeout=10,
)
assert result.returncode == 0, result.stdout + result.stderr
assert json.loads(result.stdout) == request
+91
View File
@@ -0,0 +1,91 @@
import pytest
from cbb_refresh_verify.pcb_bridge import (
PcbBridgeError,
execution_outcome,
require_document_identity,
wait_for_target_document,
)
class ProjectIntegration:
def __init__(self, project):
self.ProjectFile = str(project)
class Document:
def __init__(self, name, project):
self.Name = name
self.ProjectIntegration = ProjectIntegration(project)
class Application:
def __init__(self, document):
self.ActiveDocument = document
def job(tmp_path):
return {
'project': str(tmp_path / 'Work' / 'CBB.prj'),
'pcb': str(tmp_path / 'Work' / 'PCB' / 'CBB.pcb'),
}
def test_bridge_rejects_wrong_document_before_actions(tmp_path):
current = Document('OTHER.pcb', tmp_path / 'Work' / 'OTHER.prj')
with pytest.raises(PcbBridgeError, match='身份不符') as raised:
require_document_identity(current, job(tmp_path))
assert raised.value.error_code == 'PCB_IDENTITY_MISMATCH'
def test_bridge_attaches_through_com_without_window_title_gate(tmp_path):
expected = Document('CBB.pcb', tmp_path / 'Work' / 'CBB.prj')
attempts = iter((RuntimeError('not ready'), Application(expected)))
events = []
def provider():
value = next(attempts)
if isinstance(value, Exception):
raise value
return value
app, document, integration = wait_for_target_document(
job(tmp_path), provider, process_alive=lambda: True,
emit=lambda **event: events.append(event), sleep=lambda _seconds: None,
)
assert app.ActiveDocument is document
assert integration.ProjectFile.endswith('CBB.prj')
assert not any(event['stage'] == 'com_wait' for event in events)
assert events[-1]['stage'] == 'identity_verified'
def test_bridge_stops_if_pcb_exits_before_com_is_ready(tmp_path):
alive = iter((True, False))
with pytest.raises(PcbBridgeError) as raised:
wait_for_target_document(
job(tmp_path), lambda: (_ for _ in ()).throw(RuntimeError('not ready')),
process_alive=lambda: next(alive), sleep=lambda _seconds: None,
)
assert raised.value.error_code == 'PCB_EXITED_BEFORE_COM'
def test_fatal_dialog_overrides_successful_save_markers():
result = execution_outcome(
save_complete=True,
pcb_exited=True,
fatal_error='SAVE_REUSABLE_BLOCK_FAILED: Error saving the Reusable Block',
)
assert result['status'] == 'FAIL'
assert result['error_code'] == 'SAVE_REUSABLE_BLOCK_FAILED'
def test_success_requires_save_and_pcb_exit():
assert execution_outcome(save_complete=True, pcb_exited=True)['status'] == 'PASS'
assert execution_outcome(save_complete=False, pcb_exited=True)['status'] == 'FAIL'
assert execution_outcome(save_complete=True, pcb_exited=False)['status'] == 'FAIL'
+52
View File
@@ -0,0 +1,52 @@
from cbb_refresh_verify.post_verify_diagnostics import build_snapshot, invoke_with_evidence
def test_invoke_evidence_distinguishes_entering_from_returning():
events = []
def invoke():
assert events == [{'stage': 'verify_invoke', 'lm_pid': 100}]
invoke_with_evidence(invoke, events.append, {'lm_pid': 100})
assert events == [
{'stage': 'verify_invoke', 'lm_pid': 100},
{'stage': 'verify_invoke_returned', 'lm_pid': 100},
]
def test_invoke_failure_does_not_claim_returned():
events = []
def invoke():
raise RuntimeError('COM invocation failed')
try:
invoke_with_evidence(invoke, events.append, {'lm_pid': 100})
except RuntimeError:
pass
assert events == [{'stage': 'verify_invoke', 'lm_pid': 100}]
def test_snapshot_records_preexisting_and_rejected_pcb_processes():
processes = [
(20, 'ExpeditionPCB.exe', r'D:\Mentor\wg\ExpeditionPCB.exe',
r'D:\Mentor\wg\ExpeditionPCB.exe "F:\library\target.pcb" -ReusableCircuit'),
(21, 'exppcb.exe', r'D:\Mentor\wg\exppcb.exe',
r'D:\Mentor\wg\exppcb.exe "F:\library\target.pcb"'),
(22, 'ExpeditionPCB.exe', r'D:\Mentor\wg\ExpeditionPCB.exe',
r'D:\Mentor\wg\ExpeditionPCB.exe "F:\library\target.pcb" -ReusableCircuit'),
]
snapshot = build_snapshot(processes, [], r'F:\library\target.pcb', {20})
assert [(p['pid'], p['preexisting'], p['matches_current_filter'])
for p in snapshot['processes']] == [
(20, True, True), (21, False, False), (22, False, True),
]
def test_snapshot_keeps_lm_modal_details_without_changing_windows():
modal = {'pid': 100, 'hwnd': 9, 'class_name': '#32770',
'title': 'Confirm Verify', 'texts': ['OK', 'Cancel']}
snapshot = build_snapshot([], [modal], r'F:\library\target.pcb', set())
assert snapshot['windows'] == [modal]
+79
View File
@@ -0,0 +1,79 @@
import pytest
from cbb_refresh_verify.runtime_timing import RunTimings, parse_save_progress
def test_phase_duration_uses_worker_monotonic_time_not_delayed_poll_time():
now = [900.0]
timer = RunTimings(clock=lambda: now[0])
timer.record({'stage': 'pcb_launch', 'monotonic_seconds': 1000.0})
now[0] = 1600
timer.record({'stage': 'identity_verified', 'monotonic_seconds': 1132.0})
assert timer.snapshot()[0]['pcb_startup'] == 132.0
def test_action_and_save_subtimings_accumulate_real_durations():
timer = RunTimings(clock=lambda: 1000.0)
timer.record({'stage': 'integration_action_complete', 'action': 'ForwardAnnotate',
'elapsed_seconds': 341, 'call_elapsed_seconds': 336})
timer.record({'stage': 'integration_action_complete', 'action': 'BackAnnotate',
'elapsed_seconds': 4, 'call_elapsed_seconds': 3})
timer.record({'stage': 'save_progress', 'timings_seconds': {'save': 246, 'close': 3}})
durations, unfinished = timer.snapshot()
assert durations['forward_annotation'] == 341
assert durations['forward_annotation_call'] == 336
assert durations['back_annotation'] == 4
assert durations['save'] == 246
assert durations['close'] == 3
assert 'synch_ces' not in durations # skipped is not a zero-time measurement
def test_timeout_reports_unfinished_phase_without_fabricating_completion():
now = [10.0]
timer = RunTimings(clock=lambda: now[0])
timer.record({'stage': 'save_start', 'monotonic_seconds': 15})
now[0] = 45
durations, unfinished = timer.snapshot()
assert durations['save_close'] == 30
assert unfinished == ('save_close',)
assert 'save' not in durations
assert durations['total'] == 35
def test_save_helper_timing_parser_keeps_completion_markers():
result = parse_save_progress('SAVE_START\nTIMING|save|246.250\nSAVE_OK\nTIMING|close|3.125\nCLOSE_OK\n')
assert result == {'markers': ['SAVE_START', 'SAVE_OK', 'CLOSE_OK'],
'timings_seconds': {'save': 246.25, 'close': 3.125}}
@pytest.mark.parametrize('invalid', ['TIMING|save|NaN', 'TIMING|save|-1', 'TIMING|save|bad'])
def test_invalid_helper_timing_never_poison_result(invalid):
assert parse_save_progress(invalid)['timings_seconds'] == {}
def test_returned_but_rejected_save_is_not_reported_as_still_in_call():
now = [10.0]
timer = RunTimings(clock=lambda: now[0])
timer.record({'stage': 'save_progress', 'markers': ['SAVE_START'], 'monotonic_seconds': 12})
now[0] = 30
timer.record({'stage': 'save_progress', 'markers': ['SAVE_START'],
'timings_seconds': {'save': 5}})
durations, unfinished = timer.snapshot()
assert durations['save'] == 5
assert 'save' not in unfinished
def test_repeat_action_and_repeated_save_snapshot_do_not_double_count():
timer = RunTimings(clock=lambda: 1000.0)
for _ in range(2):
timer.record({'stage': 'integration_action_complete', 'action': 'ForwardAnnotate',
'elapsed_seconds': 10, 'call_elapsed_seconds': 8})
event = {'stage': 'save_progress', 'markers': ['SAVE_START', 'SAVE_OK'],
'timings_seconds': {'save': 30}}
timer.record(event)
timer.record(event)
values, unfinished = timer.snapshot()
assert values['forward_annotation'] == 20
assert values['forward_annotation_call'] == 16
assert values['save'] == 30
assert unfinished == ()
+112
View File
@@ -0,0 +1,112 @@
"""Production safeguards: no input injection, no desktop switching, no menu driving.
These asserts encode the operating rules for this tool: the user's mouse,
keyboard and desktop are never touched. Dialogs that belong to a process this
run started are answered with a posted BM_CLICK, which is a message to that
dialog and not user input.
"""
from pathlib import Path
SOURCE_ROOT = Path(__file__).resolve().parents[1]/'src'/'cbb_refresh_verify'
# Anything that moves the cursor, injects input, switches desktops, or drives
# the Library Manager menu/keyboard must never appear in production code.
FORBIDDEN_APIS = (
'mouse_event',
'SendInput',
'SetCursorPos',
'SwitchDesktop',
'click_input',
'SendKeys',
'keybd_event',
'SetForegroundWindow',
'SetActiveWindow',
'AttachThreadInput',
'WM_MOUSEMOVE',
'WM_CONTEXTMENU',
'WM_COMMAND',
'VK_APPS',
'TVM_SELECTITEM',
'EndMenu',
)
def production_sources():
return sorted(path for path in SOURCE_ROOT.rglob('*.py') if '__pycache__' not in path.parts)
def test_no_input_injection_or_desktop_switching_in_production_code():
offenders = []
for path in production_sources():
text = path.read_text(encoding='utf-8')
for api in FORBIDDEN_APIS:
if path.name == 'library_manager_verify.py' and api in {'WM_MOUSEMOVE', 'TVM_SELECTITEM'}:
continue
if path.name == 'library_manager_verify.py' and api == 'click_input':
# The only permitted real-input route is the explicit
# interactive compatibility mode; the default worker remains
# isolated and never reaches this branch.
continue
if api in text:
offenders.append(f'{path.name}: {api}')
assert offenders == [], f'输入注入/桌面切换/菜单驱动 API 不得出现在生产代码: {offenders}'
def test_library_manager_verify_route_is_private_and_semantic():
text = (SOURCE_ROOT/'library_manager_verify.py').read_text(encoding='utf-8')
assert 'launch_library_verify' in text
assert 'invoke_with_evidence(' in text and 'verify_action.invoke,' in text
# WM_COMMAND dispatch was experimentally disproved on EE7.9 and must not
# return to the production path. The only fallback is a message posted to
# the private popup menu itself, after semantic Verify resolution.
assert '_post_lmc_menu_command' not in text
assert 'verify_command_posted' not in text
assert '_post_menu_item_click' in text
assert 'WM_RBUTTONDOWN' in text and 'WM_RBUTTONUP' in text
assert 'SetCursorPos' not in text
assert 'SendInput' not in text
assert 'SetForegroundWindow' not in text
def test_real_input_is_guarded_by_explicit_interactive_mode():
text = (SOURCE_ROOT/'library_manager_verify.py').read_text(encoding='utf-8')
assert 'if interactive_input:' in text
assert 'item.click_input(button=\'right\')' in text
assert 'if menu_handle and not interactive_input:' in text
def test_batch_execution_uses_observed_reusable_circuit_route():
import inspect
from cbb_refresh_verify import mentor_adapter
text = inspect.getsource(mentor_adapter.execute_job)
assert 'native_lm_verify' in text
assert "job['lmc_file']" in text
assert 'launch_pcb_process' in text
def test_dialog_handling_only_posts_button_clicks():
text = (SOURCE_ROOT/'mentor_adapter.py').read_text(encoding='utf-8')
assert 'BM_CLICK' in text
# The only posted messages are the documented dialog button clicks.
assert text.count('PostMessage') == 1
def test_desktop_worker_close_kills_unbound_worker_tree():
text = (SOURCE_ROOT/'desktop_worker.py').read_text(encoding='utf-8')
assert 'if self.poll() is None:' in text
assert 'self.kill()' in text
def test_verification_never_deletes_or_moves_library_files():
for path in production_sources():
text = path.read_text(encoding='utf-8')
for operation in ('os.remove', '.unlink('):
assert operation not in text, f'{path.name} 不得删除/移动中心库文件'
adapter = (SOURCE_ROOT/'mentor_adapter.py').read_text(encoding='utf-8')
assert "Path(root) / 'backup'" in adapter
assert 'shutil.rmtree(backup)' in adapter
# The only library-side mutation is quarantining the volatile, unreachable
# cdbsvr address advertisement; stable CBB content remains untouched.
assert adapter.count('shutil.move') == 1
assert "sAddress.adr" in adapter
+77
View File
@@ -0,0 +1,77 @@
import os
from pathlib import Path
import subprocess
import pytest
from cbb_refresh_verify.runtime_timing import parse_save_progress
@pytest.mark.parametrize('save_ok', [True, False])
def test_packaged_vbs_measures_real_save_call_and_preserves_failure_gate(tmp_path, save_ok):
# Execute the real helper in its target 32-bit host. Only external COM
# object creation is replaced; Save/Validate/Close order and timers are real.
script = Path(__file__).parents[1] / 'src/cbb_refresh_verify/save_verified_block.vbs'
source = script.read_text(encoding='utf-8')
classes = r'''
Class FakePi
Public ProjectFile, ForwardAnnotationStatus, SynchCESStatus, LoadCESStatus, BackAnnotationStatus
Private Sub Class_Initialize
ProjectFile = WScript.Arguments(0)
ForwardAnnotationStatus = 2
SynchCESStatus = 2
LoadCESStatus = 2
BackAnnotationStatus = 2
End Sub
End Class
Class FakeDoc
Public Property Get ProjectIntegration
Set ProjectIntegration = New FakePi
End Property
Public Function Validate(token)
Validate = 17
End Function
Public Function Save()
WScript.Sleep 120
Save = SAVE_RETURN
End Function
Public Function IsSaved()
IsSaved = True
End Function
Public Function Close(saveChanges)
Close = True
End Function
End Class
Class FakeApp
Public Property Get ActiveDocument
Set ActiveDocument = New FakeDoc
End Property
Public Sub Quit()
End Sub
End Class
Class FakeLic
Public Function GetToken(value)
GetToken = value
End Function
End Class
'''
source = source.replace('Option Explicit', 'Option Explicit\n' + classes.replace('SAVE_RETURN', str(save_ok)))
source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp')
source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic')
harness = tmp_path/'save_harness.vbs'
harness.write_text(source, encoding='ascii')
cscript = Path(os.environ['WINDIR'])/'SysWOW64/cscript.exe'
completed = subprocess.run([str(cscript), '//nologo', str(harness), 'expected.prj'],
capture_output=True, text=True, timeout=10)
parsed = parse_save_progress(completed.stdout)
assert parsed['timings_seconds']['save'] >= .08
if save_ok:
assert completed.returncode == 0, completed.stderr
assert 'SAVE_OK' in parsed['markers']
assert 'CLOSE_OK' in parsed['markers']
assert parsed['timings_seconds']['post_save_check'] >= 0
assert parsed['timings_seconds']['close'] >= 0
else:
assert completed.returncode == 4, completed.stderr
assert 'SAVE_OK' not in parsed['markers']
assert 'CLOSE_OK' not in parsed['markers']
+140
View File
@@ -0,0 +1,140 @@
from pathlib import Path
from cbb_refresh_verify.status_bridge import (
BridgeResult,
BridgeUnavailable,
BridgeResponseError,
parse_bridge_response,
StatusBridgeClient,
)
import pytest
def test_parse_ready_response_preserves_raw_evidence():
result = parse_bridge_response(
'{"ok":true,"status":"READY","source":"IsVerifiedReuseBlock","raw_status":2}'
)
assert result.status == "READY"
assert result.source == "IsVerifiedReuseBlock"
assert result.raw_status == 2
def test_parse_rejects_success_without_authoritative_status():
try:
parse_bridge_response('{"ok":true,"status":"UNKNOWN"}')
except BridgeResponseError as error:
assert "authoritative" in str(error)
else:
raise AssertionError("missing authoritative status must be rejected")
def test_unavailable_bridge_has_actionable_diagnostic(tmp_path):
missing = tmp_path / "CbbStatusBridge32.exe"
try:
raise BridgeUnavailable(missing)
except BridgeUnavailable as error:
assert str(missing) in str(error)
assert "32-bit" in str(error)
def test_bridge_rejects_mismatched_response_identity():
line = ('{"ok":true,"request_id":"request-2","block_name":"OTHER",'
'"lmc_file":"C:/lib/other.lmc","status":"READY",'
'"source":"IsVerifiedReuseBlock","raw_status":1}')
with pytest.raises(BridgeResponseError, match='请求标识'):
parse_bridge_response(line, expected_request_id='request-1',
expected_block='TARGET', expected_lmc='C:/lib/mentor_lib.lmc')
def test_bridge_accepts_correlated_response():
line = ('{"ok":true,"request_id":"request-1","block_name":"TARGET",'
'"lmc_file":"C:/lib/mentor_lib.lmc","status":"READY",'
'"source":"IsVerifiedReuseBlock","raw_status":1}')
result = parse_bridge_response(line, expected_request_id='request-1',
expected_block='TARGET', expected_lmc='C:/lib/mentor_lib.lmc')
assert result == BridgeResult(
'READY', 'IsVerifiedReuseBlock', 1, '', result.response,
request_id='request-1', block_name='TARGET', lmc_file='C:/lib/mentor_lib.lmc')
def test_bridge_accepts_legacy_response_with_redundant_unc_separators():
line = ('{"ok":true,"request_id":"request-1","block_name":"TARGET",'
'"lmc_file":"\\\\\\\\\\\\\\\\192.168.0.252\\\\\\\\eda\\\\\\\\lib\\\\\\\\mentor_lib.lmc",'
'"status":"READY","source":"IsVerifiedReuseBlock","raw_status":1}')
result = parse_bridge_response(
line,
expected_request_id='request-1',
expected_block='TARGET',
expected_lmc=r'\\192.168.0.252\eda\lib\mentor_lib.lmc',
)
assert result.status == 'READY'
def test_one_shot_client_preserves_mapped_drive_in_request(tmp_path, monkeypatch):
executable = tmp_path / 'CbbStatusBridge32.exe'
executable.touch()
captured = {}
class Process:
returncode = 0
def communicate(self, request_line, timeout):
import json
request = json.loads(request_line)
captured.update(request)
return json.dumps({
'ok': True,
'request_id': request['request_id'],
'block_name': request['block_name'],
'lmc_file': request['lmc_file'],
'status': 'READY',
'source': 'IsVerifiedReuseBlock',
}), ''
monkeypatch.setattr(
'cbb_refresh_verify.status_bridge.subprocess.Popen',
lambda *args, **kwargs: Process(),
)
StatusBridgeClient(executable).query(Path(r'Y:\library\mentor_lib.lmc'), 'TARGET')
assert captured['lmc_file'] == r'Y:\library\mentor_lib.lmc'
def test_one_shot_client_passes_private_read_opt_in_to_bridge(tmp_path, monkeypatch):
executable = tmp_path / 'CbbStatusBridge32.exe'
executable.touch()
captured = {}
class Process:
returncode = 0
def communicate(self, request_line, timeout):
import json
request = json.loads(request_line)
response = {
'ok': True,
'request_id': request['request_id'],
'block_name': request['block_name'],
'lmc_file': request['lmc_file'],
'status': 'READY',
'source': 'IsVerifiedReuseBlock',
'raw_status': 1,
}
return json.dumps(response), ''
def popen(*args, **kwargs):
captured.update(kwargs.get('env') or {})
return Process()
monkeypatch.setattr('cbb_refresh_verify.status_bridge.subprocess.Popen', popen)
result = StatusBridgeClient(
executable, env={'CBB_STATUS_BRIDGE_ALLOW_PRIVATE': '1'}
).query(tmp_path / 'mentor_lib.lmc', 'TARGET')
assert result.status == 'READY'
assert captured['CBB_STATUS_BRIDGE_ALLOW_PRIVATE'] == '1'
+46
View File
@@ -0,0 +1,46 @@
import json
import subprocess
import sys
from pathlib import Path
def run_server_client(fake_server, names):
process = subprocess.Popen(
[sys.executable, str(fake_server)],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True,
)
requests = []
for name in names:
requests.append(json.dumps({"op": "is_verified", "lmc_file": "x.lmc",
"block_name": name, "block_type": "RULP"}) + "\n")
stdout, _ = process.communicate("".join(requests), timeout=5)
return [json.loads(line) for line in stdout.splitlines() if line.strip()]
def test_server_response_is_one_line_per_request(tmp_path):
fake = tmp_path / "fake_server.py"
fake.write_text(
"import json,sys\n"
"for line in sys.stdin:\n"
" p=json.loads(line); print(json.dumps({'ok':True,'block_name':p['block_name'],'status':'READY','source':'fake'}), flush=True)\n",
encoding="utf-8",
)
result = run_server_client(fake, ["A", "B"])
assert [item["block_name"] for item in result] == ["A", "B"]
def test_one_bad_request_does_not_stop_following_request(tmp_path):
fake = tmp_path / "fake_server.py"
fake.write_text(
"import json,sys\n"
"for line in sys.stdin:\n"
" p=json.loads(line)\n"
" if p.get('block_name') == 'BAD': print(json.dumps({'ok':False,'error':'bad'}), flush=True)\n"
" else: print(json.dumps({'ok':True,'block_name':p['block_name'],'status':'PENDING','source':'fake'}), flush=True)\n",
encoding="utf-8",
)
result = run_server_client(fake, ["BAD", "GOOD"])
assert result[0]["ok"] is False
assert result[1]["ok"] is True
+267
View File
@@ -0,0 +1,267 @@
import os
from pathlib import Path
os.environ.setdefault('QT_QPA_PLATFORM','offscreen')
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
from cbb_refresh_verify.ui.main_window import MainWindow
from cbb_refresh_verify.verify_runner import VerifyResult
from threading import Event
from PySide6.QtCore import Qt
from PySide6.QtGui import QPalette
def test_application_palette_keeps_table_text_readable(qtbot):
from PySide6.QtWidgets import QApplication
from cbb_refresh_verify.application import configure_qt_application
app = QApplication.instance()
configure_qt_application(app)
text = app.palette().color(QPalette.ColorRole.Text)
base = app.palette().color(QPalette.ColorRole.Base)
assert text.value() < 100
assert base.value() > 180
def fake_reader(_): return LibraryReadResult((CbbRecord('CBB1','Reusable Blocks'),))
def test_verify_requires_loaded_library_and_invalidates_on_path_change(qtbot):
window=MainWindow(reader=fake_reader, verifier=lambda _: VerifyResult('PASS')); qtbot.addWidget(window)
assert not window.batch_button.isEnabled()
window.lmc_edit.setText('lib.lmc'); window.load_library()
qtbot.waitUntil(lambda: window.batch_button.isEnabled())
# LibSpec / DMS config are optional: they only add the contents check.
assert hasattr(window, 'libspec_edit') and hasattr(window, 'dms_edit')
window.lmc_edit.setText('different.lmc')
assert not window.batch_button.isEnabled()
assert window.cbb_table.rowCount() == 0
def test_ui_removes_current_cbb_controls_and_hides_advanced_settings(qtbot):
window = MainWindow(reader=fake_reader, verifier=lambda _: VerifyResult('PASS'))
qtbot.addWidget(window)
assert not hasattr(window, 'cbb_combo')
assert not hasattr(window, 'verify_button')
assert window.advanced_panel.isHidden()
window.advanced_toggle.click()
assert not window.advanced_panel.isHidden()
def test_window_title_and_action_buttons_are_polished(qtbot):
window = MainWindow(reader=fake_reader, verifier=lambda _: VerifyResult('PASS'))
qtbot.addWidget(window)
assert '后台串行' not in window.windowTitle()
assert not window.windowIcon().isNull()
for button in (window.load_button, window.browse_button, window.selected_batch_button,
window.batch_button, window.stop_button, window.logs_button):
assert not button.icon().isNull()
def test_import_incomplete_rows_are_skipped_and_disabled(qtbot, tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
broken = tmp_path / 'ReusableBlocksLP' / 'BROKEN_CBB' / 'Work'
broken.mkdir(parents=True)
valid = tmp_path / 'ReusableBlocksLP' / 'VALID_CBB' / 'Work'
(valid / 'PCB' / 'Layout').mkdir(parents=True)
(valid / 'VALID_CBB.prj').write_text('KEY PCBDesignPath "PCB\\actual.pcb"', encoding='utf-8')
(valid / 'PCB' / 'actual.pcb').write_text('pcb', encoding='utf-8')
(valid / 'PCB' / 'Layout' / 'LayoutDB.lyt').write_bytes(b'lyt')
calls = []
def reader(_):
return LibraryReadResult((CbbRecord('BROKEN_CBB', 'LP'), CbbRecord('VALID_CBB', 'LP')))
window = MainWindow(reader=reader,
verifier=lambda req: (calls.append(req.block_name) or VerifyResult('PASS')),
data_root=tmp_path)
qtbot.addWidget(window)
window.lmc_edit.setText(str(lmc))
window.load_library()
qtbot.waitUntil(lambda: window.batch_button.isEnabled())
assert window.cbb_table.item(0, 2).text().startswith('跳过:')
assert not (window.cbb_table.item(0, 0).flags() & Qt.ItemIsUserCheckable)
window.verify_all()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['VALID_CBB']
def test_batch_does_not_block_ui_and_stop_skips_next_item(qtbot,tmp_path):
entered, release = Event(), Event()
calls=[]
def verify(req):
calls.append(req.block_name); entered.set()
release.wait(3)
return VerifyResult('PASS')
def reader(_): return LibraryReadResult((CbbRecord('A','LP'),CbbRecord('B','LP')))
window=MainWindow(reader=reader,verifier=verify,data_root=tmp_path)
qtbot.addWidget(window); window.lmc_edit.setText('lib.lmc');window.load_library()
qtbot.waitUntil(lambda: window.batch_button.isEnabled())
window.verify_all()
try:
qtbot.waitUntil(entered.is_set)
assert window.stop_button.isEnabled()
window.stop_button.click()
finally:
release.set()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['A']
assert list((tmp_path/'reports').glob('*.log'))
def test_loaded_library_shows_selectable_rows_and_selected_batch_action(qtbot, tmp_path):
def reader(_): return LibraryReadResult((CbbRecord('A', 'LP'), CbbRecord('B', 'LP')))
window = MainWindow(reader=reader, verifier=lambda _: VerifyResult('PASS'), data_root=tmp_path)
qtbot.addWidget(window)
window.lmc_edit.setText('lib.lmc')
window.load_library()
qtbot.waitUntil(lambda: window.batch_button.isEnabled())
assert window.cbb_table.rowCount() == 2
assert not window.selected_batch_button.isEnabled()
window.cbb_table.item(0, 0).setCheckState(Qt.Checked)
window.selected_batch_button.click()
qtbot.waitUntil(lambda: not window.busy)
assert (tmp_path / 'reports').exists()
assert window.cbb_table.item(0, 2).text() == '绿色 / Ready'
assert window.cbb_table.item(0, 3).text() == 'PASS'
def test_large_library_load_does_not_update_controls_for_every_table_cell(qtbot, tmp_path):
records = tuple(CbbRecord(f'CBB_{index:04d}', 'LP') for index in range(300))
window = MainWindow(reader=lambda _: LibraryReadResult(records), data_root=tmp_path)
qtbot.addWidget(window)
calls = []
original_update = window._update
window._update = lambda: (calls.append(window.cbb_table.rowCount()), original_update())[1]
window.lmc_edit.setText(str(tmp_path / 'center.lmc'))
window.load_library()
qtbot.waitUntil(lambda: not window.busy)
assert window.cbb_table.rowCount() == 300
assert window._row_by_name['CBB_0299'] == 299
assert len(calls) < 20
def test_ready_rows_show_status_and_cannot_be_selected_or_verified(qtbot, tmp_path):
def reader(_):
return LibraryReadResult((CbbRecord('READY_CBB', 'LP', status='READY'), CbbRecord('PENDING_CBB', 'LP', status='PENDING')))
calls = []
window = MainWindow(reader=reader, verifier=lambda req: (calls.append(req.block_name) or VerifyResult('PASS')), data_root=tmp_path)
qtbot.addWidget(window)
window.lmc_edit.setText('lib.lmc')
window.load_library()
qtbot.waitUntil(lambda: window.batch_button.isEnabled())
assert window.cbb_table.columnCount() == 4
assert window.cbb_table.item(0, 2).text() == '绿色 / Ready'
assert not (window.cbb_table.item(0, 0).flags() & Qt.ItemIsUserCheckable)
assert window.cbb_table.item(0, 0).background().color().name().lower() == '#e8f5e9'
window.cbb_table.item(0, 0).setCheckState(Qt.Checked)
assert 'READY_CBB' not in window._selected_names()
window.verify_all()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['PENDING_CBB']
assert window.cbb_table.item(1, 0).checkState() == Qt.Unchecked
assert not (window.cbb_table.item(1, 0).flags() & Qt.ItemIsUserCheckable)
assert window.cbb_table.item(1, 0).background().color().name().lower() == '#e8f5e9'
def test_unc_library_uses_mentor_path_for_read_and_verify_and_releases_on_close(qtbot, tmp_path):
calls = []
class FakeLease:
display_path = Path(r'\\server\share\mentor_lib.lmc')
mentor_path = Path(r'Y:\mentor_lib.lmc')
closed = False
def close(self):
self.closed = True
lease = FakeLease()
def lease_factory(path):
assert str(path) == str(lease.display_path)
return lease
def reader(path):
calls.append(path)
return LibraryReadResult((CbbRecord('CBB1', 'LP', status='PENDING'),))
window = MainWindow(reader=reader, data_root=tmp_path, path_lease_factory=lease_factory)
qtbot.addWidget(window)
window.lmc_edit.setText(str(lease.display_path))
window.load_library()
qtbot.waitUntil(lambda: not window.busy)
assert calls == [lease.mentor_path]
assert window._request('CBB1').lmc_file == lease.mentor_path
window.close()
assert lease.closed
def test_advanced_options_are_copied_to_verify_request(qtbot, tmp_path):
window = MainWindow(reader=fake_reader, data_root=tmp_path)
qtbot.addWidget(window)
window.loaded_path = 'display.lmc'
window.mentor_lmc_path = Path(r'Y:\lib\mentor_lib.lmc')
window.libspec_edit.setText('EE7.9_CUSTOM')
window.dms_edit.setText(r'Y:\config\login.conf')
window.mentor_bin_edit.setText(r'D:\Mentor\bin')
window.timeout_spin.setValue(45)
request = window._request('CBB1')
assert request.lmc_file == Path(r'Y:\lib\mentor_lib.lmc')
assert request.libspec == 'EE7.9_CUSTOM'
assert request.dms_login_config == r'Y:\config\login.conf'
assert request.mentor_bin == r'D:\Mentor\bin'
assert request.timeout_seconds == 45
def test_ui_request_keeps_background_trigger_mode(qtbot, tmp_path):
window = MainWindow(reader=fake_reader, data_root=tmp_path)
qtbot.addWidget(window)
window.loaded_path = 'display.lmc'
window.mentor_lmc_path = Path(r'Y:\lib\mentor_lib.lmc')
assert window._request('CBB1').interactive_input is False
def test_ui_request_exposes_native_lm_verify_compatibility_switch(qtbot, tmp_path):
window = MainWindow(reader=fake_reader, data_root=tmp_path)
qtbot.addWidget(window)
window.loaded_path = 'display.lmc'
window.mentor_lmc_path = Path(r'Y:\lib\mentor_lib.lmc')
assert window._request('CBB1').native_lm_verify is False
window.native_lm_verify_check.setChecked(True)
assert window._request('CBB1').native_lm_verify is True
def test_library_directory_input_uses_its_only_lmc(qtbot, tmp_path):
lmc = tmp_path / 'mentor_lib.lmc'
lmc.touch()
calls = []
window = MainWindow(
reader=lambda path: (
calls.append(path) or LibraryReadResult((CbbRecord('CBB1', 'LP'),))
),
data_root=tmp_path / 'data',
)
qtbot.addWidget(window)
window.lmc_edit.setText(str(tmp_path))
window.load_library()
qtbot.waitUntil(lambda: not window.busy)
assert calls == [lmc]
assert window._request('CBB1').lmc_file == lmc
def test_ui_default_timeout_matches_request_and_labels_inactivity(qtbot):
from cbb_refresh_verify.verify_runner import VerifyRequest
window = MainWindow(reader=fake_reader)
qtbot.addWidget(window)
assert window.timeout_spin.value() == 600
assert window.timeout_spin.value() == VerifyRequest(Path('lib.lmc'), 'CBB1', Path('data')).timeout_seconds
assert '无进展' in window.timeout_spin.suffix()
def test_batch_summary_exposes_failures_only_report(qtbot, tmp_path):
window = MainWindow(reader=fake_reader, data_root=tmp_path)
qtbot.addWidget(window)
report=tmp_path/'reports/batch-20260929-test.log'
window._batch_done(([VerifyResult('FAIL',stderr='Mentor error')],report))
assert '仅失败日志' in window.summary.text()
assert str(report.with_name('failures-20260929-test.log')) in window.summary.text()
+150
View File
@@ -0,0 +1,150 @@
from pathlib import Path
import json
import pytest
from cbb_refresh_verify import verify_diagnostics as diagnostics
def pcb_fixture(tmp_path):
pcb = tmp_path / 'CBB' / 'Work' / 'PCB' / 'CBB.pcb'
pcb.parent.mkdir(parents=True)
pcb.write_bytes(b'PCB')
return pcb
def test_missing_generated_jobprefs_is_warning_not_a_failure(tmp_path):
pcb = pcb_fixture(tmp_path)
record = diagnostics.collect_preflight_diagnostics(pcb, tmp_path / 'evidence')
assert record['non_blocking'] is True
assert record['directory_writable'] is True
assert len(record['paths']) == 4
assert any(item['path'].endswith(str(Path('Work/Layout_Temp/JobPrefsDB.jpf')))
for item in record['paths'])
assert len(record['warnings']) == 3
assert list(pcb.parent.iterdir()) == [pcb] # no fake dirs, lock or prefs files
assert json.loads((tmp_path/'evidence/diagnostics/preflight.json').read_text('utf-8')) == record
def test_jobprefs_readable_probe_reads_only_one_byte_and_closes_handle(tmp_path, monkeypatch):
pcb = pcb_fixture(tmp_path)
prefs = pcb.parent/'Layout/JobPrefsDB.jpf'
prefs.parent.mkdir()
prefs.write_bytes(b'real database data')
record = diagnostics.collect_preflight_diagnostics(pcb, tmp_path/'evidence')
entry = next(item for item in record['paths'] if item['path'] == str(prefs))
assert entry['readable'] is True
assert entry['size_bytes'] == len(b'real database data')
prefs.rename(prefs.with_suffix('.moved')) # would fail on Windows if handle leaked
def test_unreadable_jobprefs_does_not_prevent_verify(tmp_path, monkeypatch):
pcb = pcb_fixture(tmp_path)
prefs = pcb.parent/'Layout/JobPrefsDB.jpf'
prefs.parent.mkdir()
prefs.touch()
original = Path.open
def deny(path, *args, **kwargs):
if path == prefs:
raise PermissionError('simulated network share permission')
return original(path, *args, **kwargs)
monkeypatch.setattr(Path, 'open', deny)
record = diagnostics.collect_preflight_diagnostics(pcb, tmp_path/'evidence')
assert record['non_blocking'] is True
assert 'simulated network share permission' in str(record)
def test_writability_failure_is_diagnostic_only(tmp_path, monkeypatch):
pcb = pcb_fixture(tmp_path)
def deny(**kwargs):
raise PermissionError('no create permission')
monkeypatch.setattr(diagnostics.tempfile, 'NamedTemporaryFile', deny)
record = diagnostics.collect_preflight_diagnostics(pcb, tmp_path/'evidence')
assert record['directory_writable'] is False
assert record['non_blocking'] is True
assert 'no create permission' in str(record)
assert pcb.read_bytes() == b'PCB'
def test_native_log_tail_is_bounded_and_preserves_multiline_detail(tmp_path):
pcb = pcb_fixture(tmp_path)
source = pcb.parent/'LogFiles/ForwardAnnotation.txt'
source.parent.mkdir()
raw = b'x' * 10000 + b'\nERROR: Symbol $1I1\n pin mapping explanation\r\n'
source.write_bytes(raw)
record = diagnostics.collect_native_failure_logs(pcb, tmp_path/'evidence', max_bytes=1024)
item = next(item for item in record['files'] if item['source'] == str(source))
target = Path(item['evidence'])
assert item['truncated'] is True
assert item['original_size_bytes'] == len(raw)
assert target.read_bytes() == raw[-1024:]
assert source.read_bytes() == raw
source.rename(source.with_suffix('.moved'))
assert (tmp_path/'evidence/diagnostics/native-logs.json').is_file()
def test_native_logs_include_known_root_and_logfiles_paths_without_recursing(tmp_path, monkeypatch):
pcb = pcb_fixture(tmp_path)
sources = [pcb.parent/'LogFiles/PCBLogFile.txt', pcb.parent/'ReusableBlock.txt',
pcb.parent.parent/'ReusableBlock.txt']
for source in sources:
source.parent.mkdir(exist_ok=True)
source.write_text('native message', encoding='utf-8')
def unexpected(*args, **kwargs):
pytest.fail('diagnostics must not recursively enumerate a network CBB')
monkeypatch.setattr(Path, 'rglob', unexpected)
monkeypatch.setattr(Path, 'glob', unexpected)
record = diagnostics.collect_native_failure_logs(pcb, tmp_path/'evidence')
copied = [item for item in record['files'] if item.get('evidence')]
assert {item['source'] for item in copied} == {str(source) for source in sources}
assert len({item['evidence'] for item in copied}) == 3
def test_log_access_error_is_recorded_not_raised(tmp_path, monkeypatch):
pcb = pcb_fixture(tmp_path)
source = pcb.parent/'LogFiles/PCBLogFile.txt'
source.parent.mkdir()
source.touch()
original = Path.open
def deny(path, *args, **kwargs):
if path == source:
raise PermissionError('native log is locked')
return original(path, *args, **kwargs)
monkeypatch.setattr(Path, 'open', deny)
record = diagnostics.collect_native_failure_logs(pcb, tmp_path/'evidence')
assert 'native log is locked' in str(record)
assert record['non_blocking'] is True
def test_local_evidence_write_error_does_not_mask_original_failure(tmp_path, monkeypatch):
pcb = pcb_fixture(tmp_path)
original = Path.mkdir
def deny(path, *args, **kwargs):
if 'evidence' in path.parts:
raise PermissionError('evidence unavailable')
return original(path, *args, **kwargs)
monkeypatch.setattr(Path, 'mkdir', deny)
record = diagnostics.collect_native_failure_logs(pcb, tmp_path/'evidence')
assert 'evidence unavailable' in str(record)
assert record['non_blocking'] is True
def test_failure_log_helper_has_hard_timeout_and_never_launches_mentor(tmp_path, monkeypatch):
import subprocess
pcb = pcb_fixture(tmp_path)
root = tmp_path/'evidence'
root.mkdir()
job_path = root/'request.json'
job_path.write_text(json.dumps({'root': str(root), 'pcb': str(pcb)}), encoding='utf-8')
calls = []
def timed_out(command, **kwargs):
calls.append((command, kwargs))
raise subprocess.TimeoutExpired(command, kwargs['timeout'])
monkeypatch.setattr(diagnostics.subprocess, 'run', timed_out)
result = diagnostics.capture_failure_logs_with_timeout(job_path, timeout_seconds=2)
assert result['status'] == 'TIMEOUT'
assert len(calls) == 1
assert '--collect-failure-logs' in calls[0][0]
assert '--verify-worker' not in calls[0][0]
assert calls[0][1]['timeout'] == 2
assert (root/'diagnostics/native-log-capture.json').is_file()
+44
View File
@@ -0,0 +1,44 @@
import json
import pytest
def test_parse_export_probe_requires_all_known_exports():
from cbb_refresh_verify.verify_probe import parse_export_probe
payload = {
"ok": True,
"probe": "exports",
"dll_path": r"D:\Mentor\LMCDLL70.dll",
"architecture": "x86",
"exports": {
"IsVerifiedReuseBlock": {"found": True, "address": "0x100544e0"},
"GetStatusRBInContextOfCL": {"found": True, "address": "0x1006ddc0"},
"VerifyReuseBlock": {"found": True, "address": "0x10057840"},
"UnVerifyReuseBlock": {"found": True, "address": "0x10061b40"},
"GetReusableCircuitVerificationStatus": {"found": True, "address": "0x20019c30"},
},
"write_call": {"enabled": False, "reason": "CFilename ABI not reconstructed"},
}
result = parse_export_probe(json.dumps(payload))
assert result.architecture == "x86"
assert result.export("VerifyReuseBlock").found is True
assert result.write_enabled is False
def test_parse_export_probe_rejects_write_enabled_payload():
from cbb_refresh_verify.verify_probe import ProbeResponseError, parse_export_probe
payload = {
"ok": True,
"probe": "exports",
"dll_path": "LMCDLL70.dll",
"architecture": "x86",
"exports": {},
"write_call": {"enabled": True, "reason": "unsafe"},
}
with pytest.raises(ProbeResponseError, match="写接口探测桥不能启用写调用"):
parse_export_probe(json.dumps(payload))
File diff suppressed because it is too large. Load diff
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff. Show more