Compare commits

...
87 Commits
Author SHA1 Message Date
阿白叔 c04957293c docs: release V1.1.2 with Chinese tutorial and embedded GIF 2026-10-16 07:25:40 +08:00
阿白叔 6b5f79b412 test: accept frozen BOM workflow and add window-only GIF tutorial 2026-10-15 23:35:57 +08:00
阿白叔 a16914bc72 docs: align current workflow and plan packaged acceptance 2026-10-15 23:01:48 +08:00
阿白叔 0f8dde61bf docs: assess release readiness against current checks and batch tools 2026-10-15 22:58:47 +08:00
阿白叔 ce574ddb44 perf(ui): render rule models and create detail views on demand 2026-10-15 22:51:10 +08:00
阿白叔 84d8f9c7f5 perf(ui): bound plan edit work and release finished BOM previews 2026-10-15 22:00:46 +08:00
阿白叔 b3883cfca1 perf(plans): resolve project identity once per validation pass 2026-10-15 22:00:20 +08:00
阿白叔 224f4e7c1e fix(startup): run recovery once and avoid scanning idle projects 2026-10-15 21:45:35 +08:00
阿白叔 45a9cc6e0c perf(bom): share validation and reuse the target inventory index 2026-10-15 21:45:05 +08:00
阿白叔 6c0ca95d84 refactor(ui): remove obsolete project table and test-only cell adapter 2026-10-15 21:35:32 +08:00
阿白叔 136d7ffd67 feat(ui): show verified per-reference replacement results 2026-10-15 21:06:57 +08:00
阿白叔 159616ea4a perf(logs): reuse event sequence for unchanged log files 2026-10-15 21:01:39 +08:00
阿白叔 d0125f8f59 fix(ui): isolate BOM reports and keep target workspace usable 2026-10-15 20:56:29 +08:00
阿白叔 2fdbe3acb3 test: verify Part Label copying through live UI replacement and independent readback 2026-10-15 19:27:15 +08:00
阿白叔 65a72c6a3a fix: tolerate transient status locks and document real BOM roundtrip validation 2026-10-15 18:22:33 +08:00
阿白叔 9b2372e389 fix: bound slow CAD startup and retain blocked COM diagnostics 2026-10-15 18:14:29 +08:00
阿白叔 29ea67c35e test: distinguish safe preflight failures from uncertain native results 2026-10-15 17:54:18 +08:00
阿白叔 d832a1c736 fix: recover uncertain native failures and reopen long project paths safely 2026-10-15 17:49:10 +08:00
阿白叔 7f0ec29d31 feat: report BOM validation and start new rounds from completed batches 2026-10-15 17:12:55 +08:00
阿白叔 ff06f86f62 fix: bridge long CAD project paths and normalize COM path getters 2026-10-15 17:09:56 +08:00
阿白叔 e655797e32 fix: tolerate transient continuation read locks and record regression results 2026-10-15 16:44:33 +08:00
阿白叔 b47059587a fix: share batch defaults and protect BOM drafts across task lifecycle 2026-10-15 16:44:11 +08:00
阿白叔 a1f924295c fix: cancel inventory reads safely and compare canonical discovery content 2026-10-15 16:40:35 +08:00
阿白叔 0f0d6a7103 fix: extend verified component inventories and preserve BOM edits 2026-10-15 16:28:37 +08:00
阿白叔 1b39d802bd Verify real CBB BOM imports and handle first-open native database updates 2026-10-15 15:20:19 +08:00
阿白叔 a332e7bd59 Validate stable native inventories across ICDB session updates 2026-10-15 15:01:27 +08:00
阿白叔 4d8ba4c5bb Convert reviewed CBB BOM into existing template with source audit 2026-10-15 14:36:46 +08:00
阿白叔 791b3854b3 Add cached task search and switchable display sorting 2026-10-15 14:36:24 +08:00
阿白叔 8986ce1759 Enable automatic text wrapping in BOM templates 2026-10-15 14:18:32 +08:00
阿白叔 9f95b24067 Add project-scoped batch BOM template and atomic preview confirmation 2026-10-15 14:13:47 +08:00
阿白叔 75165f60de Plan project-scoped batch BOM previews without publishing 2026-10-15 14:00:50 +08:00
阿白叔 714ac0bfc6 Fix blank BOM download and legacy worker long paths for 1.1.2 2026-10-15 13:53:45 +08:00
阿白叔 fc67d403cb Record verified 1.1.1 portable build and packaged private CAD probe 2026-10-15 13:35:47 +08:00
阿白叔 7610a0fd86 Retry transient Windows sharing conflicts when publishing private CAD state 2026-10-15 13:30:45 +08:00
阿白叔 980198a987 Release version 1.1.1 and fix standalone frozen CAD helper import 2026-10-15 13:27:59 +08:00
阿白叔 579ecc38c4 Document native private desktop execution and measured release evidence 2026-10-15 11:34:14 +08:00
阿白叔 48ad7b3592 Verify desktop disappearance and finish private session feedback and native probes 2026-10-15 11:30:14 +08:00
阿白叔 fee1aff557 Connect production replacement and recovery to owned private CAD sessions 2026-10-15 11:16:11 +08:00
阿白叔 f26e868bfc Handle native exited-child errors during private cleanup 2026-10-15 11:15:34 +08:00
阿白叔 5c0f6a3fd3 Harden private desktop process ownership and cleanup 2026-10-15 10:51:51 +08:00
阿白叔 2a4e793d70 Plan production private desktop execution and verified resource cleanup 2026-10-15 10:44:45 +08:00
阿白叔 7d1574e748 Complete four-part optimization checklist and compatibility evidence 2026-10-15 10:38:46 +08:00
阿白叔 dfe1f80f90 Record native session comparison and honest regression limits 2026-10-15 10:37:49 +08:00
阿白叔 5817522ac0 Integrate read-only task bundles and cancellable log and feedback reads 2026-10-15 10:37:47 +08:00
阿白叔 2172d8faee Reuse supervised project sessions between verified replacement steps 2026-10-15 10:37:37 +08:00
阿白叔 4194c011e3 fix(discovery): preserve uncached fallback for unverifiable projects 2026-10-15 10:24:28 +08:00
阿白叔 260e270be8 fix(discovery): stabilize first-open normalization before caching 2026-10-15 10:23:52 +08:00
阿白叔 80f1cfd799 Extract read-only project discovery worker orchestration 2026-10-15 10:18:34 +08:00
阿白叔 e265ca515d fix(snapshot): validate evidence generations and bound unstable reads 2026-10-15 10:10:29 +08:00
阿白叔 e3b0f8940c Preserve legacy terminal phase wrapper compatibility 2026-10-15 09:56:05 +08:00
阿白叔 c0bf96f49d Keep latest reads responsive with bounded cooperative cancellation 2026-10-15 09:54:39 +08:00
阿白叔 1df3f0cf30 Unify read-only quick-run evidence snapshots and protocol models 2026-10-15 09:54:28 +08:00
阿白叔 42e5736ec6 docs: plan project session reuse and cancellable read models 2026-10-15 09:50:30 +08:00
阿白叔 bc6b726675 feat: show execution phases and verify responsive task queries 2026-10-15 09:44:40 +08:00
阿白叔 87ec3acc20 Hash project content before reusing discovery evidence 2026-10-15 09:39:53 +08:00
阿白叔 78f3b0c32a feat: keep task browsing and paged logs responsive during execution 2026-10-15 09:35:45 +08:00
阿白叔 3e45040def Extract durable batch backup coordination from queue execution 2026-10-15 09:33:35 +08:00
阿白叔 44b4f5be48 Reuse validated task-local project discovery through public preparer APIs 2026-10-15 09:30:10 +08:00
阿白叔 1719683fc3 Add cancellable directory scanning and targeted task validation 2026-10-15 09:27:46 +08:00
阿白叔 83ed50452b docs: plan execution responsiveness improvements 2026-10-15 09:23:38 +08:00
阿白叔 d79250b699 docs: record native multi-project timings and regression results 2026-10-15 09:12:26 +08:00
阿白叔 0225787084 feat: record execution timings and speed up batch queues 2026-10-15 09:10:26 +08:00
阿白叔 20d8b81a34 feat: show persisted per-reference replacement details in task logs 2026-10-15 08:38:58 +08:00
阿白叔 10581df3e2 refactor: move batch plans above project execution details 2026-10-14 22:54:23 +08:00
阿白叔 ae7e0e6a1b feat: add BOM template import and simplify task navigation 2026-10-14 22:46:53 +08:00
阿白叔 6c817de359 Merge remote-tracking branch 'origin/main'
# Conflicts:
#	README.md
2026-10-14 22:29:53 +08:00
阿白叔 cffa845b11 docs: describe single-project controls and target search 2026-10-14 16:02:05 +08:00
阿白叔 f5d91e6216 refactor: make task detail single-project and add scoped execution 2026-10-14 15:57:16 +08:00
阿白叔 6b52aa534e test: allow injected desktop supervision on non-Windows 2026-10-14 15:56:50 +08:00
阿白叔 a18d4dbee6 docs: clarify private desktop probe evidence 2026-10-14 15:52:17 +08:00
阿白叔 b1a72bef29 feat: run read-only probe inside private desktop 2026-10-14 15:51:40 +08:00
阿白叔 fbc7ddd037 feat: enforce bound membership and native probe boundary 2026-10-14 15:49:16 +08:00
阿白叔 855af0bd12 feat: add frozen project context and isolated worker boundary 2026-10-14 15:32:55 +08:00
阿白叔 4f457b1e88 feat: add fast target plan search and visible-row editing 2026-10-14 15:32:09 +08:00
阿白叔 a93e40ed2a docs: record approved single-project UI and background worker plan 2026-10-14 15:25:53 +08:00
阿白叔 62e7114211 docs: record bounded native exports and installed help findings 2026-10-14 14:48:29 +08:00
阿白叔 dd6ab99a31 docs: compare CBB Verify and native backend routes 2026-10-14 14:27:25 +08:00
阿白叔 de2d48fbe0 feat: integrate V1.1.0 project task planning into existing desktop UI 2026-10-14 13:55:48 +08:00
阿白叔 157b99851a Guard complete target sheet readback 2026-10-14 13:43:50 +08:00
阿白叔 730c76081f Use latest status when checking recovered jobs 2026-10-14 13:38:43 +08:00
阿白叔 f3d0d7a93d Track latest unverified queue state 2026-10-14 13:31:52 +08:00
阿白叔 235a1005e9 Implement v1.1 target plans and project task backend 2026-10-14 13:30:30 +08:00
阿白叔 a7e1b9bd33 feat: add V1.1.0 serial task scheduler and fast verification entrypoints 2026-10-14 12:02:46 +08:00
阿白叔 210fae575d docs: define V1.1.0 single-project task iteration 2026-10-14 11:28:50 +08:00
阿白叔 c9b38f15c0 chore: ignore local worktrees 2026-10-14 10:21:50 +08:00
阿白叔 5051a3b9d6 Improve README documentation 2026-10-14 10:10:26 +08:00
abaishu0730 7dd7bc8d12 docs: add project README 2026-10-13 11:22:30 +08:00
195 changed files with 21834 additions and 2773 deletions

No files matched your search

+2
View File
@@ -16,3 +16,5 @@ __pycache__/
*.rar
.coverage
coverage.xml
/.worktrees/
/.superpowers/
+130
View File
@@ -0,0 +1,130 @@
# DxDesigner 器件批量替换工具
面向 **Windows + DxDesigner / Expedition Enterprise 7.9.5** 的器件批量替换工具。一个工程对应一个任务,可以只替换同料号下的部分位号;支持直接编辑和 Excel BOM 导入,同批工程按顺序执行。
**最新版本:V1.1.2** · [下载便携包](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/releases/download/v1.1.2/DxPartReplace-1.1.2.zip) · [版本说明与附件](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/releases/tag/v1.1.2) · [完整使用说明](docs/user/v1.1.0-project-tasks.md)
## 窗口操作教程
下面的 GIF 来自已验收 EXE 的真实窗口操作,包含创建任务、BOM 导入、错误行提示、保存、顺序执行、查看结果和开始新一轮。共 20 个步骤、47.5 秒;仅记录工具及其弹窗,CAD 等待已压缩,Excel 填表示例在录制之外完成。
![V1.1.2 窗口操作教程](docs/user/media/v1.1.2-window-bom-tutorial.gif)
如果图片没有自动播放,可以[单独打开 GIF](docs/user/media/v1.1.2-window-bom-tutorial.gif)。
## 开始使用
1. 下载并完整解压便携包,保留 `DxPartReplace.exe` 和 `_internal` 的相对位置。**便携包无需安装 Python**,本机仍需安装可用的 DxDesigner、许可证和中央库。
2. 双击 `DxPartReplace.exe`。首次运行会自动创建同目录的 `data`,保存任务、日志和执行证据。
3. 点击左侧 **新建**,在弹窗填写工程根目录,点击 **读取工程**,勾选需要处理的 `.prj`,再点击 **创建任务**。每个工程自动创建一个任务。
首次使用请在完整工程副本上验证映射与库配置。执行前保存并关闭待处理工程;工具会启动自己的后台 CAD,主桌面仍可查看其他文件。
## 方式一:通过 BOM 批量配置
### 1. 导出本批模板
选择任务,打开顶部 **本批位号计划**,点击 **BOM 模板**。只要已导入工程,就能导出同批所有工程的一张空白表,**不需要先采集位号或填写料号规则**。
工程名称、工程路径自动填写。工程路径用于唯一分配任务,请保持原样;同一工程有多条替换时,可以复制该工程行。
### 2. 在 Excel 填写替换项
保留原模板的 11 列表头,按需要填写:
| 列名 | 填写内容 |
| --- | --- |
| `old_part_number` | 工程当前的旧料号 |
| `new_part_number` | 中央库中的目标新料号 |
| `refdes` | 要处理的位号,例如 `RV05`;一行可以写多个位号,以逗号、分号、空格或顿号分隔 |
| `enabled` | `TRUE` / `是` 表示替换,`FALSE` / `否` 表示保留 |
| `sync_nc` | 是否同步 NC,默认开启,可逐行关闭 |
| `custom_value` | 可选的自定义 Value;填写后优先写入,留空沿用任务的 Value 策略 |
例如,首次配置的旧料号同时对应 `RV05`、`RV11`,只想替换 `RV05`,可以只填写 `RV05` 的启用项;首次采集的其余位号默认不替换。
**再次导入时,BOM 中未列出的既有计划行会保留原勾选和编辑状态。** 如果这轮只想执行 BOM 列出的目标,请在预览中检查其他启用行,并明确取消勾选,或在 BOM 中填写对应的 `enabled=FALSE` 行。
同名位号分布在不同图页时,补填 `schematic_name`、`sheet_number` 或 `uid` 消除歧义。`enabled` 留空默认替换,`sync_nc` 留空默认开启;建议显式填写。料号按文本填写;导入不接受公式,也不接受旧新相同、链式或循环替换。
### 3. 导入并检查报告
点击 **导入 BOM**,选择填好的文件。工具按工程匹配位号;缺少库存时,会调用后台 CAD 只读采集。
- 校验报告显示通过、失败、未检查的行数,并标明 Excel 行号及原因。
- 有错误时,整批不会生成新的可保存预览,也不会部分写入计划。修正后重新导入。
- 全部通过后,先得到预览;可以切换任务,检查或修改各工程的位号计划。
### 4. 保存并执行
确认预览后点击 **保存本批位号计划**;普通单工程编辑时按钮显示 **保存位号计划**。
点击 **执行当前任务** 处理当前工程,或点击左侧 **顺序执行本批任务** 处理同批工程。确认范围后,工具逐项执行原生 Replace Part、保存、关闭并重新打开核验。
**左侧搜索和显示排序只影响浏览,不改变本批执行范围。** 调整执行顺序请使用上移、下移任务按钮。
## 方式二:直接在界面编辑
1. 在 **本批料号规则** 添加旧、新料号,按需配置 Value 与同步 NC;规则提供采集条件和默认值。
2. 切到 **本批位号计划**,点击 **采集所有匹配位号**。
3. 勾选需要替换的行,逐行填写新料号、自定义 Value 和 NC。查找可按位号、UID、料号、图页或 Value 过滤;批量操作的范围会显示为当前工程或可见行。
4. 保存计划后执行。位号计划模式以**已保存的每行计划**为准,手动覆盖的值不会因修改默认规则而被随意覆盖。
两种方式可以配合使用,不必为了编辑而先导出 Excel。切换任务会保留编辑草稿;关闭时有未保存内容会提示保存全部、放弃或取消。
## Value、暂停与执行结果
- 顶部 **Value 策略** 开关控制当前任务是否将替换后的 Part Label 写入 Value;逐行自定义 Value 优先。处理多个任务时,分别确认各任务的开关。
- **同步 NC** 是逐行选项,默认开启,可以关闭。
- 点击 **完成当前项后暂停** 后,工具在当前步骤安全收尾后停止,不会在原生写入中途强行中断。
- 点击 **替换结果 / 日志** 查看图页、位号、旧料号、实际回读料号和核验状态。失败、未命中、未核验不会显示为已保存成功;完整日志支持翻页。
- 日志和 BOM 详情按需打开,关闭后释放窗口;数据和证据仍保留。
## 完成后再执行一轮
已完成任务可以点击 **开始新一轮**。工具归档旧计划、命令、快照与执行证据,清空过期位号基线,将同批已完成任务恢复为待配置。
接着按工程**当前料号**重新填 BOM 或修改规则,重新采集、保存并执行。旧轮次可通过 **查看轮次证据** 打开。出现状态不确定或恢复提示时,先使用 **核验并恢复**,不要直接重复执行。
## 更新程序与保留数据
先关闭旧程序并备份 `data`。完整解压新包,用新 EXE 和 `_internal` 配合原 `data` 使用;不要混用不同版本的依赖目录,也不要删除原数据。
```text
DxPartReplace/
DxPartReplace.exe
_internal/
data/ 首次运行后创建,更新时保留
task-center.db 任务数据库
logs/application.log 应用日志
tasks/<任务ID>/ 任务事件、备份、快照及轮次证据
```
不同版本不要同时打开同一数据目录。排查失败时保留日志、原生报告和工程副本;不要手工删除锁文件、状态或恢复证据来强行续跑。
## 验证范围与已知限制
V1.1.2 已完成本机冻结 EXE 验收:两个工程实际替换和独立回读、297 字符工程路径、BOM 失败/成功导入、Part Label 写入 Value、旧版任务数据副本、新轮次和自有后台资源释放。详见[成品验收报告](docs/testing/2026-10-15-packaged-acceptance.md)。
当前按 **evaluation-only(评估试用)** 交付。不同机器、中央库和 CAD 版本仍需用工程副本确认兼容性;替换回读通过不代表已通过 Packager、ERC 或网表检查。
首次采集与 CAD 启动可能需要较长时间,存在已知的偶发 COM 启动阻塞;启动有等待上限和清理机制。本次两工程执行约 4 分 19 秒,不承诺其他工程使用相同时间。长路径兼容已覆盖验证场景,不代表旧 CAD 或中央库支持任意路径。
## 开发与更多资料
源码运行需要 Python 3.12:
```powershell
py -3.12 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -e ".[dev]"
.\.venv\Scripts\python.exe -m dx_productivity.trial_task_center.application
```
源码默认数据目录为 `%LOCALAPPDATA%\DxProductivity\trial-task-center`,可用 `DX_TASK_CENTER_HOME` 指定独立目录。运行回归:`python -m pytest -q`;构建使用 `packaging/Build-DxPartReplace.ps1`。
- [完整桌面使用说明](docs/user/v1.1.0-project-tasks.md)
- [中断核验与恢复](docs/user/interrupted-recovery.md)
- [Value 与属性继承](docs/user/value-copy-and-layout.md)
- [历史流程和独立 CLI 说明](docs/user/trial-task-center.md)
- [CLI 与原生批处理集成](docs/user/part-replacement.md)
- [V1.1.2 版本说明](docs/releases/v1.1.2.md)
@@ -0,0 +1,11 @@
# BOM 真人流程与重复执行
沿用当前 1.1.2 开发版和 11 列模板;用户已授权实现与在副本上实际替换。原 CAD PID 18732、原工程及原始 BOM 不操作;及时提交推送,不打包发布。
1. 导入反馈:提供结构化校验报告,显示总行数、校验通过/失败/未检查行数、工程、Excel 行号和原因。严格原 API 保持拒绝整批部分写入;UI 走报告入口,有错误时不保存或默默执行部分替换,修正后重新导入。
2. 完成任务:显式“开始新一轮”保留旧命令、快照、计划和日志,重置运行状态并清除已过期目标基线,重新采集当前工程再编辑和执行;不解除中断/不确定状态。批规则编辑需兼顾同批仍完成的成员,以明确的新一轮范围保证一致性。
3. 长路径:分别核对证据目录、Excel 路径、实际工程路径;通过真实 WSH 检查和实际 CAD 试验发现限制后修复。身份验证始终使用原始工程身份,运行别名不得让工程串位。
4. 原生真人流程脚本:Qt 弹窗选择创建任务、导出默认模板、修改模板实际单元格、失败导入报告、成功导入预览、保存、点击执行、原生 Replace Part 保存回读;开始新一轮后再次导入与替换;用独立原生读取核对选中与未选中位号,检查私有桌面及自有 CAD 释放。
5. 自动回归覆盖报告、事务、重跑状态和长路径身份;真实验证记录步骤耗时、路径长度、日志、前后器件和截图,报告任何实际限制。
并行所有权:报告代理持有 bom_plan.py/bom_batch.py/new bom_import_report.py/ui/project_plan.py;重跑代理持有 service.py/store reset helper/ui/main_window.py/run_panel.py/execution_state.py;主代理持有路径兼容、VBS 与真实探针,并接入报告服务 API。不得并行启动 CAD。
@@ -0,0 +1,26 @@
# 2026-10-15 全流程审查修复
范围:修复当前审查确认的八项问题,沿用 1.1.2 开发版和现有 11 列 BOM 模板;提交并推送当前开发分支,不打包、不发布。不操作用户原 CAD 进程。
## 约束与决策
- 同批规则通过服务层事务同步到所有未删除成员。任一成员被冻结或已有不可编辑执行证据时,拒绝整个修改,不做部分成功;已有历史分歧须明确报错,避免选中任务决定执行结果。
- 规则是位号计划的默认值。修改规则时仅更新仍与旧默认值一致的新料号、NC;Value 开关和内容作为一组比较并传播,保留用户的手动覆盖与启用选择;界面明确显示实际执行使用位号计划。规则新增可以补全空默认值;删除不清空用户位号计划。历史规则合并后统一检查链式替换及循环;显式编辑或删除冲突规则可以解除历史分歧。
- 位号基线允许执行前添加,既有 UID、位号、旧料号与旧 Value 必须全部仍在且一致。采集时包含既有旧料号,防止以不完整清单掩盖工程变化。预览不落库,确认批量事务后才保存。
- 新 BOM 预览取代重叠的过期范围,同范围保留未重新导入工程的编辑。关闭窗口检查所有任务草稿,提供保存全部、放弃、取消;保存失败保持打开和草稿。
- 回收站使用独立入口,保留搜索、排序、恢复、永久删除,不恢复常驻状态下拉框。
- 原生读取比较基于规范化内容,枚举顺序变化可接受,实际字段变化及重复身份仍拒绝。
- 采集与 BOM 导入共用可取消操作控制,显示每工程进度;取消传至原生启动及监控,等待自有会话安全释放,不保存部分计划。
- 回归额外发现 Windows 临时共享冲突会令工程会话的继续指令读取失败;在 VBS 的继续指令读取处增加有界重试,保留后续 token 和 checkpoint 严格校验。
## 工作项
1. 位号清单扩展与 BOM 事务:`bom_batch.py`、`store_target_plan.py`,针对增量、身份变化、回滚增加回归。
2. 界面草稿、预览、回收站:`ui/project_plan.py`、`ui/main_window.py`、`ui/task_list.py`,含关闭保护和采集取消界面接入。
3. 原生顺序比较、取消:`discovery_cache.py`、`quick_run.py`、`project_discovery.py`、`inventory.py`,保留缓存一致性与私有桌面释放约束。
4. 服务层批规则与默认值传播:`service.py` 与新独立规则模块;服务采集 API 接入取消进度,并扩展采集旧料号范围。
5. 集成回归:针对现有捕获的七工程真实库存复放导入,完整适用测试;审查修复后的变更,分批 Git 提交推送。
接口:`preview_bom_batch` / `preview_batch`、`collect_target_inventory` / preparer 的库存读取使用可选关键字 `stop_event=None, on_progress=None`。`on_progress(message: str)` 仅通知,UI 用线程信号回主线程;取消抛出 `TaskCenterError('operation_cancelled', ...)`。未传控制参数时兼容已有两参数测试替身。
任务交叉:工作项 1 生产库存扩展接口,由 4 调用;1、3 共用取消参数,由 4 接线;2 消费 4 的公开 API。各项代码分别持有,集成时统一检查。
@@ -0,0 +1,12 @@
# 1.1.2 界面与吞吐优化
沿用用户已认可的审查方案;本轮不打包、不发布。
1. 修复 BOM 报告跨批次残留:按导入发起批次存储,切换时恢复,支持折叠摘要。
2. 修复 980×700 长路径场景位号表不可见:路径省略与复制、可调表格/执行区、有限日志高度。
3. 明确当前工程与本批范围,集中 Value 策略、区分自定义内容和实际回读,修正私有桌面说明。
4. 整理操作层级、任务选中态、表格排序和样式;保留默认 BOM 与原位号计划入口。
5. 对千步队列做一次定位分析,优化确认的热点,保留文件身份与不确定状态保护。
6. 按行为运行针对性 Qt/执行回归,复放真实证据副本,记录截图和性能;分批提交并推送。
已验证的 CAD 替换与 Part Label 证据继续有效。UI 和纯队列优化无需重复修改真实工程。
+97
View File
@@ -0,0 +1,97 @@
{
"artifacts": {
"version": "1.1.1",
"code_commit": "7610a0fd86b98733b6e92234ba744ca5bcfc88d4",
"build_checks": {
"passed": 219,
"seconds": 34.87
},
"exe_sha256": "f029d60fe808c7b5eb47adf9795d4733faa66f33c3f6e9f779fc2541268d1c70",
"vbs_sha256": "212857251e3f42347720b21520836035fa467635ef47f4ca3f330f04cc5a2480",
"private_cad_helper_probe": {
"passed": true,
"project_opened": false,
"clean_released": true
},
"zip_sha256": "f42f656974cb5170dc4ed80a3e9eaabdedae45ecee229da46a57a178d867e532",
"zip_bytes": 52514265,
"file_count": 235,
"unpacked_bytes": 128586142
},
"packaged_helpers": {
"passed": true,
"commands": [
{
"action": "probe",
"executable": "F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\dist\\DxPartReplace\\DxPartReplace.exe"
},
{
"action": "quit",
"executable": "F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\dist\\DxPartReplace\\DxPartReplace.exe"
}
],
"session": {
"desktop": "dx-258535e794ca41598c912ae87fcdf92b",
"token": "258535e794ca41598c912ae87fcdf92b",
"state": "released",
"cad_pid": 52248,
"guid": "{449B3896xE3A2x469Ax9AEExE68DD21C4B67}",
"startup_seconds": 31.484000000025844,
"clean": true,
"shutdown_seconds": 4.60999999998603
},
"source_path_removed_from_child": true,
"project_opened": false
},
"desktop_observation": {
"samples": 166,
"file_read_samples": 166,
"input_desktop_before": "Default",
"input_desktop_after": "Default",
"foreground_pids": [
10104,
13256
],
"owned_cad_became_foreground": false,
"owned_cad_on_input_desktop": false,
"baseline_default_cad_pids": [
18732
],
"observed_default_cad_pids": [
18732
],
"cad_exit_confirmed": {
"52248": true
},
"desktop_absent": {
"dx-258535e794ca41598c912ae87fcdf92b": true
},
"sessions": {
"dx-258535e794ca41598c912ae87fcdf92b": {
"desktop": "dx-258535e794ca41598c912ae87fcdf92b",
"token": "258535e794ca41598c912ae87fcdf92b",
"state": "released",
"cad_pid": 52248,
"guid": "{449B3896xE3A2x469Ax9AEExE68DD21C4B67}",
"startup_seconds": 31.484000000025844,
"clean": true,
"shutdown_seconds": 4.60999999998603,
"evidence_path": "data\\tasks\\packaged\\quick-run\\private-desktop.json"
}
},
"observer_errors": []
},
"extracted_zip_smoke": {
"extracted_zip_smoke": true,
"version": "1.1.1",
"exit_code": 0,
"missing_helper_arguments_exit_code": 2,
"data_directory_excluded_from_archive": true,
"log": "2026-10-15T05:34:36Z INFO dx_productivity.trial_task_center.f2619d17fd50a1f1 logging configured root=F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\build\\release-1.1.1-smoke-data application_log=F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\build\\release-1.1.1-smoke-data\\logs\\application.log\n2026-10-15T05:34:36Z INFO dx_productivity.trial_task_center.f2619d17fd50a1f1 application_start version=1.1.1 executable=F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\build\\release-1.1.1-extracted\\DxPartReplace\\DxPartReplace.exe os=Windows-11-10.0.26200-SP0 data_root=F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\build\\release-1.1.1-smoke-data database=F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\build\\release-1.1.1-smoke-data\\task-center.db application_log=F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\build\\release-1.1.1-smoke-data\\logs\\application.log\n2026-10-15T05:34:36Z INFO dx_productivity.trial_task_center.f2619d17fd50a1f1 recovered_interrupted_projects=none\n2026-10-15T05:34:37Z INFO dx_productivity.trial_task_center.f2619d17fd50a1f1 operation_start=list_tasks task_id= at=2026-10-15T13:34:37.043664\n2026-10-15T05:34:37Z INFO dx_productivity.trial_task_center.f2619d17fd50a1f1 operation_complete=list_tasks task_id= at=2026-10-15T13:34:37.047016\n2026-10-15T05:34:37Z INFO dx_productivity.trial_task_center.f2619d17fd50a1f1 application_clean_shutdown exit_code=0\n"
},
"pre_release_fixes": [
"Absolute package import for an application executed as the frozen entry script; regression reproduced before the fix.",
"Bounded atomic state publication retry for Windows readers denying delete access; native transient and persistent sharing tests added."
],
"validation_boundary": "Real packaged EXE probe/quit helpers launched by the source supervisor; no project opened in this package smoke. Previous real replacement evidence is linked in the release notes. No new Packager/ERC qualification."
}
+24
View File
@@ -0,0 +1,24 @@
# 1.1.1 发布构建记录
日期:2026-10-15。程序源码提交:`7610a0fd86b98733b6e92234ba744ca5bcfc88d4`;后续发布文档及探针提交不改变成品程序代码。
- 标准构建脚本发布检查:219 passed,34.87 秒;没有跳过或放宽构建门槛。
- PyInstaller 6.22.3 / Python 3.12.10 构建成功;构建自带的独立启动退出检查通过。
- ZIP 解压到全新目录后,EXE 启动日志为 version=1.1.1,正常退出码 0;helper 缺少必要参数时退出码 2。
- 成品 EXE 的真实后台 CAD probe/quit 通过,子进程移除源码 PYTHONPATH,没有打开工程;CAD 与桌面确认释放,主桌面没有被切换或抢占。
- 本次私有 CAD 启动 31.484 秒,退出 4.610 秒;166 次主桌面采样和普通文件读取均完成。
- ZIP CRC、文件清单、EXE 哈希及包内 VBS 与源码哈希一致性检查通过;包内不含 data、任务数据库、日志或工程备份。
产物:`dist/DxPartReplace-1.1.1.zip`,52,514,265 字节(50.08 MiB),235 个文件。
| 文件 | SHA-256 |
| --- | --- |
| ZIP | `f42f656974cb5170dc4ed80a3e9eaabdedae45ecee229da46a57a178d867e532` |
| EXE | `f029d60fe808c7b5eb47adf9795d4733faa66f33c3f6e9f779fc2541268d1c70` |
| QuickPartReplace.vbs | `212857251e3f42347720b21520836035fa467635ef47f4ca3f330f04cc5a2480` |
源码、验证探针和记录推送至 `codex/execution-responsiveness`,版本标签 `v1.1.1`。发行附件为 ZIP 与 `SHA256SUMS-1.1.1.txt`,发布页:[DxPartReplace 1.1.1](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/releases/tag/v1.1.1)。附件上传后另行下载验证 SHA-256。
本次发版过程中复现并修复了两项:冻结脚本入口的相对导入失败,以及状态读者短暂占用导致 Windows 原子替换失败。第一轮成品 helper 实际已退出 CAD、释放桌面,但最终状态记录因占用失败;修复后重新运行标准构建与成品探针通过。
详细证据见 [JSON](v1.1.1-build.json)。本轮成品验证由源码监督器调用实际 EXE 的 probe/quit 入口,不代表又执行了成品整批替换。此前真实替换、恢复及异常清理证据见 [后端验证记录](../testing/2026-10-15-private-desktop-execution.md),没有新增 Packager/ERC 认证。
+31
View File
@@ -0,0 +1,31 @@
# DxPartReplace 1.1.1
发布日期:2026-10-15。
本版包含按工程创建任务、位号计划、可选 BOM/Excel 导入、任务顺序执行,以及后台 CAD 执行与完整退出清理。
## 更新内容
- 自动采集、替换和中断恢复默认使用私有桌面中的自有 CAD,主桌面可继续查看其他文件。
- 完成、暂停和异常退出均检查自有进程及桌面释放;记录每次后台会话证据。
- 单步替换同样执行备份、保存、关闭与重开核验;恢复成功后无需另行手动保存。
- 界面显示后台 CAD 启动及退出阶段,保留位号、旧新物料号、执行阶段耗时和速率记录。
- 保留同一工程的连续步骤会话复用、异步查询及取消、工程发现缓存等优化。
- 修复冻结程序后台 helper 的脚本入口导入错误,版本号更新为 1.1.1。
- 后台状态文件遇到短暂的 Windows 读取占用时进行有限重试,持续权限错误仍会明确报告。
## 下载与使用
下载 `DxPartReplace-1.1.1.zip` 并完整解压,运行 `DxPartReplace/DxPartReplace.exe`。保留同目录的 `_internal`,不能只复制 EXE。无需另外安装 Python,仍需本机可用的 DxDesigner EE 7.9.5、许可证和中央库。
升级前关闭旧工具并备份原 `data`;更新 EXE 和 `_internal`,保留原有 `data`。新包不含本机任务、日志或工程备份,不同版本不要同时使用同一数据目录。
目标工程开始前须保存关闭,运行时不要同时打开或修改它。其他工程不会被接管。后台 CAD 启动实测约 22~35 秒,许可证和系统资源仍共享。
`SHA256SUMS-1.1.1.txt` 提供 ZIP 的 SHA-256。便携目录同时包含使用说明和版本清单。
## 验证范围
发布构建运行功能和执行保护检查,再执行 PyInstaller 构建及独立 EXE 启动退出检查。成品另执行实际私有 CAD probe/quit 验证,不依赖源码 PYTHONPATH;确认主桌面不切换、自有 CAD 退出、私有桌面释放。发布记录保存测试结果、ZIP/EXE/脚本哈希及验证证据。
原生替换、保存回读、恢复、暂停和超时证据见 [私有桌面执行验证](../testing/2026-10-15-private-desktop-execution.md)。本次成品验证没有重新进行整批替换或 Packager/ERC 验收;现有现场验收边界不变。
+261
View File
@@ -0,0 +1,261 @@
{
"version": "1.1.2",
"release_date": "2026-10-16",
"release_tag": "v1.1.2",
"classification": "evaluation-only",
"code_commit": "a16914bc7221dbc62c467b7a89e06ab0c40c1fbc",
"accepted_exe_sha256": "73d6deb81d52ce34ce9c6d2958275a9b7376f316ae1872552882f0d65070ce75",
"exe_sha256": "73d6deb81d52ce34ce9c6d2958275a9b7376f316ae1872552882f0d65070ce75",
"vbs_sha256": "9997d8a41ad3820e7fd905c8024fc10c765c0e6218eb7f3c091301e3c73db9dc",
"program_files": {
"DxPartReplace.exe": "73d6deb81d52ce34ce9c6d2958275a9b7376f316ae1872552882f0d65070ce75",
"_internal/api-ms-win-core-console-l1-1-0.dll": "015bd08815c7b934a8952c3a7578e9ce59f21136e8a880d42bbd414bec2c6058",
"_internal/api-ms-win-core-datetime-l1-1-0.dll": "5534812cdbdae94ba45cb216e5eb9af686b853948df54365103555abbbaf9d9a",
"_internal/api-ms-win-core-debug-l1-1-0.dll": "837d2b1b2cd03e03fc6ccb050698b6b5763af17c201304872342a5eae9e0a2d2",
"_internal/api-ms-win-core-errorhandling-l1-1-0.dll": "de43b165f568c276c00e95acd454e3092f352a18e95874595f4f4658c06d2ec7",
"_internal/api-ms-win-core-fibers-l1-1-0.dll": "3cebc45bf479ad74cfabf2c6bfd4994d7ad639ed1221025981d19cedf9ce0416",
"_internal/api-ms-win-core-fibers-l1-1-1.dll": "5ef70308bcca628ce6b0e2856b15b1c7ae340c3f9bbbc4c1071d8c191a34a5c3",
"_internal/api-ms-win-core-file-l1-1-0.dll": "250ac829f2617bcac1c6e5b8c4f630462e20765863ba573526a3e11bbfb94a9a",
"_internal/api-ms-win-core-file-l1-2-0.dll": "ae14079a114733f60ce87b92cba42acd8083c2cd67594e53bc37dc0b97a4b465",
"_internal/api-ms-win-core-file-l2-1-0.dll": "914bf26a298713119477ea0a8e7bd43171b91344ebe24fb47ad77c49686e3d87",
"_internal/api-ms-win-core-handle-l1-1-0.dll": "ab5489955e371b15f77906c08ec3c7affe2c7a46a08c514ca628768b4478974b",
"_internal/api-ms-win-core-heap-l1-1-0.dll": "c70f9644d8377fa39c5b71f2e9734c1400d7598904fdeb772e8502099982dcb7",
"_internal/api-ms-win-core-interlocked-l1-1-0.dll": "f8129710188e407bb0e6f46d30aeba277d67b947ece5fe09e883fde2323f3ae6",
"_internal/api-ms-win-core-kernel32-legacy-l1-1-1.dll": "5200b16cb2ddc61cfc07373a9a84aa85a3ab50806ca96c879c883275832944c1",
"_internal/api-ms-win-core-libraryloader-l1-1-0.dll": "48786fb88b001dcd1f63acea903d3ca9cc0b3060d5a325e3f2f3cbc3bfd53166",
"_internal/api-ms-win-core-localization-l1-2-0.dll": "9ec3898f7eba91faa28b51616c211a2689e3a13aeef8de6e13cb674e49d689eb",
"_internal/api-ms-win-core-memory-l1-1-0.dll": "3a6cbc524c99e1cd80d5368f5601402a37ad602528b1ab628093573ef638eb3b",
"_internal/api-ms-win-core-namedpipe-l1-1-0.dll": "97145ef89c44949fcf0f04ac834a8bc7d687ef49ee73ae9fc32f3c11136b7201",
"_internal/api-ms-win-core-processenvironment-l1-1-0.dll": "8bc7c10b1851aea644e9c9f381cdb935e091fee6b0be3d3aedc6fffaac96adb7",
"_internal/api-ms-win-core-processthreads-l1-1-0.dll": "d8030b777617c71f0f94564607699dbf7561487d779db9756aed378c5675213f",
"_internal/api-ms-win-core-processthreads-l1-1-1.dll": "f5e676713340f73a03a3d41a6ec9883b431da7d16c7f07bd0a920fb80e6c0753",
"_internal/api-ms-win-core-profile-l1-1-0.dll": "f023d47e44d3eea6b0743580f57e8c6ba81e79d5ebfa7da26250076c647b980e",
"_internal/api-ms-win-core-rtlsupport-l1-1-0.dll": "9746d8930704153578a628c010638a5f818ffe5a927e25591b108e256dc6afca",
"_internal/api-ms-win-core-string-l1-1-0.dll": "7c53ae24c982d16ffd1bf7f918d115b11b7f30e57bc7feaa18cb9781e4abb926",
"_internal/api-ms-win-core-synch-l1-1-0.dll": "56d9d62ca5dba79a6581b8d574a7d8b2a64a5ecb71e47dcf06ed0285708b1859",
"_internal/api-ms-win-core-synch-l1-2-0.dll": "f6482bbec5612c39ecb4822787a333f2b7570f7a5f922a4059be41ba957bb372",
"_internal/api-ms-win-core-sysinfo-l1-1-0.dll": "272d02765fdd3582618236c2d309abba069642f9bc1062ede069d0c144e17007",
"_internal/api-ms-win-core-sysinfo-l1-2-0.dll": "8a0900788859d0eb51c2f48f50cc6ed376a120b518100fa20e11d7702ccde260",
"_internal/api-ms-win-core-timezone-l1-1-0.dll": "ff35de6c03812b332e140f17dade25c5dd4775156da9eeb1eaae3fddd27236ec",
"_internal/api-ms-win-core-util-l1-1-0.dll": "191ef3e98641a57296f19d572d8eb62489470ff1ef6030d136af170c2f835173",
"_internal/api-ms-win-crt-conio-l1-1-0.dll": "54ee5ec719a051496ff60aa00dbeaa94b9a7d2cdac27fe9b7317f1a666b6a2aa",
"_internal/api-ms-win-crt-convert-l1-1-0.dll": "8b94662429171019fcd63c70bbf2095a075170599704a5e7dcdbe3da13f3a429",
"_internal/api-ms-win-crt-environment-l1-1-0.dll": "39e5929593709e8af3bc9e0a75ec1155778d6f4a247f4cdfc58928ad6db88434",
"_internal/api-ms-win-crt-filesystem-l1-1-0.dll": "5a8ecebac32edf4e1f3c5c6c1c8ea1a1add6cda4f9c9cb26f752fb295bea6865",
"_internal/api-ms-win-crt-heap-l1-1-0.dll": "c71080cbcb43bf1f8f3e391deb12a582eb0abefc80946f340675a2c616e4feb4",
"_internal/api-ms-win-crt-locale-l1-1-0.dll": "6c68648e524187e03c4ad9aaa4a99113c6ee9f29fb39cc0ed93f951975138e63",
"_internal/api-ms-win-crt-math-l1-1-0.dll": "d4fbcccbe29371cbce431e43b2eb4f7ba9a6f04a3d740a071f02457a505e9dc8",
"_internal/api-ms-win-crt-process-l1-1-0.dll": "47c1935942e3ac0812e4dcf18c0e265e565f0194a3349111c299712f5565f7ac",
"_internal/api-ms-win-crt-runtime-l1-1-0.dll": "72adc1b3677e0814d9c4ebf0964000e84bb2acf67336c8963061665e44f78029",
"_internal/api-ms-win-crt-stdio-l1-1-0.dll": "900afc3989673c9bb1a687ed38c192f46db9e6ba6d11a668898a539e7fc23798",
"_internal/api-ms-win-crt-string-l1-1-0.dll": "fcf12466cc12fd3b73611fc0763a5a1f9d44e90349513c34a0c83b0f36421793",
"_internal/api-ms-win-crt-time-l1-1-0.dll": "886e57c4a6adb299b38f02945369f590a67da4e79a798359fc60aaa067212d7c",
"_internal/api-ms-win-crt-utility-l1-1-0.dll": "5f8f26b216ade615b67a41f6fbbb910972fc6153315a65bb8f09912be50215b1",
"_internal/base_library.zip": "9524f278655c7799933d381bbcf061bcf5961e8541460c279083ae1c61da277b",
"_internal/libcrypto-3-x64.dll": "deabf96c676dd3652b32da2cb38a7dcc2f2daa8197ad19aba3c7a99454933c1e",
"_internal/libcrypto-3.dll": "ccfffddcd3defb8d899026298af9af43bc186130f8483d77e97c93233d5f27d7",
"_internal/libffi-8.dll": "eff52743773eb550fcc6ce3efc37c85724502233b6b002a35496d828bd7b280a",
"_internal/libssl-3-x64.dll": "e84dcc3caca7720b2b426cb408df3129406e3b4d4ce4e729632bab319013ef6c",
"_internal/libssl-3.dll": "007142039f04d04e0ed607bda53de095e5bc6a8a10d26ecedde94ea7d2d7eefe",
"_internal/pyexpat.pyd": "d615e193d1affcdbfe504e90d3621cbdcff94bf72b79d899126534507fd6d27a",
"_internal/python3.dll": "fb975a606e7fbf74f64260e3f60c3490b4f74a183c0926fd6ed1ac4c52ac7b1c",
"_internal/python312.dll": "9a0e3435aaa680d868150f87ab3e388ad2eebc22f87e036155c7b4eda8cd2120",
"_internal/select.pyd": "d4d7181b11db0bd22a6cd5cda6f8583d1f5c77615fd0a6ca33350619d6e0438a",
"_internal/sqlite3.dll": "8daa45684bf6688fca28d956b2e8942f2fa98f656675ce68e6d61dd869848a7a",
"_internal/ucrtbase.dll": "3239227d27667ba20d10a880751924e5719de0078f9fce232d149d383f7681f6",
"_internal/unicodedata.pyd": "208ee1cd3cbad0828433ca7246b05be2b1ff5569983d27d296c0b38888585488",
"_internal/VCRUNTIME140.dll": "052ad6a20d375957e82aa6a3c441ea548d89be0981516ca7eb306e063d5027f4",
"_internal/VCRUNTIME140_1.dll": "6a99bc0128e0c7d6cbbf615fcc26909565e17d4ca3451b97f8987f9c6acbc6c8",
"_internal/_bz2.pyd": "65f610646d10d5babea080e060d244b546ec52c54012e5e937dc72dcc2e2e7bc",
"_internal/_ctypes.pyd": "0e56107a891100535f2da79d85a5ae65ff1227b4765bd108f8593ac1a1110d81",
"_internal/_decimal.pyd": "aeacfead2befcc0768063a037bb64bd32109ae09cb144e5f571b04dd7965db9d",
"_internal/_elementtree.pyd": "5009a9a53c03ef8387443b5cf6ce08e5c3a79727466a0b931c5bbca915bf89ca",
"_internal/_hashlib.pyd": "03d233dbace599168eaffec823de6ed7beec8c2a4ebfe9b8a3d8e042a59af3ba",
"_internal/_lzma.pyd": "e3deecc1f59a3b811c608861decd84de1e8df8bafd5e2b39188861318c5a38cf",
"_internal/_multiprocessing.pyd": "2c636df7059cb0dd7e978dd735c7c5c8ddb09cf94754cf9e232296b96c5c545a",
"_internal/_queue.pyd": "48e76e0ad63f6932b4a77b5819f41c1e7595636ca8d9e824f0943a14b8bb5035",
"_internal/_socket.pyd": "3efa4636cf9e350856f6927d67a4c2564bf9bd2758a00bbf17d3aece5b60016d",
"_internal/_sqlite3.pyd": "64b51df2805c58b023a875e8ae3be7ac7f61ef664f32ca6c90f6315da47ef0bc",
"_internal/_ssl.pyd": "0bc527d2dbc50009f43b2ed5d5982c4f63f4b647647ffa9eda612dcda80f6040",
"_internal/_uuid.pyd": "acce4f281d7ffb2dec0997527faf25b1df62ad7bd3032c568ddcf65c90edc867",
"_internal/_wmi.pyd": "a980f1e7a29842bd946863fc2693fbeb555a9dc0f9e1630dfed9a2fcdef3ece2",
"_internal/PIL/_avif.cp312-win_amd64.pyd": "6731dce52baab0b96b0eeb3c664844b5b42c2168ea8668af2430e2fbdd2dfbd8",
"_internal/PIL/_imaging.cp312-win_amd64.pyd": "c8c519ec72bf75b2945b4fc4afa854af2fca8b970a403134f9ddda3e164d85e9",
"_internal/PIL/_imagingcms.cp312-win_amd64.pyd": "c89c633ae1bf3f26a327d14ff688db66628e19c9866ab925479f27dcb60a2d6f",
"_internal/PIL/_imagingmath.cp312-win_amd64.pyd": "82ac45c41a008854d05f67deda298b65a7bed850d0d79a3af861ed583f6e7d62",
"_internal/PIL/_imagingtk.cp312-win_amd64.pyd": "690cc1cae4a2dc8594a342b9241e691dcc89d81dad4cddcefdf285275365a2b1",
"_internal/PIL/_webp.cp312-win_amd64.pyd": "9823cebb84f425af3ac1e7437259bc176e7ad7e25d7fa829b0e1a3e55c11be70",
"_internal/PySide6/MSVCP140.dll": "4c667b706893593812cd111b369ba6a77f54d1f1b1ae87cf3bf37692663cfba2",
"_internal/PySide6/MSVCP140_1.dll": "d419d24b0a76366f5c9d908b0e45fe70e9e9154bb8ad5f3de42070f2337f857b",
"_internal/PySide6/MSVCP140_2.dll": "89917964abb6ca16a260cab258e180c3abc239b5af00eed659d0edf0efdd339c",
"_internal/PySide6/opengl32sw.dll": "34b444c016289b560662ff896deceb7f4b2c0723aed3d319ae167c9186ce42b3",
"_internal/PySide6/pyside6.abi3.dll": "d0b5c701fb3a8ea839e72b602058f3960935156ebeca084893c54c99e54dd707",
"_internal/PySide6/Qt6Core.dll": "d6a3c37c5263c5d418fc0e80b722bc9fca7c0859e6f635f9624a2fde00bdc653",
"_internal/PySide6/Qt6Gui.dll": "ae29b005f51b6850bf57fa06fced0dc8c7039fd6fafc3bfbcfe76e38adc7abf1",
"_internal/PySide6/Qt6Network.dll": "dd3512d1c5ed062d30c98426cd0a850f13e0cf31437afb5b0b474132b9c52922",
"_internal/PySide6/Qt6OpenGL.dll": "d51088f16db8c96dba7ef3c1474e611adb3ebdb211fea35b8e755d2a7407f7ad",
"_internal/PySide6/Qt6Svg.dll": "1eac8f7415b311a88cb3cb4e25c3098d0e059c24c831fbbb13f43a80f0df06b7",
"_internal/PySide6/Qt6VirtualKeyboard.dll": "a14fac89759569965dbeb45b2a13e592c0bce0cc559adaa32145fcb92de016f9",
"_internal/PySide6/Qt6Widgets.dll": "ff0df9e2e6827e035f0731a4cedfc6333f4602bca00775e56346f27032406b74",
"_internal/PySide6/QtCore.pyd": "74f96322c5e9cea73aefd2ed5870e5275336b31f552fcd32f12fc81d23f1bc6f",
"_internal/PySide6/QtGui.pyd": "7bef20046045199c037b7cbfedaa1c5464730fa948b2c9ec8afbf718e63774d4",
"_internal/PySide6/QtNetwork.pyd": "c5038bb71fc9d57330fa2d8eeec65aab69fcf02687cc8f54dbfb5995cfec6a71",
"_internal/PySide6/QtWidgets.pyd": "f12f4ca641998e5706d5f7b0023147d573f0f2d2361e26dadf31bdbf05fbfd1d",
"_internal/PySide6/VCRUNTIME140.dll": "f893ae75a1a24eea174d982f94bc80ce2448201eaa919a73c0653a5657685de4",
"_internal/PySide6/VCRUNTIME140_1.dll": "48aa2783793ea18ab3c2c71d420d4fff9814e662a1ff810053c6e5250061a716",
"_internal/pythonwin/win32ui.pyd": "1fc9f8875056b175077ed04e7d93599f58b3cff80bd2077f5f8c8aaa144ab833",
"_internal/pywin32_system32/pythoncom312.dll": "18e5d69b62110f48da01842f9ddfd99d06cc561f0866371714ec6534fcb4e5ec",
"_internal/pywin32_system32/pywintypes312.dll": "9bd7f8c39a84d7b1ea43bfcd33c04631c60f4ff28167e82bb21987cc1c353766",
"_internal/shiboken6/MSVCP140.dll": "fd4a8c046fa3fea9ca6132f50cf8a56cf1e783b2d3093ba5c85fa063bc6b3845",
"_internal/shiboken6/Shiboken.pyd": "2f6f3a694f675b1dafdae26903191613c02866ab48e02591ae34ca1a3b1284f1",
"_internal/shiboken6/shiboken6.abi3.dll": "de3c6b2ed5f75c9ac0de4a6844b653b3b9d09263ce68c2b5fc25a96c5c3e8469",
"_internal/shiboken6/VCRUNTIME140.dll": "de617641d82eac15595d2e39394163ac33e49bb032cf2c2ea0044ed39d3675e9",
"_internal/shiboken6/VCRUNTIME140_1.dll": "fa577d54bd10a91e52472da784a619da6cf241af45f0a0c48b27e91fa0fe6104",
"_internal/win32/win32api.pyd": "8e09d7aa57dc33b663afd219fab21b6a70e9d98cc74a044df4d6cd94799d98c2",
"_internal/win32/win32event.pyd": "a6b896456443447a663fe25783dfa95929dc8ade8d7970fd78d3b4e65100371e",
"_internal/win32/win32evtlog.pyd": "f6f8814147d3ca2761d351c0c86e7142b15b63605a502e5eb62d0bbd2b88e73f",
"_internal/win32/win32file.pyd": "359ef2dc11546f619a9ac53c01a399d621c093b7cfc843fb9d7b211d0b15e103",
"_internal/win32/win32gui.pyd": "f468a03be44633fdeabc08b4a9f8b135f9e31d74b935f85631c23c7fbb9367fa",
"_internal/win32/win32job.pyd": "bfc31798ccf0bcf9b4453903918866abcfb546f5b1d6bd59e4691b83cbe44fa8",
"_internal/win32/win32process.pyd": "6d02ff9b22afa97bdb26d99454462a612848efdc3d0beb54cea2b4912d07a14c",
"_internal/win32/win32service.pyd": "5d159572b89146a13117f24ef0b232d6c24982d206c73189f4952259303de496",
"_internal/win32/win32trace.pyd": "3dd640518a4fb1084cfc38a0e312b87ff1b0b0a74535e320bb9936441b9ed8ca",
"_internal/win32/_win32sysloader.pyd": "db277aae2b8417dbd01435a8691cc74707f6699ae3199e1b205f609cefa5ad24",
"_internal/legacy-runtime/dxdesigner795/QuickPartReplace.vbs": "9997d8a41ad3820e7fd905c8024fc10c765c0e6218eb7f3c091301e3c73db9dc",
"_internal/PySide6/translations/qtbase_ar.qm": "e03fe68d83201543698fd7fe267dd5dfc5bfd195147e74ff2f19ac3491401263",
"_internal/PySide6/translations/qtbase_bg.qm": "e448ac9e3f16c29eb27af3012efe21052daa78fabfb34cd6dff2f69ee3bd3cdb",
"_internal/PySide6/translations/qtbase_ca.qm": "5298532fc52ffbc4e2c549f277151a61e741921c834286f7c04d3753677b6b04",
"_internal/PySide6/translations/qtbase_cs.qm": "03028b42df5479270371e4c3bdc7df2f56cbbe6dda956a2864ac6f6415861fe8",
"_internal/PySide6/translations/qtbase_da.qm": "7d1e5ca3310b54d104c19bf2abd402b38e584e87039a70e153c4a9af74b25c22",
"_internal/PySide6/translations/qtbase_de.qm": "ed828a83dfaa51944f166c842155b48ab3bd7cb2c46dcd96269eb5d48af4f63f",
"_internal/PySide6/translations/qtbase_en.qm": "494ac9a2b2cb2fdeced353f4a9f898ed8dcf616e9bc667438c62681e3f7f79cf",
"_internal/PySide6/translations/qtbase_es.qm": "4ffda56ba3bb5414ab0482d1dde64a6f226e3488f6b7f3f11a150e01f53fa4c8",
"_internal/PySide6/translations/qtbase_fa.qm": "f78e59b5bdd586181a999034ba418868ed17fe9c05707fb65e523f70e92253d2",
"_internal/PySide6/translations/qtbase_fi.qm": "e47fe13713e184d07fa4495dde0c589b0e8f562e91574a3558a9363443a4fa72",
"_internal/PySide6/translations/qtbase_fr.qm": "314243a55c32679ad473fdfe48dc7d66e973ad0fc8bf2164480c58dddb50c1a7",
"_internal/PySide6/translations/qtbase_gd.qm": "63b439dd44139aa3aed54c2ebe03fa9bc77f22c14ed8fba8eff2608445bb233d",
"_internal/PySide6/translations/qtbase_he.qm": "e1ebca16afe8994356f81ca007fbdb9ddf865842010fe908923d873b687cad3f",
"_internal/PySide6/translations/qtbase_hr.qm": "bb9eec9a9a652c1340dc75eb2e749be50df00f885b3d6900dfc76799c45b244d",
"_internal/PySide6/translations/qtbase_hu.qm": "98463295539d769c8645a0b7fb95ad38454cfd0b14f36af485513f036ddbbbc6",
"_internal/PySide6/translations/qtbase_it.qm": "7808ed542a7833c4bd94ec8bdfbbca00bb4f2fe15979b9121ce3249323687300",
"_internal/PySide6/translations/qtbase_ja.qm": "2b9581c69b975f59be505b127cd3c19d403ef3d12e0e8386fb97238223e9c1df",
"_internal/PySide6/translations/qtbase_ka.qm": "e55e4b72fa620bebee5297ca59dfe2f49894a1e544f2b7485b1cfd8829289d6f",
"_internal/PySide6/translations/qtbase_ko.qm": "0179ed1b136e1cb3f583351eaa2c545ba3d83a6ee3f82c32505926a1a5f5f183",
"_internal/PySide6/translations/qtbase_lg.qm": "31c0cc4ce13b1d74fe0c19ed0b47638fb31e20c93ee08092533e884007aebfb5",
"_internal/PySide6/translations/qtbase_lv.qm": "846e047573ae40c83671c3ba7f73e27efc24b98c82701da0df9973e574178bb2",
"_internal/PySide6/translations/qtbase_nl.qm": "f61513bcdbb6ad800585f9437a95d018aab17fa12ee414aa31462ff279d8240e",
"_internal/PySide6/translations/qtbase_nn.qm": "f9f2fb7c60e7fcb38bbd3c1314ef122145594265e20b0659ff00004baab13ac7",
"_internal/PySide6/translations/qtbase_pl.qm": "3cf6b5c14d5eb0cf81e9af2066e66b3aa579a6b9b3c323ed670761f6254a8c54",
"_internal/PySide6/translations/qtbase_pt_BR.qm": "3475d61604b938d459949801a906dbd34a8ca824ade94120015d676e208da859",
"_internal/PySide6/translations/qtbase_ru.qm": "3da6605668f9178d11a838c4515478084dcfb4f9cf22f99d7a92b492db9c224b",
"_internal/PySide6/translations/qtbase_sk.qm": "d586ae2c314074cf398417fdecb40709d5478dfeb0a67c2fe60d509ee9b59ed7",
"_internal/PySide6/translations/qtbase_sv.qm": "5a2178dd2c03cc4516697f1fb0049649c9ed53f5cde6b937786733dae06aeda8",
"_internal/PySide6/translations/qtbase_tr.qm": "353fdfd7165659a49212e7a25bf91c0a71588e52c836f7496640f26782414634",
"_internal/PySide6/translations/qtbase_uk.qm": "51b8ff55b37dc5907d637a8ddda12fbe816852b0244c74eb4f0fb84867a786e0",
"_internal/PySide6/translations/qtbase_zh_CN.qm": "0481a9b92a6f0578400e960a7d5ee70217a6a450eaf7f98b7d32b8dbd0d58616",
"_internal/PySide6/translations/qtbase_zh_TW.qm": "21012b2b427f8d09d31ce9cae582ca27955b478ca3dc2ec18a3068d808638c6a",
"_internal/PySide6/translations/qt_ar.qm": "b11333c520ccd8e375cde20985df402d586a1a95e0796313bbeb9f717d4db22e",
"_internal/PySide6/translations/qt_bg.qm": "1e22ee126ec9f76031d880285a907b3a0c4510392319ff700dcdee964abbb1ad",
"_internal/PySide6/translations/qt_ca.qm": "17ab2623c7f6e8def44b3dbcb517544185817d65f1298ddb10ef71136f232bdc",
"_internal/PySide6/translations/qt_cs.qm": "c585918fb1d4821a054ea40bdcf279f275ca76c88a5793f433dac6a611ac7e8f",
"_internal/PySide6/translations/qt_da.qm": "f6773c672acb73fdef6e092060d69d1e5dfee840012bac912d1e92de28714386",
"_internal/PySide6/translations/qt_de.qm": "0401c316aa3b50a172eb44a4ff1ec384924073beec7c928ef888ec48e4612688",
"_internal/PySide6/translations/qt_en.qm": "494ac9a2b2cb2fdeced353f4a9f898ed8dcf616e9bc667438c62681e3f7f79cf",
"_internal/PySide6/translations/qt_es.qm": "648ed4519bc45d7a4779479a7626ea16cf9aa23e93a0b178546cc47bea0591ab",
"_internal/PySide6/translations/qt_fa.qm": "3f4c989c6b2990d80cc6299408214b31698923b52f154483b3371875de91f88e",
"_internal/PySide6/translations/qt_fi.qm": "342d01c7eeb234e431d0506821c4cd03c0433115d8d63fee3357be2331858879",
"_internal/PySide6/translations/qt_fr.qm": "c896a38892a92346b033793d56440993236b23e47e06f3974afdb0552f628387",
"_internal/PySide6/translations/qt_gd.qm": "49df855a004a17950338af3146466f6df4d5852410bd0b58ea80e0d0203a9d24",
"_internal/PySide6/translations/qt_gl.qm": "204a01ac7deb6b5bae193afecbd1e50d18c73bf7d94badeb2bbfdf6123c4ed93",
"_internal/PySide6/translations/qt_he.qm": "36f01fff2f25e116d4b7af78097b7e49520fd5b7fb6fb120e40be228c05c045f",
"_internal/PySide6/translations/qt_help_ar.qm": "222088c9752d1cc3bab985ef2dc77e5ae78578dce18a61ec15b39f02e588163d",
"_internal/PySide6/translations/qt_help_bg.qm": "cbcdd1e0bbae332d80ddb0a286056f17c824fa28d353d7fdf12fc97d9f6fe054",
"_internal/PySide6/translations/qt_help_ca.qm": "fe40962c814a9f489e18d033e4aaabe435232c9bcf760830c6165af507cca80e",
"_internal/PySide6/translations/qt_help_cs.qm": "4ac56fc63e400943bab13f1d4c418502138908e1d488c24aee6131d3d17552aa",
"_internal/PySide6/translations/qt_help_da.qm": "6bb092552a398687119f6d52145f04bf8373977446d8f00c0dcbd56b96829f0f",
"_internal/PySide6/translations/qt_help_de.qm": "037bc99abf98571ae9375c2513536c15b571d66406c36c1de447b547ff539c07",
"_internal/PySide6/translations/qt_help_en.qm": "494ac9a2b2cb2fdeced353f4a9f898ed8dcf616e9bc667438c62681e3f7f79cf",
"_internal/PySide6/translations/qt_help_es.qm": "fd16b279f8cf69077f75e94d90c9c07a2afff3948a579e3789f5ffb5e5f4202d",
"_internal/PySide6/translations/qt_help_fr.qm": "875ee2dcdc64e3dea888d84048e382d3921a175f12847de2e6b1cb12ad9add50",
"_internal/PySide6/translations/qt_help_gl.qm": "7399a248609974773f60866c87b78ea7dfbc4f750313d692f7886cd763883c9f",
"_internal/PySide6/translations/qt_help_hr.qm": "8c8cc3c5b1ab2b074f82937001b896603420ef75592b3b78172177360dd7ea61",
"_internal/PySide6/translations/qt_help_hu.qm": "7be32e015119c969453abb6e8f3fb377963a69fafb10c27b796737b5eb283eaf",
"_internal/PySide6/translations/qt_help_it.qm": "316fe8d0815e2b4b396895beb38ef1a40431915b5e054df80f4c0cd556f26e4b",
"_internal/PySide6/translations/qt_help_ja.qm": "ae603b2c0d434d40cde433ffcba65f9ee27978a9e19316007be7fe782a5b8b47",
"_internal/PySide6/translations/qt_help_ka.qm": "159c74f94b384b5ee6afdf38b6cfc4806bc99ecf73be02d4a7021d4ceba7ec7e",
"_internal/PySide6/translations/qt_help_ko.qm": "f11c64694e8e34e1d2c46c1a1d15d6ba9f2db7b61de4fdf54eca5ab977c3e052",
"_internal/PySide6/translations/qt_help_nl.qm": "44a8a0daf775d14352180052d13f623814d7bdf98e2c5c80144b7bf74214e3b0",
"_internal/PySide6/translations/qt_help_nn.qm": "4c8a7213942078e4f72f5babd26c41b77ace70189714a58b5504a7d5ad0193dc",
"_internal/PySide6/translations/qt_help_pl.qm": "cc6cb4d8c54086224672f2e49e623c8cb7c0c1cd65b8d5ecd42fc9ba3a6065bd",
"_internal/PySide6/translations/qt_help_pt_BR.qm": "b4015c5d519b4fe93c00bf734d1742e4f0094d89862664d548eb64a46a2feae7",
"_internal/PySide6/translations/qt_help_ru.qm": "557b644e6da5f1ec720ef93965617087e4d1f40b2494cc5aa524cf3796108de7",
"_internal/PySide6/translations/qt_help_sk.qm": "f41e33e1d790bd0d3eb180f1f875bc191fe74773628f25c2cad95e1402e66867",
"_internal/PySide6/translations/qt_help_sl.qm": "2ec955e662407ebcd8dcdae5aaa21e4108e0b5b0aee0e9db712c27072943535f",
"_internal/PySide6/translations/qt_help_sv.qm": "95bdb03dbaa6dbdfda46c249e9ccce9a353f71ddb8b112961e8b005b2c60b13c",
"_internal/PySide6/translations/qt_help_tr.qm": "81da2f88cd624097581f2d29b10311796bcd9ab289e65883346d276110542d28",
"_internal/PySide6/translations/qt_help_uk.qm": "497cfc473684692ee44d7a3795e8fb2270c57069fd9eb98a615dd29ab9be8a7c",
"_internal/PySide6/translations/qt_help_zh_CN.qm": "e256d1f6034a5a5521c62f129f91731216e474f71e1d9caea3d3dcb11b670deb",
"_internal/PySide6/translations/qt_help_zh_TW.qm": "40112812abb43853d678cc6d97729f21f21b3a7321c827fc9d18f6c936447d1e",
"_internal/PySide6/translations/qt_hr.qm": "fc9e4146f33be3d09b234be01e56235d3037d8d82d64f0700b4d4a6e253a61a7",
"_internal/PySide6/translations/qt_hu.qm": "c2fa649f167cdb801d1cc0cb69c1d93594fd5bf8c0b7e79b969935da5c3e19aa",
"_internal/PySide6/translations/qt_it.qm": "9e7a18bc20ebeec54baaaf41c918a74534511271f796dffffd0f9b9ec31c68d3",
"_internal/PySide6/translations/qt_ja.qm": "0f5fe50452947d1ee9755249d860354bff6977279b4c496a5bc77e5b89dd745e",
"_internal/PySide6/translations/qt_ka.qm": "00b67c6dfc255079b5b98a5640f82519c96b2520a028682fba4078b39d743eaa",
"_internal/PySide6/translations/qt_ko.qm": "1d254b535e1cb35cbcad8210b15b89f4488159826bf35b4504696263dd102fa3",
"_internal/PySide6/translations/qt_lg.qm": "6ba668501f4c040c66da1bdc022362da3c8cf663da6aa484cbdb599028da98ed",
"_internal/PySide6/translations/qt_lt.qm": "47eb5f97467df769261421d54a5bea1131c9fb9b6388791d38bb6574335b64bf",
"_internal/PySide6/translations/qt_lv.qm": "addeca285282338294f24ca50d37d08a5f68d3785d0a94af86dd4ec8f2a3b449",
"_internal/PySide6/translations/qt_nl.qm": "39e870cbd25c0f97fa9b1828d5ea1ed9849857a2e26c5321b3f13c76be8f0548",
"_internal/PySide6/translations/qt_nn.qm": "4e544e23f75eafe1553dc896973db23b5795cd243786d5c653cc0f36a46ca74f",
"_internal/PySide6/translations/qt_pl.qm": "e6890afa0caf0f6db0248e4c94f6016b8ec8bc266f1e0e9b8f01e8ea912cf968",
"_internal/PySide6/translations/qt_pt_BR.qm": "0e24c58e35271853f8cdfb3f0f7b0741b5a9a588e43cdec62ae85a3842771e0a",
"_internal/PySide6/translations/qt_pt_PT.qm": "2c1e7bbf5168a64b43752dd4c547601c0bde6d610f8671fa3e3af38597e84783",
"_internal/PySide6/translations/qt_ru.qm": "1b388e2d6d1bd405603e794e498c6d7ec5f5a5ad819243546f6399181da36758",
"_internal/PySide6/translations/qt_sk.qm": "840c3b01c89df976fc1d2e5bfc6fc84b65666b8a3ceb4cbf5aa0c22af3d2a383",
"_internal/PySide6/translations/qt_sl.qm": "c44e0313a9414cc0e490b65b0c036fa11bca959353b228886547bc2c8492034f",
"_internal/PySide6/translations/qt_sv.qm": "daaae448e0814b469ac3d7a91096fde15491600a6b8bc6c01508425fb5e8b3ec",
"_internal/PySide6/translations/qt_tr.qm": "59e8a0c411be3b0802a68561b090f182099d6b75c4fe46f398e55f11528e11b9",
"_internal/PySide6/translations/qt_uk.qm": "053ec1f677c4dba48c6a97eb28f4fc78c1511324d1843d7f4cec2c7c00a66145",
"_internal/PySide6/translations/qt_zh_CN.qm": "c0e29d32c9540a7e78643b74214e633c56f6ab11f018e516629f2c11b1fb09fc",
"_internal/PySide6/translations/qt_zh_TW.qm": "24e226954491689549a1a1990db3b8cb78888008d8163b2fd2442b772b6d1b5f",
"_internal/PySide6/plugins/generic/qtuiotouchplugin.dll": "aa9080fa8b1c3cf4d3790c1eecf4a1f5c796ce58f31f80910357578f20fd80ac",
"_internal/PySide6/plugins/iconengines/qsvgicon.dll": "5bb97b6f114682ae0b5f42b23b6818aece6499bad88dac80a138efa8a88c12bc",
"_internal/PySide6/plugins/imageformats/qgif.dll": "d301d7e9a68327692e4c76faa6b125517730b22c68f4de7f09fda9d4ac0ddee1",
"_internal/PySide6/plugins/imageformats/qicns.dll": "49db148fea9f01e9953fd0a771d16cfaf364599f07aab3634d4f5c7c25abd78a",
"_internal/PySide6/plugins/imageformats/qico.dll": "1684fd56f1758167f7b3ac011264ae5859b3cf6113e381626ec3dc1d3122fe52",
"_internal/PySide6/plugins/imageformats/qjpeg.dll": "6517345ac19f5c489daeadc029d0018bbdc09d8e1031c60d714557972f22c6d4",
"_internal/PySide6/plugins/imageformats/qsvg.dll": "4b7d65ba39be58cb469b54b5fdee2987871d67e5050cd70724016e09966e54f6",
"_internal/PySide6/plugins/imageformats/qtga.dll": "6b0381150070fcd4224597fe73c68b47055b30b418aa14794c94c5007d14ca5d",
"_internal/PySide6/plugins/imageformats/qtiff.dll": "3d6ea04da215ee2a9459399fb9f6d73cad8787944b9d450399025bcd39d020b5",
"_internal/PySide6/plugins/imageformats/qwbmp.dll": "1a4596509987e9557edda69ed13cdd0d33f4ebda72e464ddc00a566bec05f151",
"_internal/PySide6/plugins/imageformats/qwebp.dll": "6b2c53cc4423140c29a6a1eb6dd908016e09d794b5739a05a3a39c8c49a0df8a",
"_internal/PySide6/plugins/networkinformation/qnetworklistmanager.dll": "e571a4b4e582738cd1bc4889cb2896635c2543baff408442701b6706a1b4a86e",
"_internal/PySide6/plugins/platforminputcontexts/qtvirtualkeyboardplugin.dll": "e10c64dd2ae4f9b756ec1ebe3950a05e345ba40834b7be2900af426623d85475",
"_internal/PySide6/plugins/platforms/qdirect2d.dll": "56f41ad523d016fe2cf2c90fae158e21766d1fcd021bced1a3704c6da0f00c98",
"_internal/PySide6/plugins/platforms/qminimal.dll": "768a9c6dbb1c86abbefa2ff9d7e98cdfb4fdc9292eb8d64195bb6d23939a5344",
"_internal/PySide6/plugins/platforms/qoffscreen.dll": "e776251668440169ed18a2fe1b236762d514ef5244639cbb559b5a77ddd38954",
"_internal/PySide6/plugins/platforms/qwindows.dll": "bf6dbc3009f386fa22f0ced560bea6bbf3e0e0b4442d2fb855db67cffce49dbf",
"_internal/PySide6/plugins/styles/qmodernwindowsstyle.dll": "a7a6424c23bf371bd28a404a196b210971726f6f2a87b63aac185a5e6e40da71",
"_internal/PySide6/plugins/tls/qcertonlybackend.dll": "67be4d333a0f489d02714169a6ec54eaa80efa649d733fcbeb81881ecb02b4f3",
"_internal/PySide6/plugins/tls/qopensslbackend.dll": "7a0727417b8e21e64d9a7cf0f390bc85b3e337b4eef5ac977f49659d97e6b552",
"_internal/PySide6/plugins/tls/qschannelbackend.dll": "14abc5b245c0f2e03f7bc0b474a8db2ecb441c7300a8a8b16fb865eaf2674619"
},
"program_files_equal_accepted": true,
"data_directory_excluded": true,
"gif_sha256": "4b3fed6694ab08d921ca88f92babb0af16380489533d9ed43b143e720d6e04d3",
"bom_sha256": "13e0f1f45b117f3fd18db80790881e932842c4cabfe750f744fab8cb884f5589",
"acceptance_report": "docs/testing/2026-10-15-packaged-acceptance.md",
"build_checks": {
"passed": 369,
"seconds": 63.39
},
"final_source_checks": {
"passed": 369,
"seconds": 83.97
},
"zip_sha256": "2fc74a711e6c5876425d9ece3445ae322d67db9cb34260c4b8ed80f8bbd60f80",
"zip_bytes": 55257821,
"file_count": 238,
"extracted_zip_smoke": true,
"binary_unchanged_since_native_acceptance": true
}
+16
View File
@@ -0,0 +1,16 @@
# V1.1.2 发布构建记录
发布日期:2026-10-16。本次沿用 `a16914bc7221dbc62c467b7a89e06ab0c40c1fbc` 构建并完成实机验收的程序文件,更新中文 README、使用说明、恢复说明、版本说明、通用 BOM 空表和离线 GIF 后重新压缩。版本标签另包含后续文档与验收工具;`src`、`integration`、`packaging` 和 `pyproject.toml` 与该构建提交无差异。
- 原标准构建检查:369 passed,63.39 秒。
- 本次发布前源码检查:369 passed,83.97 秒,1 条 pywinauto COM STA 提示。
- 发布包:`DxPartReplace-1.1.2.zip`,55,257,821 字节,238 个文件,无本机 `data`、数据库、任务日志或工程备份。
- ZIP SHA256:`2fc74a711e6c5876425d9ece3445ae322d67db9cb34260c4b8ed80f8bbd60f80`。
- EXE SHA256:`73d6deb81d52ce34ce9c6d2958275a9b7376f316ae1872552882f0d65070ce75`。
- VBS SHA256:`9997d8a41ad3820e7fd905c8024fc10c765c0e6218eb7f3c091301e3c73db9dc`。
- 完整 EXE 与 `_internal` 文件清单逐一哈希核对,与实机验收版本一致。清单见 [JSON](v1.1.2-build.json)。
- 最终 ZIP 再次解压,移除源码导入路径后运行 `--smoke-test`,退出码 0,启动版本和正常退出日志通过;离线 GIF 与仓库文件哈希相符,BOM 空表为原模板 11 列且不含工程数据。
本轮未重新执行 CAD 替换。真实两工程替换、独立读取、Part Label→Value、未选位号保留、新轮次、旧版元数据兼容及 10 个后台会话释放使用同一程序文件的 [成品验收证据](../testing/2026-10-15-packaged-acceptance.md)。程序身份不变,不能把此次启动检查描述成又完成一次实际替换。
附件为便携 ZIP、`SHA256SUMS-1.1.2.txt`、`release-manifest-1.1.2.json`、`BOM-template.xlsx`、`window-tutorial-1.1.2.gif`。仓库默认分支和版本标签均包含中文 README 及 GIF。发布时逐项回下载核对本地 SHA256,未通过时不解除草稿状态。
+37
View File
@@ -0,0 +1,37 @@
# DxPartReplace V1.1.2
发布日期:2026-10-16。交付级别:**evaluation-only(评估试用)**。
V1.1.2 完善工程任务、BOM 计划和结果查看流程,加入窗口 GIF 中文教程。沿用已完成本机实际替换验收的程序文件,发布包重新整理中文说明与离线 GIF,不包含本机任务数据库、日志或工程备份。
## 下载与上手
下载附件 `DxPartReplace-1.1.2.zip`,完整解压后运行 `DxPartReplace.exe`。无需安装 Python,本机需要可用的 DxDesigner / Expedition Enterprise 7.9.5、许可证和中央库。
[中文教程与 GIF](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/src/tag/v1.1.2/README.md) · [窗口 GIF](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/raw/tag/v1.1.2/docs/user/media/v1.1.2-window-bom-tutorial.gif)
## 主要更新
- 一工程一任务,同批工程顺序执行;左侧搜索和显示排序不改变执行范围。
- 已导入工程即可导出默认 11 列 BOM,同批工程共用一张表,按工程路径分配至任务,无需先采集。
- 一行支持多个位号,只替换启用目标;NC 默认开启,可逐行关闭,自定义 Value 优先。
- BOM 先整批校验再预览,报告通过、失败、未检查数量及 Excel 行号;点击保存才原子写入计划,有错误不部分保存。
- 规则表、位号表、结果表使用模型视图;详情按需创建,关闭释放,隐藏页不反复渲染,草稿独立保留。
- 显示实际回读的位号、旧新料号和核验状态,日志支持分页;已完成任务可创建新轮次,旧证据归档保留。
- 完善工程和证据长路径访问、受监督后台执行、清理与不确定状态保护。
## 本机验收
- 标准构建检查 369 项通过,冻结 EXE 启动与退出通过。
- 两工程实际 BOM 流程、原生替换、保存重开和全新 CAD 独立回读通过;RV05 替换、RV11 保留,启用复制后 Value 与目标 Part Label 均回读为 0R。
- 297 字符工程路径、错误/正确 BOM 导入、旧 1.1.1 元数据任务副本兼容、开始新一轮通过。
- 原工程全文件哈希未变;10 个观察到的自有 CAD 和私有桌面均释放,主桌面及原 CAD 未被接管。
- GIF 20 步、47.5 秒,仅含应用窗口与弹窗,实际等待压缩。详见[成品验收记录](../testing/2026-10-15-packaged-acceptance.md)。
## 更新与限制
更新前关闭旧程序并备份 `data`,保留旧数据,用新包中的 EXE 与 `_internal` 配套运行。不同版本不要同时打开同一数据目录。
本次验收不替代其他机器、库版本或 Packager/ERC 验收。已知 CAD COM 偶发启动阻塞根因仍待定位;程序保留有界等待、取消检查与清理保护。首次采集可能需要数分钟。出现不确定状态时先核验恢复,避免重复执行。
程序构建及验收提交为 `a16914bc7221dbc62c467b7a89e06ab0c40c1fbc`;版本标签另包含后续文档与验收工具,产品运行代码未改变。附件 `release-manifest-1.1.2.json` 记录 EXE、VBS、GIF 和完整程序文件清单;`SHA256SUMS-1.1.2.txt` 可校验下载附件。
@@ -0,0 +1,89 @@
# CBB Verify 与后台原生后端借鉴调研
调研日期:2026-10-14。读取 `cbb-refresh-verify-795`、`mentor_PDF_output` 源码、已有离线证据和本机 EE7.9.5 安装目录静态文件;没有启动 Mentor、没有附着 COM、没有修改工程或中心库。
## CBB Verify 的真正原理
CBB Verify 当前代码使用有界的原生进程监督器:
```text
单个 CBB
-> 固定目标 LMC/CBB/PCB 身份
-> 创建独立 Windows desktop
-> CreateProcess + Job Object 管理 worker 和子进程
-> 启动 common\\win32\\bin\\ExpeditionPCB.exe <PCB> -ReusableCircuit
-> 通过 PID、命令行和父子关系绑定本次 wg PCB worker
-> COM 获取 MGCPCB.Application / ActiveDocument
-> ProjectIntegration 状态机逐项执行并重新读取状态
-> 保存、关闭、退出证据
-> x86 状态桥调用 IsVerifiedReuseBlock
-> 只有本次执行后的 READY/raw=1 才算成功
```
其中 `Library Manager` 的原生 Verify 菜单路线只是兼容/诊断路线。已有现场记录表明,在 7.9.5 上它依赖物理光标命中树节点;私有 desktop 中光标位置不可用,消息投递会落到停靠面板菜单。真实输入可以成功,但会切换用户输入桌面,因此没有作为默认后台路径。
`reusable_circuit_direct` 路线的价值在于:窗口可以存在于私有桌面,用户前台不被切走;进程树可被 Job Object 收回;COM 操作不靠屏幕坐标;成功判定依赖执行后的权威状态,而不是“窗口关闭”或某个中间灯变绿。
本轮核对的源码依据:
- `cbb-refresh-verify-795/src/cbb_refresh_verify/desktop_worker.py:26-45`:CreateDesktop、STARTUPINFO.lpDesktop、CreateProcess、Job Object。
- `src/cbb_refresh_verify/mentor_adapter.py:178-192,651-706`:优先 common 启动器、生产 direct 路线、实际 PCB worker 绑定和 COM 文档身份检查。
- `src/cbb_refresh_verify/integration.py:10-15,57-96`:ForwardAnnotate/SynchCES/LoadCES/BackAnnotate 状态机,每次执行后重读状态;初始四绿时只做一次 ForwardAnnotate,再按实际 Required 修复。
- `tools/status_bridge/CbbStatusBridge32.cpp:19,187-205`:x86/MFC 桥动态读取 LMCDLL70.dll 的 IsVerifiedReuseBlock 导出。它是 CBB 状态读取接口,不能作为替换执行接口。
- `docs/diagnostics/2026-09-29-r4-field-log-review.md:9-27`:已有现场报告记载 direct 路线、9 个本次 READY/raw=1 成功项和 8 个失败项。本轮未重新运行这些工程。
旧 README、API-FINDINGS 和研究计划中存在不同历史路线,不能只按其中一句话判断当前实现。上述结论优先依据当前 mentor_adapter 的实际分支以及有日期的现场记录。
## 可借鉴到 Part Replace 的部分
可以直接借鉴以下架构:
1. 把一个工程任务封装成独立 native worker,会话绑定工程路径、任务 ID、目标 UID 集合、旧料号、新料号和计划哈希。
2. 用 `CreateProcess`、私有 desktop 和 Job Object 管理 DxDesigner 及其脚本/辅助进程。超时只终止本次创建的进程树。
3. 通过进程 PID、命令行和父子关系绑定本次 DxDesigner/worker,禁止附着到用户已有的同名进程。
4. 将“打开工程、选中 UID、调用 Replace Part、Library Wins、保存、关闭、重新打开”拆成状态机,每个阶段写结构化事件和快照。
5. 把最终判断改成后置不变量:目标 UID 已变成新料号、RefDes/网络/引脚/受保护属性保持、未选中同旧料号器件未变、保存后重开仍成立。任一状态不确定就阻断后续任务。
6. 沿用 CBB 的单项证据目录、串行队列、失败后继续/不确定后停止、最终报告和可恢复检查点。
不能直接照搬 CBB 的内容检查接口。CBB 的 `ProjectIntegration`、ReusableCircuit 保存和 `IsVerifiedReuseBlock` 是 CBB 中心库认证语义,与原理图器件替换不是同一对象。
## “像 MentorPDF 一样”的原生接口调查
MentorPDF 使用的是官方命令行:
```text
sch2pdf.exe -project <project.prj> -a <output.pdf> -c <color> ...
```
它没有 UID、RefDes、旧料号、新料号或 Library Wins 参数,所以只能借鉴其进程管理、串行队列、Job Object、前后指纹、日志目录和原子提交,不能作为替换后端。
本机安装目录静态检索到的候选如下:
| 候选 | 证据 | 判断 |
| --- | --- | --- |
| `sch2pdf.exe` | 官方 CLI;输入工程,输出 PDF | PDF 导出,可能更新 iCDB/日志;没有已证明的替换合同 |
| `DxPDF.exe` | PDF GUI 前端字符串 | 不含替换合同 |
| `icdbPartsLister.exe` | 字符串包含 `Part Number`、`REFDES`、`cComp`、`Component` | 只能作为只读库存候选,尚无输出协议或写入证据 |
| `IVdApp.ExecuteCommand` / `ccomp` | TypeLib 有 ExecuteCommand;安装样例只证明 `component 74ls01` 放置元件 | `ccomp` 语法、范围、Library Wins 均未证实 |
| `IVdBlock.ChangeComponentPreserveRefdes` | 当前 7.9.5 TypeLib 确有 DISPID 42 | 没有 Library Wins 参数,未证明选中范围、网络/引脚和中心库语义 |
| `IVdApp.ReplacePart` | 只在工作区保存的 119.0 wrapper 中出现 | 当前安装版 TypeLib 1.0 不含,不能盲调 |
| `CLibServer::VerifyRCCells(int)` | CBB 研究计划中的内部 ABI 候选 | 只与 CBB Verify 相关,ABI 尚未验证,不能用于 Part Replace |
补充搜索范围:四个相关安装 bin 目录中的 91 个 PE 文件导出表,只找到两个 iCDB::String::Replace 字符串处理符号,没有发现设计替换导出。这个结果不能排除未导出内部函数、资源命令或其他版本能力。详细路径、符号和边界见 `2026-10-14-mentorpdf-native-interface-followup.md`。
另外,本轮用 7-Zip 成功解开本机 `automate.chm`、`viewdraw.chm`、`dxdesigner.chm`。`viewdraw/command/ccomp.htm`、`getst/Replacing_Components_.htm` 和 `refer2/HID_COMP_REPLACE.htm` 实际为跳转至 InfoHub 的占位页面,没有命令参数说明。安装 `docs` 只包含系统管理手册,没有找到对应的完整原理图命令参考。提取内容仅保存在忽略目录 `build/native-help-20261014`,没有提交厂商帮助内容。
## 建议的下一步
建议新增一个 **research-only `private_desktop_backend`**,不改变当前生产后端:
1. 先用可丢弃工程副本验证 `viewdraw.exe`/Viewdraw COM 是否能在私有 desktop 启动、打开单工程并通过 UID 选中;只读确认 COM 身份,不执行替换。
2. 再验证原生 Replace Part 对话框能否通过窗口消息在私有 desktop 完成一次单 UID 替换。若依赖物理光标或真实输入,立即判定该路线不适合后台。
3. 只有在目标选择、Library Wins、保存回读、未选中件保护和进程清理全部有证据后,才把它提升为可选后端。
4. `icdbPartsLister.exe` 先做命令行 `--help`/版本和只读输出探针;如果没有稳定输入输出合同,就不接入库存采集。
当前推荐:保留 V1.1.0 的原生对话框后端作为现行写入路径;借鉴 CBB Verify 的私有 desktop、Job Object、PID 绑定和权威后置验证,先做独立探针,不把未证实候选接口接入正式替换流程。任务、位号计划和 Excel 继续由现有架构管理,后台适配只改变执行器。
已有串行调度、任务证据、输入冻结和保存回读不需要再重写。新增工作的重点是桌面隔离、自己启动的 CAD 进程身份、跨进程 COM 绑定以及对话框是否依赖真实输入。Job Object 强制回收也不能照搬为所有阶段的取消策略:在 CAD/iCDB 写入或保存期间,应先完成收尾或标记不确定,再决定清理,避免中断数据库写回。
证据等级:源码调用链为 A;安装文件名和 PE 字符串为 B;`icdbPartsLister`、`ccomp`、`ChangeComponentPreserveRefdes` 的实际语义和私有 desktop Replace Part 行为为 C,必须现场验证。
@@ -0,0 +1,98 @@
# MentorPDF 原生接口链路补充调研
调研日期:2026-10-14。此次只读取 `mentor_PDF_output` 源码、本机 EE7.9.5 安装目录文件名/PE 字符串和已存在的 Viewdraw 脚本样例;没有启动 `sch2pdf`、`DxPDF`、DxDesigner,也没有附着 COM 或写入工程。
## MentorPDF 的实际原生链路
MentorPDF 不是 COM 自动化器,也没有向 Viewdraw 发送替换命令。它是一个 Python UI/CLI 外壳,发现并串行启动 Mentor 安装提供的独立 `sch2pdf.exe`:
- `src/mentor_pdf_export/engine.py:6-23` 从 `SDD_HOME` 或有限的 `CDEFG:\Mentor*` 路径寻找 `wv/win32/bin/sch2pdf.exe`。
- `src/mentor_pdf_export/profiles.py:56-74` 只组装 `sch2pdf.exe -project <project> -a <pdf> -c <color>` 以及 `-p/-e/-i2s/-uAll/-udx/-l/-schematic` 选项;没有组件 UID、RefDes、料号或替换参数。
- `src/mentor_pdf_export/engine.py:82-120,148-205` 用 Windows `CreateProcess`/Job Object 启动子进程,捕获 stdout/stderr,支持取消、超时和后台 iCDB 写回等待。Linux/非 Windows 才退回 `subprocess.Popen`。
- `src/mentor_pdf_export/exporter.py:72-124,144-170` 在启动前保存源指纹和 `command.json`,原生输出先写 staging PDF,验证 PDF 和源工程指纹后再原子发布。
- `src/mentor_pdf_export/workers.py:28-100` 用一个 `BatchWorker` 串行执行多个工程,禁止同一 `Exporter` 并行运行;每个项目有独立结果和可重试运行目录。
- `src/mentor_pdf_export/scanner.py:34-65` 扫描 `.prj`,只读工程头部中的 `FrontEndSnapshot`、`iCDBDir`、`RootBlock`,拒绝链接和受保护目录。
因此可借鉴的是**原生进程适配器、批次队列、证据目录、源指纹与原子提交**,不能借鉴为替换 API。PDF 工具输入的是工程路径和打印参数,实际设计读取/数据库行为留给 `sch2pdf` 内部,源码没有提供“按位号选择组件”的可复用协议。
## 本机官方工具和候选
在 `D:\Mentor\7.9.5EE\SDD_HOME\wv\win32\bin` 中,受限检索得到三个相关可执行文件:
| 文件 | SHA-256 | 静态线索 | 判断 |
| --- | --- | --- | --- |
| `sch2pdf.exe` | `EF246E3AA2F1CD46BF41F1C89393EED362E8DC8540ADD49F489D9BDEED5A51A6` | PE 字符串含 `-project`、`Schematic`、`Component`、`RefDes`、`Part Number` | 原生 PDF 导出器;没有证据表明它接受替换/写入参数。 |
| `DxPDF.exe` | `F9F7F63FE1C1C85004F020118775728CE6D407352CCA8008D25110504595F112` | PE 字符串含 `DxPDF (Version 4.00)`、`-project`、`CDxPdfMainDialog::setProjectFile`,依赖 `dxpdfgui70.dll` | GUI PDF 前端;没有发现替换接口。 |
| `icdbPartsLister.exe` | `B227796564C59AAAF6DF19939A559DF1FF180C0E3D26173F043CC44B5919DA8D` | PE 字符串含 `Part Number`、`REFDES`、`cComp`、`Component`、`refdes` | 可能是只读部品/数据库列表器;静态字符串不能证明筛选、导出格式或写入能力,不能当替换后端。 |
安装目录的 Viewdraw 样例只有 `D:\Mentor\7.9.5EE\SDD_HOME\wv\samples\viewdraw\scripting\ToolbarButton.vbs`、`menu.vbs` 和 `readme.txt`。`ToolbarButton.vbs:30-34` 示例为 `Application.ExecuteCommand "component 74ls01"` 或 `ActiveView.ActiveBlock.AddComponentMoveMode`,语义是放置新元件,不是替换现有元件,也没有 `Library Wins` 或目标 RefDes 参数。安装样例没有 `ccomp`、`ReplacePart` 或 `Library Wins` 示例。
现有安装版 TypeLib 的真实成员仍以 `docs/research/v1.1.0-native-typelib-evidence.json` 为准:有 `ExecuteCommand`、`SelectComponent`、`Selected` 和 `ChangeComponentPreserveRefdes`,没有直接 `ReplacePart`。因此 MentorPDF 的独立进程模式不能绕过这一接口事实。
## 对 V1.1.0 的借鉴
可以把替换工具的单工程任务执行器做成类似 MentorPDF 的独立 backend runner:
```text
task -> preflight/inventory -> frozen target UID set
-> backend process/COM bridge
-> before/after snapshot -> verify
-> saved/reopened readback -> atomic evidence/result
```
可直接借鉴的设计点:
1. 用 `request.json`、`command.json`、`stdout/stderr`、前后快照和 `result.json` 建立每任务证据目录(MentorPDF `exporter.py:120-165`)。
2. 任务按工程串行执行,禁止同一原生工具并行(`exporter.py:72-78`、`workers.py:28-100`)。
3. 子进程必须创建后立即纳入 Job Object,超时只终止本工具创建的进程树(`engine.py:82-120`)。
4. 执行前后保存工程指纹;外部原生程序可能写 iCDB/log,即使可接受也必须单独标为 warning,不能伪称源工程字节不变(`exporter.py:120-152`、`docs/testing/2026-10-10-v032-native-policy.md:5-7,30-41`)。
5. 输出/报告写到独立运行目录,成功结果才原子提交,失败/不确定保留证据(`exporter.py:122-170,186-213`)。
替换工具的差异是:替换会写设计,必须先做备份/冻结 UID,再验证未选中的同旧料号位号没有变化;不能照搬 MentorPDF “直接读取原工程”的策略。MentorPDF 的 `sch2pdf` 子进程也不适合作为替换代理,因为它的 CLI 合同没有组件选择或新料号字段,且其内部可能更新 iCDB。
## 建议的接口代理边界
为 V1.1.0 保留三个明确后端类别:
- `native_dialog_backend`:当前已实现的精确选中 + 原生 Replace Part 操作,仍需现场验证控件/完成观察;
- `viewdraw_component_backend`:仅研究 `SelectComponent`、`ChangeComponentPreserveRefdes`,必须标记 `research_only`,不宣称 Library Wins;
- `native_process_backend`:未来若发现带明确输入合同的官方替换 CLI,可借鉴 MentorPDF 的 Job Object/日志/证据框架接入。当前安装目录未发现该工具。
任何代理都必须接收 `project_path + sheet + target_uids + expected_old_part + new_part + evidence_dir`,在写入前核对工程指纹和选中集合;接口没有目标 UID、范围和库策略时不得自动扩大范围。`icdbPartsLister.exe` 只有在单独验证输出字段、只读性质和与当前工程身份绑定后,才可作为 inventory 辅助,不可直接成为 replacement backend。
## 证据等级
- **A:源码直接证据**:MentorPDF 的 `engine.py`、`profiles.py`、`exporter.py`、`workers.py`、`scanner.py` 调用链和行号。
- **B:安装文件静态证据**:可执行文件名、哈希、PE 字符串、Viewdraw 样例脚本。只能证明存在和字符串/示例,不证明完整运行语义。
- **C:待现场验证**:`icdbPartsLister.exe` 的实际输出协议、任何 `ccomp` 命令行为、`ChangeComponentPreserveRefdes` 的写入结果,以及未来版本可能存在的直接 `ReplacePart` API。
本报告没有运行任何官方工具,也没有把 PE 字符串或 MentorPDF 的导出命令解释成“支持按位号替换”的证据。
## 有界 PE 导出检索补充
为检查是否存在类似 `sch2pdf.exe` 的原生替换进程,我对以下已安装目录做了静态 PE 导出扫描,没有加载 DLL 或执行 EXE:
```text
D:\Mentor\7.9.5EE\SDD_HOME\wv\win32\bin
D:\Mentor\7.9.5EE\SDD_HOME\dx\win32\bin
D:\Mentor\7.9.5EE\SDD_HOME\iCDB\win32\bin
D:\Mentor\7.9.5EE\SDD_HOME\lm\win32\bin
```
扫描了上述目录中 91 个 PE 文件(`.dll`/`.exe`),按导出名称筛选 `replace`、`ccomp`、`ChangeComponent`、`LibraryWins`、`Library_Wins`,结果只有两条内部 C++ 修饰导出:
```text
iCDBNetLauncher.exe
?Replace@String@iCDB@@QAE?AV12@ABV12@0ABV?$BitContainerT@W4ESearchParams@iCDB@@$00@2@@Z
ordinal 4101, RVA 0x486e0
iCDBRSCMConfigurator.exe
?Replace@String@iCDB@@QAE?AV12@ABV12@0ABV?$BitContainerT@W4ESearchParams@iCDB@@$00@2@@Z
ordinal 4101, RVA 0x15ccc0
```
这两个符号是 `iCDB::String::Replace` 风格的字符串/搜索参数函数,不是设计元件替换;导出对象是 EXE 而非稳定 SDK DLL,名称包含编译器修饰、C++ 类 ABI、内部类型和固定 ordinal,不能从外部安全调用。没有发现名称含 `ccomp`、`ChangeComponent`、`LibraryWins` 或设计 `ReplacePart` 的导出。这个阴性结果只覆盖上述四个目录的 PE 导出表,不能证明所有资源、未导出内部函数、脚本命令或其他安装版本不存在相关能力。
官方启动脚本也没有隐藏替换参数:`D:\Mentor\7.9.5EE\SDD_HOME\common\win32\bin\viewdraw.bat:1-14` 只收集 `%*` 并执行 `%SDD_START% ...\\viewdraw.exe %epdarglist%`;`icdbPartsLister.bat:1-14` 以同样方式执行 `icdbPartsLister.exe`。这些脚本提供进程环境/参数转发,不定义 `ccomp`、料号、位号或 Library Wins 合同。
因此,当前安装中没有静态证据显示存在可像 `sch2pdf` 一样、以独立 CLI/导出函数实现精确库料号替换的官方原生进程。后端仍应使用已知的 Viewdraw COM 选择能力加原生替换交互;任何内部 C++ 导出都应标为 `unsupported`,不应作为 V1.1.0 代理。
@@ -0,0 +1,69 @@
# V1.1.0 DxDesigner 7.9.5 原生替换接口调研
调研日期:2026-10-14。范围为现有工作区源码、已有测试、本机注册的 7.9.5 COM TypeLib 与安装帮助;本次没有附着、启动或修改任何 CAD 工程,也没有做写入式 live probe。
**安装版 TypeLib 复核更正:** 本机实际注册的 `viewdraw.tlb` 是版本 `1.0`,不含 `ReplacePart`、`OpenReplacePartDialog`、`ReplacePartCompleted` 或 `SelectExactSet`。工作区保存的一份同名 `designer_ifc.py` 是声明版本 `119.0` 的 makepy wrapper,虽然含 `IVdApp.ReplacePart(SourcePart, Scope, DestinationPart, PinMapping, PropertyMapping)`、`SRP_Selection=5` 和 `PropMT_LibraryWins=3`,但**不能用于证明本机 7.9.5 有这些成员**。下文旧桥中的这些名称应按候选/模拟接口理解。本机真实接口结果以 [离线 TypeLib 证据](v1.1.0-native-typelib-evidence.json) 为准。
## 结论
现有的 `Viewdraw.Application` COM 接口足以读取工程/图页/器件,按 UID 精确选中指定器件,并在替换前后核对选中集合。V1.1.0 的“一个旧料号只替换部分位号”可沿用这条选择链路。**写入路径仍应调用原生 Replace Symbol / Replace Part 并明确核验 Library Wins**。目前没有证据表明 `Block.ChangeComponentPreserveRefdes` 或 `ExecuteCommand("ccomp ...")` 能完整实现中央库选件、Library Wins、引脚及网络保持、Undo 和 Packager 通过。两者只适合作为可丢弃工程上的隔离探针,不能注册为默认执行后端。
这里的“原生接口”需要分清层次:现行自动执行使用 COM 读写选中状态,再从 `viewdraw.exe` 菜单资源识别 Replace Symbol 命令并发送 `WM_COMMAND`,随后通过 DxDesigner 原生对话框选择库行及选项。这是**原生 UI 工作流的自动化**,不是已证明存在的“传入旧件、新料号、Library Wins 参数的一次性 COM API”。
## 现有证据
| 路线 | 已有证据 | 当前判断 |
| --- | --- | --- |
| `Viewdraw.Application` | `QuickPartReplace.vbs:184,402,416` 附着/创建对象;`native_helper.py:196-204` 从活动对象取得 `IVdApp`;一叶知秋 `integration/dxdesigner795/CompatibilityProbe.vbs:122-132` 使用 `GetProjectData` 和 `DesignComponents` 枚举全工程。 | 可用作工程上下文、清单和选中控制;实际环境、精确 build 和 32/64 位组合仍需现场验收。 |
| 按器件精确选择 | `native_helper.py:214-249` 以 UID 设置 `Selected` 并重新读取选中 UID;本机 TypeLib 有 `IVdComp.Selected/_SetSelected` 和 `IVdApp.SelectComponent`;旧桥 `PartReplaceBridge.vbs:2097-2150` 所用的 `SelectExactSet` 不在安装版 TypeLib。一叶知秋 `core/Mailbox.vbs:365-375` 已用 `SelectByName` 定位单件。 | 位号应在扫描阶段绑定项目、图页、UID、旧料号;执行前重查完整身份和选中集合。仅用 RefDes 文本不能跨图页唯一定位。 |
| 原生 Replace Part + Library Wins | `native_helper.py:165-193,437-445` 从 Viewdraw 菜单资源识别 Replace Symbol;`:450-517` 打开原生对话框、选择精确库行、检查目标 Part Number/符号、确认原生选项,再执行;`:519-553` 验证结果及未选中件未变。`QuickPartReplace.vbs:780-815` 调用 helper;`:837-865` 对未保存失败做原生 Undo 和快照验证。 | 是已有的自动写入路线;需在现场 build/中央库上回归,并以证据确认每个控件 ID 对应的选项,不能只依赖 ID。 |
| `Application.OpenReplacePartDialog` | 旧桥 `PartReplaceBridge.vbs:2260-2261,2341-2384` 调用该名称并读 `ReplacePartCompleted`;旧 probe `PartReplaceProbe.vbs:951-985` 将其列为候选,`ccomp_research` 明确 `production_enabled=false`。本机 7.9.5 `IVdApp` TypeLib 没有这两个成员。 | 旧桥属于未证实候选/模拟路径;不能注册为本机可调用 COM 接口。 |
| `Block.ChangeComponentPreserveRefdes` | 本机 7.9.5 TypeLib 的 `IVdBlock` 确有 DISPID `42`,参数 `OldComp, NewComp`,返回 `VARIANT_BOOL`;保存的 wrapper `designer_ifc.py:5005,9943` 也有相同名称。现有设计 `docs/superpowers/specs/2026-09-01-dxdesigner-795-part-replacement-design.md:50-61` 记录符号原点及 Packager 失败的社区线索。 | 存在方法不等于可用于库料号替换;签名没有 Library Wins 参数,也未说明只作用于选中位号、如何选库及连接语义。 |
| `ExecuteCommand("ccomp ...")` | 类型库包装 `designer_ifc.py:1385,2974,3926` 暴露 `ExecuteCommand(CommandString)`;现有脚本只在 `QuickPartReplace.vbs:845,1143` 对 `undo` 使用它。旧设计 `...part-replacement-design.md:50-60` 仅记载 `ccomp :component_name` 候选,旧 probe 将 `Application.CComp` 标为研究项。全工作区未找到执行 `ExecuteCommand("ccomp ...")` 的生产调用或成功报告。 | 命令存在性、准确语法、选择范围及 Library Wins 行为均未证实。不能用 `undo` 可执行推断 `ccomp` 可执行。 |
已有文档 `docs/user/part-replacement.md:5,129-142` 对生产边界、精确选择与硬不变量作了明确约束。旧设计 `...part-replacement-design.md:37` 曾写“Python 不直接附着 COM”,但当前 `native_helper.py:196-204` 已直接附着。V1.1.0 文档应以当前实现和 live 证据为准,修正这处历史差异;不要把旧设计中的未验证候选当作生产能力。模拟测试 `tests/integration/test_part_replace_probe.py:498-562` 与 `test_part_replace_bridge.py:336-355` 只能证明协议和错误处理,不构成真实 7.9.5 行为证据。
## 本机安装版 TypeLib 细查
注册表 `HKLM\SOFTWARE\Classes\TypeLib\{4ADEF4E1-690A-11CE-9261-0020C5E26659}\1.0\0\win32` 指向 `D:\Mentor\7.9.5EE\SDD_HOME\wv\win32\bin\viewdraw.tlb`,SHA-256 为 `09323c8940f1acf3f469d887dcfdf7bcd114164a29b01ebeb9a7f978fa1a0df7`,共 223 个 TypeInfo。离线脚本 `tools/research/probe-native-capabilities.py` 直接调用 `pythoncom.LoadTypeLib(path)` 读这个文件,并与保存的 wrapper 比较;它不调用 `GetActiveObject` 或 `CreateObject`。输出 `docs/research/v1.1.0-native-typelib-evidence.json` 的 `wrapper_matches_installed_version=false`。
安装版真实可见成员包括 `IVdApp.ExecuteCommand(CommandString)` DISPID 29、`SelectComponent(sSchName, sSheetName, sCompUID)` DISPID 266、`QueryPages` DISPID 46、`DesignComponents` DISPID 59、`GetProjectData` DISPID 228;`IVdComp.Selected` 和 `_SetSelected`;`IVdBlock.DeSelectAll`、`ChangeComponent` DISPID 24、`ChangeComponentPreserveRefdes` DISPID 42。**没有任何名称含 Replace 的 TypeLib 函数**。旧桥引用的 `SelectExactSet`、`OpenReplacePartDialog`、`ReplacePartCompleted` 在安装版各接口中均未出现;目前测试里的同名 mock 不能当作原生接口。
外部 wrapper 的 `IVdApp.ReplacePart` 确有 DISPID 300、两个 BSTR、三个 32 位整数/枚举、布尔返回,以及 `SRP_Selection=5`、`PinMT_ByPinNumber=2`、`PropMT_LibraryWins=3`。它的声明版本是 `119.0`,与安装版 `1.0` 不同。因此可作为**未来版本接口线索**,但本机 V1.1.0 后端 capability 必须返回 `unavailable`,不能尝试按 DISPID 300 盲调。只有安装的 TypeLib 与运行时真实包含该方法,且 Selection + 精确 UID 选中 + Library Wins 的现场语义全部验证,才能为对应 build 启用直接 API 后端。
安装版 `automate.chm` 尝试用系统 `hh.exe -decompile` 提取,但没有得到可读文件;工作区的 `designer_auto_ref.pdf` 为较新 Xpedition Designer Automation Reference,页 696-697 解释 PinMapping/PropertyMapping 枚举,却不能代表本机 7.9.5 的接口集。故本结论优先依据安装版二进制 TypeLib,帮助材料只用于理解候选语义。
## 建议的 live probe
1. 准备已关闭、可丢弃的完整工程副本,记录 DxDesigner 版本/build、中央库身份、工程树哈希;选择同一旧料号的两个以上器件,其中仅一个目标位号需要替换。另选一个多单元或引脚较多的代表件。
2. 先只读探测 `ProjectPath`、`QueryPages`、`DesignComponents`、每个器件的 UID/RefDes/层级/图页/旧料号/Value/引脚/网络;在不同图页和同页重复位号场景验证身份是否唯一。记录 COM 调用返回值与错误号。
3. 在副本上单独验证 `IVdComp.Selected` 与 `IVdApp.SelectComponent`:只选目标 UID,重新枚举选中集合。若集合不一致则停止。记录目标与同旧料号未选中器件的完整前快照。`SelectExactSet` 不作为本机 7.9.5 探针调用。
4. 建立基准:使用现行原生对话框路线对目标位号执行一次 Replace Part + Library Wins,记录库行、目标符号、控件文本/状态、替换后全图页快照、Undo、保存关闭再打开回读、Packager/ERC/网表结果。
5. 对 `ChangeComponentPreserveRefdes` 和 `ccomp` **分别使用新的副本**做最小写入探针。先只读确认签名和命令语法;确认可恢复后仅改一个目标件。记录实际作用范围、库控制字段、RefDes/位置/方向、引脚号与网络、非目标件、Undo、保存回读和 Packager。任一步不确定就关闭副本且不保存,并留证;不能把属性值或 Part Number 单字段变化视为通过。
6. 只有候选路线在多类器件、多图页、现场中央库上满足与基准相同的硬不变量,且有可重复证据和精确 build 绑定,才考虑提升为可选后端。选择一组目标位号后,必须证明未选中的同料号位号保持原样。
现行代码核验目标及未选中件料号(`native_helper.py:519-547`),但后端晋级标准还要使用 `docs/user/part-replacement.md:140` 的完整保护字段,并核对 NC/Value 策略、保存回读和独立 Packager/ERC/网表结果。现场报告应保存命令、参数、返回值/错误、前后快照、差异及文件 SHA-256,而不是只保存“成功”布尔值。
## V1.1.0 后端边界建议
将**计划和身份验证**留在任务层;替换后端只负责一组已冻结的目标 UID。在单工程任务内按图页、旧料号、新料号及 Value/NC 策略分组,后端逐组处理。最小契约可表达为:
```text
ReplacementRequest:
project_path, project_fingerprint, sheet_identity
targets: [{uid, refdes, old_part_number, baseline_fingerprint}]
new_part_number, library_identity, policy, command_id
ReplacementBackend:
capability(build, library_identity) -> supported / research_only / unavailable
inspect(request) -> current target identities and full-sheet baseline
replace(request, evidence_dir) -> result with attempted/committed/uncertain status
verify(request, result) -> selected and unselected differences
recover(request, result) -> verified undo or close_without_save evidence
```
生产后端先封装当前 native dialog/helper 路线。`ChangeComponentPreserveRefdes` 与 `ccomp` 应放入独立研究适配器,并强制 `research_only`、可丢弃副本和显式试验入口。后端不能自行扩大目标集合;命令中无 UID、旧料号或工程指纹匹配失败时,必须在写入前失败。结果须区分“未开始”“已变更但未确认”“已验证”和“已恢复”,使批次调度器遇到不确定状态时停下。
## 外部资料与证据等级
现有设计在 `...part-replacement-design.md:69` 引用了 Siemens 社区关于 `ChangeComponentPreserveRefdes` 导致封装失败的讨论。此次网络可访问 Siemens 支持门户首页(HTTP 200),但未取得公开的 7.9.5 API 正文或可复核的 `ccomp`/Library Wins 参数说明;搜索请求超时。因此报告中对这两条路线的判断以本机类型库、工作区源码与设计记录为依据,**没有宣称公开资料证明其替换语义**。下一轮应优先取得站点安装包里的 Automation Reference、命令手册和现场 build 录屏/日志,再做写入试验。
@@ -0,0 +1,629 @@
{
"format_version": 1,
"mode": "offline_installed_typelib_and_wrapper_comparison",
"attached_to_viewdraw": false,
"mutation_attempted": false,
"wrapper": {
"path": "F:\\Sync Tool Skyworth\\Work Maps\\AppTraceRecorder\\reference\\SiemensEDA_Python_Interface\\xpedition_designer\\designer_ifc.py",
"sha256": "4f6c341091b3b55ed579df6747b2cf261f49533cdbafaa9db306b06ff751c95a"
},
"typelib": {
"path": "D:\\Mentor\\7.9.5EE\\SDD_HOME\\wv\\win32\\bin\\viewdraw.tlb",
"exists": true,
"sha256": "09323c8940f1acf3f469d887dcfdf7bcd114164a29b01ebeb9a7f978fa1a0df7",
"size": 188040
},
"saved_wrapper_candidates": {
"declared_version": {
"major": 119,
"minor": 0
},
"constants": {
"SRP_Project": 1,
"SRP_Board": 2,
"SRP_Schematic": 3,
"SRP_Sheet": 4,
"SRP_Selection": 5,
"PinMT_ByName": 1,
"PinMT_ByPinNumber": 2,
"PropMT_LibraryOnly": 1,
"PropMT_SchematicWins": 2,
"PropMT_LibraryWins": 3
},
"methods": [
{
"interface": "IVdApp",
"name": "ReplacePart",
"dispid": 300,
"arguments": [
"SourcePart",
"Scope",
"DestinationPart",
"PinMapping",
"PropertyMapping"
],
"makepy_return_type": [
11,
0
],
"makepy_argument_types": [
[
8,
1
],
[
3,
1
],
[
8,
1
],
[
3,
1
],
[
3,
1
]
],
"wrapper_line": 3347,
"status": "typelib_candidate"
},
{
"interface": "IVdAppProtectionProxy",
"name": "ReplacePart",
"dispid": 300,
"arguments": [
"SourcePart",
"Scope",
"DestinationPart",
"PinMapping",
"PropertyMapping"
],
"makepy_return_type": [
11,
0
],
"makepy_argument_types": [
[
8,
1
],
[
3,
1
],
[
8,
1
],
[
3,
1
],
[
3,
1
]
],
"wrapper_line": 4277,
"status": "typelib_candidate"
},
{
"interface": "IVdApplicationAtTest",
"name": "ReplaceConnector",
"dispid": 2,
"arguments": [
"SourceConnector",
"Scope",
"DestinationConnector",
"PinMapping",
"PropertyMapping"
],
"makepy_return_type": [
11,
0
],
"makepy_argument_types": [
[
8,
1
],
[
3,
1
],
[
8,
1
],
[
3,
1
],
[
3,
1
]
],
"wrapper_line": 4549,
"status": "typelib_candidate"
},
{
"interface": "IVdApplicationAtTest",
"name": "ReplaceSymbol",
"dispid": 3,
"arguments": [
"SourceSymbol",
"Scope",
"DestinationSymbol",
"PinMapping",
"PropertyMapping"
],
"makepy_return_type": [
11,
0
],
"makepy_argument_types": [
[
8,
1
],
[
3,
1
],
[
8,
1
],
[
3,
1
],
[
3,
1
]
],
"wrapper_line": 4554,
"status": "typelib_candidate"
}
]
},
"installed_typelib": {
"guid": "{4ADEF4E1-690A-11CE-9261-0020C5E26659}",
"major_version": 1,
"minor_version": 0,
"type_count": 223,
"interfaces": {
"IVdApp": [
{
"name": "ExecuteCommand",
"dispid": 29,
"parameters": [
"CommandString"
],
"argument_types": [
[
8,
1
]
],
"return_type": [
11,
0
]
},
{
"name": "QueryPages",
"dispid": 46,
"parameters": [
"Name"
],
"argument_types": [
[
8,
1
]
],
"return_type": [
[
26,
[
29,
50338560
]
],
0
]
},
{
"name": "DesignComponents",
"dispid": 59,
"parameters": [
"Library",
"Name",
"EndSheet",
"LevelString",
"RecurseDown"
],
"argument_types": [
[
8,
1
],
[
8,
1
],
[
8,
49
],
[
8,
49
],
[
11,
49
]
],
"return_type": [
[
26,
[
29,
50338560
]
],
32
]
},
{
"name": "GetProjectData",
"dispid": 228,
"parameters": [],
"argument_types": [],
"return_type": [
[
26,
[
29,
50343040
]
],
0
]
},
{
"name": "SelectComponent",
"dispid": 266,
"parameters": [
"sSchName",
"sSheetName",
"sCompUID"
],
"argument_types": [
[
8,
1
],
[
8,
1
],
[
8,
1
]
],
"return_type": [
11,
0
]
}
],
"IVdView": [
{
"name": "SelectByName",
"dispid": 1,
"parameters": [
"Name"
],
"argument_types": [
[
8,
1
]
],
"return_type": [
11,
0
]
},
{
"name": "SelectObject",
"dispid": 12,
"parameters": [
"ObjectType",
"Expression",
"SelectOwner",
"RegExp",
"AddSelect"
],
"argument_types": [
[
[
29,
50334848
],
1
],
[
8,
1
],
[
11,
1
],
[
11,
1
],
[
11,
1
]
],
"return_type": [
22,
0
]
}
],
"IVdBlock": [
{
"name": "DeSelectAll",
"dispid": 14,
"parameters": [],
"argument_types": [],
"return_type": [
24,
0
]
},
{
"name": "ChangeComponent",
"dispid": 24,
"parameters": [
"OldComp",
"NewComp"
],
"argument_types": [
[
8,
1
],
[
8,
1
]
],
"return_type": [
11,
0
]
},
{
"name": "ChangeComponentPreserveRefdes",
"dispid": 42,
"parameters": [
"OldComp",
"NewComp"
],
"argument_types": [
[
8,
1
],
[
8,
1
]
],
"return_type": [
11,
0
]
}
],
"IVdComp": [
{
"name": "Selected",
"dispid": 26,
"parameters": [],
"argument_types": [
[
11,
1
]
],
"return_type": [
24,
0
]
},
{
"name": "_SetSelected",
"dispid": 12,
"parameters": [
"Flag"
],
"argument_types": [
[
22,
1
]
],
"return_type": [
24,
0
]
}
],
"ICommandsManager": [
{
"name": "ExecuteCommand",
"dispid": 307,
"parameters": [
"CommandString"
],
"argument_types": [
[
8,
1
]
],
"return_type": [
11,
0
]
}
],
"IVdAppProtectionProxy": [
{
"name": "ExecuteCommand",
"dispid": 29,
"parameters": [
"CommandString"
],
"argument_types": [
[
8,
1
]
],
"return_type": [
11,
0
]
},
{
"name": "QueryPages",
"dispid": 46,
"parameters": [
"Name"
],
"argument_types": [
[
8,
1
]
],
"return_type": [
[
26,
[
29,
50338560
]
],
0
]
},
{
"name": "DesignComponents",
"dispid": 59,
"parameters": [
"Library",
"Name",
"EndSheet",
"LevelString",
"RecurseDown"
],
"argument_types": [
[
8,
1
],
[
8,
1
],
[
8,
49
],
[
8,
49
],
[
11,
49
]
],
"return_type": [
[
26,
[
29,
50338560
]
],
32
]
},
{
"name": "GetProjectData",
"dispid": 228,
"parameters": [],
"argument_types": [],
"return_type": [
[
26,
[
29,
50343040
]
],
0
]
},
{
"name": "SelectComponent",
"dispid": 266,
"parameters": [
"sSchName",
"sSheetName",
"sCompUID"
],
"argument_types": [
[
8,
1
],
[
8,
1
],
[
8,
1
]
],
"return_type": [
11,
0
]
}
]
}
},
"wrapper_matches_installed_version": false
}
+54
View File
@@ -0,0 +1,54 @@
# 1.1.2 代码精简与启动/BOM 审查
审查起点:`136d7ff`。本轮不打包、不发布,不启动 CAD;原始工程、BOM 与既有实测证据不参与写入。
## 结论与已处理项
代码确实有历史包袱,但不能按文件大小直接删除。审查起点 Python 生产源码 86 个文件、22,564 行,其中旧 `part_replace` 为 7,503 行;测试目录约 30,337 行,不属于生产包源码。通过检查 GUI、CLI、VBS 动态调用和打包入口,本轮确认并处理以下内容。
1. 删除 `ui/project_table.py` 的孤立工程列表控件(122 行)。当前窗口使用单工程摘要与位号计划;生产代码、工具、菜单和打包配置均未引用旧控件。
2. 删除 `TargetTable.item()` / `_CellAdapter`。它们只为测试模拟旧 QTableWidget 接口;相关用例现直接通过真实 QTableView model 修改、勾选与读取,排序后的 UID 绑定覆盖继续保留。
3. 删除未使用的私有导入,保留真实使用的批量备份、协议和包导出。
4. 合并 BOM 普通预览与报告校验引擎。`preview_batch` 保留严格调用接口,以同一份 `inspect_batch` 结果返回预览或报错,不再独立维护采集、路由、匹配和编辑保留逻辑。
5. `BomMatcher` 对一个工程的位号清单只建立一次索引,逐行仅返回实际命中的目标。每行校验与最终合并校验均保留,继续拒绝重复目标、歧义位号、替换链和循环;未导入位号的原编辑保留。
6. 修复损坏 Excel 在普通预览中被误报为未处理异常的问题;按 BOM 导入错误报告。
7. 修复读表过程中取消被 ValueError 捕获并转成 BOM 错误的问题。`TaskCenterError` 是 ValueError 子类,需先传播操作异常;inspect/strict 两入口均验证保留 `operation_cancelled`,没有采集或部分保存。
8. 启动恢复统一由 runner 完成,删除 application 提前恢复。旧顺序会先修改数据库,使 runner 来不及记录恢复前/后事件。迁移恢复、确认迁移记录和旧运行任务协调均保留。
9. 通过按中断状态过滤的一次 SQL 查询替代逐任务读取工程;30 个空闲任务场景不再产生 30 次逐任务工程读取。
10. Windows 启动诊断改用 `sys.getwindowsversion()`,避免仅为了记录 OS 信息就启动 WMI 查询。审查期间真实遇到 `platform._wmi_query` 的 `0x8007000e` 异常;这项修正与 CAD COM 绑定问题分别处理。
生产源码相对起点净减少 **186 行**,减少 1 个模块。新增的索引类替代重复构建和扫描,不是简单把大文件挪到另一个文件。
## 保留依据
| 范围 | 仍存在的调用 |
| --- | --- |
| 旧 `part_replace` CLI | pyproject 公开入口、`python -m dx_productivity`、Start-PartReplacement.ps1 的 discover/status/create/operator-step |
| 人工 runner / comparison / evidence | 旧服务入口、历史任务恢复、迁移事件与证据校验;GUI 的规则检查仍跨包复用 inputs |
| SceneOS | application 的 `--sceneos-cli` 分派仍存在 |
| 菜单和 VBS 桥 | MenuRuntime 的 ExecuteGlobal 动态加载,不能仅依靠 Python import 搜索判死 |
| QuickPartReplace / native_helper | 当前原生替换、私有桌面子进程仍使用,打包配置显式包含 VBS |
`quick_run.py`、`service.py`、`store.py` 仍然偏大。进一步分职责需要检查协议和兼容入口;本轮未引入另一套执行架构或删除仍被调用的功能。
## 验证
- 位号编辑、排序和单工程 UI:11 passed。
- BOM、库存扩展、事务、任务上下文、UI 草稿和重复轮次选定回归:99 passed,31.19 秒。
- 启动、旧人工流程和应用引导:37 passed,21.39 秒,包括历史迁移恢复和恢复前/后事件。
- 审查末尾读表取消与启动恢复检查:12 passed,23.55 秒。上述检查有重叠,不相加为总用例数。
- 另运行真实 Qt 的 offscreen 应用启动/关闭 smoke;数据目录位于 `build/code-pruning-startup-smoke-20261015`。
- 只读复核代理确认原生保存/恢复事务、目标身份、NC 与 Value 处理边界未削弱;其指出的读表取消错误已修复。
## BOM 模拟规模测量
使用 1000 个模拟位号、真实 XLSX 的 200 条替换行,包含工程匹配、逐行校验和预览构建,不启动 CAD。
| 版本 | 结果 |
| --- | --- |
| 精简前 | 探针进程运行 285.36 秒仍未完成,主动停止;该值包含建库和生成模板,不能视为完整匹配耗时 |
| 精简后 | 校验阶段 5.920 秒,200 行通过、0 行失败,1000 个位号中恰好启用 200 个 |
临时探针位于 `build/probe-bom-scale-audit.py`,前后结果分别保留在 `build/bom-scale-before-20261015/metrics.json` 和 `build/bom-scale-after-20261015/metrics.json`。未将一次性探针加入生产代码。
此结果不能换算成完整 CAD 替换速度。上一轮千步执行测试未达到 30 秒目标、CAD COM 启动偶发阻塞,仍是独立的未解决项。
@@ -0,0 +1,41 @@
# 1.1.2 位号计划响应与内存审查
起点 `224f4e7`。本轮不打包;使用模拟库存、真实 Excel 和 Qt 事件循环进行验证,不启动 CAD。
## 已处理
- `ComponentTarget.key` 被循环调用时重复访问文件系统。500 个启用位号的规则编译原需 1500 次解析,同规模库存合并需 3500 次。增加单次校验内的 `ProjectIdentityResolver`,按原始路径字符串复用解析结果;编译、合并、数据库保存及 BOM 索引各有独立作用域。
- BOM 表格路由重复解析同一个工程路径;改为仅在本次读表阶段复用,原生采集后不复用该路由缓存检查工程身份。
- UI 修改一个单元格时,摘要会复制并统计全表,执行按钮保护又以元组成员查询扫描全部任务。现在模型维护启用数量,摘要读取源模型数量;任务 ID 使用集合,同次按钮更新只计算一次本批未保存状态。
- 已保存或放弃的 BOM 报表仍强引用整份预览,包括原库存和计划。现在只释放结束的预览,保留校验行、数量和说明;未保存预览和失败后可重试的数据继续保留。
## 保护边界
解析器不跨刷新、采集或保存操作持续缓存;单独访问 `ComponentTarget.key` 仍即时解析。大小写规范、原理图/图页/UID、位号、旧料号、旧 Value 的比对仍保留。数据库事务、保存前基线复核、原生路径访问检查和恢复保护没有减少。
排序和筛选后的编辑继续按原始 UID 写回;摘要按当前工程全部源数据统计。只有相关 BOM 工程全部保存成功或明确放弃时,才释放报告中的预览引用。
## 本机测量
| 场景 | 优化前 | 优化后 |
| --- | --- | --- |
| 500 位号规则编译 | 0.543 秒 / 1500 次路径解析 | 0.00274 秒 / 1 次 |
| 500 位号库存合并 | 1.299 秒 / 3500 次路径解析 | 0.00666 秒 / 1 次 |
| 模拟 3000 任务、3000 位号,本地改单元格,5 次平均 | 41.56 毫秒 | 1.60 毫秒 |
| 1000 模拟位号、200 行真实 XLSX 校验 | 上轮 5.920 秒 | 0.143 秒;200 行通过、0 行失败 |
这些数值只覆盖上述本地处理,不包含 CAD 启动、采集和实际替换。路径耗时为单次对照,不能视为所有机器的固定收益。
临时探针和结果保留在 build:
- `probe-plan-identity.py`;`plan-identity-before-20261015/metrics.json`、`plan-identity-after-20261015/metrics.json`。
- `probe-local-plan-edit.py`;`local-plan-edit-before-20261015/metrics.json`、`local-plan-edit-after-20261015/metrics.json`。
- `probe-bom-scale-audit.py`;`bom-scale-identity-after-20261015/metrics.json`。
## 验证
先复现重复解析和保存/放弃后预览未释放,再修正。路径用例还确认下一次操作会重新解析;弱引用用例确认预览可回收而报告仍可查看。
本轮针对目标身份、命令、恢复、BOM、库存扩展、长路径、UI、草稿和新轮次共 **169 passed,22.58 秒**。只读审查复核了缓存范围、完整基线字段、筛选统计和保存失败保护,未发现新的重要问题。未为本轮局部优化重复运行整套测试或 CAD。
仍待解决:CAD COM 偶发启动阻塞、千步执行的 30 秒目标,以及大执行模块进一步按职责整理。本轮不对这些项目作完成声明。
@@ -0,0 +1,55 @@
# 1.1.2 可用性与发布条件评估
评估基线:`ce574dd`,2026-10-15。本轮查询公开官方资料、运行构建脚本采用的源码检查、审查现有成品和使用说明;没有构建、启动 CAD、改工程、打标签或发布。
## 判断
| 问题 | 当前判断 | 证据边界 |
| --- | --- | --- |
| 可以用吗 | 支持本机已验证环境内的工程副本试用 | 核心 BOM、多工程顺序执行、部分位号替换、保存重开回读、完成后新轮次有实机证据;不同现场/库未统一验收 |
| 好用了吗 | 日常流程已成形,UI 的重复构建问题已改善;首次采集和 CAD 启动仍慢 | UI 与本地数据性能不能代表原生 CAD 速度,不能把一个审查者的判断等同于用户验收 |
| 可直接正式发布吗 | 暂不建议宣称稳定正式版 | 最新源码尚无对应冻结成品全流程验收;偶发原生启动阻塞根因未闭环;交付文档存在旧界面说明 |
| 能否准备试用版 | 可以进入候选包验证,完成下列交付检查后提供评估包 | 仍按原有 evaluation-only 定位,不需要为试用另起 UI 框架或做全部扩展功能 |
本轮按 `packaging/Build-DxPartReplace.ps1` 的源码检查范围执行:
```powershell
python -m pytest -q tests/v1_1 tests/trial_task_center/test_application.py tests/trial_task_center/test_execution_safety.py tests/part_replace/test_verification.py --junitxml=build/release-research-20261015/current-release-gate.xml
```
结果:**369 passed,1 warning,76.47 秒**。警告为 pywinauto 的 COM STA 模式提示。此结果不包含 PyInstaller 构建、冻结包运行、真实 CAD 替换或默认目录之外的千步性能用例,不能概括成“全部发布验收通过”。
## 已有真实能力
- 两工程创建任务、导出默认 11 列 BOM、填写部分位号、失败行提示、修正后导入、预览和整批保存;失败导入不保存半批。
- 两轮真实替换及全新 CAD 会话独立回读,未选中的同料号位号保持不变;302 字符工程路径与 284 字符模板路径完成实际流程。
- Part Label 复制开关实际改变 Value 写入结果;NC 开关有单独原生验证。
- 后台私有桌面和自有 CAD 退出有观察证据,主桌面文件读取与用户原 CAD 未被接管。
- 规则/结果使用 Model/View,详情按需创建、关闭释放,隐藏 tab 不渲染;草稿、结果数据与控件生命周期独立。
证据:`docs/testing/2026-10-15-bom-live-roundtrip.md`、`2026-10-15-part-label-live.md`、`2026-10-15-project-session-and-read-model.md`,及 `docs/reviews/2026-10-15-ui-component-lifetime.md`。后续 UI 修改使用复制数据库复放和专项回归,没有在每个提交重复运行真实替换。
## 发布前实际缺口
1. **最新成品身份和冻结运行验证。** 当前 `dist/DxPartReplace` 对应旧的 `714ac0b` 候选,不是本次 `ce574dd`;已发布 1.1.1 对应 `7610a0f`。先固定待发布提交、构建并生成版本/commit/EXE/VBS/ZIP 哈希清单,再从最终 ZIP 解压运行。确认源码路径不参与加载,实际打开按需日志/结果/BOM 窗口、完成模板导入,并在旧 `data` 副本上验证升级。现有 `--smoke-test` 只覆盖空白根目录启动退出,不覆盖这些交互。正式承诺新版完整替换前,再用最终冻结包的独立工程副本做有代表性的 BOM→替换→回读→释放验收。
2. **CAD 启动稳定性和等待体验。** 已观察到 GetActiveObject/QueryInterface 偶发阻塞;120 秒预算和清理机制限制了等待,不代表根因已修。既有成功样本的 CAD 启动约 27–67 秒,首次采集也可能超过一分钟。应对已有失败条件定位和补测,明确启动/就绪/取消状态;保留超时、身份及退出证据。不能仅凭 UI 更快就承诺执行更快。
3. **干净分发目录和正确说明。** 构建脚本会保存并恢复本机 `data`,这是保护本机数据;应另建干净 staging 排除本机任务、日志、数据库和备份,再压缩。使用说明仍有“完成任务自动显示全部日志”“当前界面保留 Capture Before/After”等过期描述,需要按实际按需分页和一工程一任务流程统一。README 当前仍明示未发布和 evaluation-only,发布时不能只改标题为稳定版。
本轮另单独执行 `tests/trial_task_center/test_batch.py::test_thousand_item_multisheet_mixed_queue_has_bounded_runtime_and_memory`,结果 **1 passed,测试总计 33.17 秒**。其中被断言的执行区间 **29.517 秒**,通过原有 `<30秒` 门槛;1000 步、91 步保存、909 步未命中,唯一性和完成状态通过,tracemalloc 峰值 2,200,063 字节,约 33.88 步/秒。原始指标为 `build/release-research-20261015/queue-stress-metrics.json`,JUnit 为同目录 `queue-performance-gate.xml`。此次达标应更新之前“尚未通过”的当前状态;但接近门槛、仅单次测量,不承诺跨机器稳定达标。该测试是模拟 worker 的兼容队列,不能作为新任务模式实际 CAD 的吞吐量。
## 网上可借鉴的规则
| 官方资料 | 原则 | 本工具的落点 |
| --- | --- | --- |
| [Microsoft PowerRename](https://learn.microsoft.com/en-us/windows/powertoys/powerrename) | 批量操作前对照原值与新值、预览实际变更,可筛选仅显示匹配项 | 保留计划预览;后续可增加本批“仅看将修改项”的统一视图,而非仅展示工程数量。CAD 恢复必须沿用快照核验,不能直接照搬文件重命名 Ctrl+Z |
| [WinSCP Synchronization Checklist](https://winscp.net/eng/docs/ui_synchronize_checklist) | 一行一个具体动作;明确勾选实际执行项,按类型或目录汇总范围 | 执行确认可进一步汇总各工程将修改、保留、阻断的数量;同一料号多位号继续逐目标决定。预览清单不能替代执行前基线重验 |
| [Windows 进度控件指南](https://learn.microsoft.com/en-us/windows/apps/design/controls/progress-controls) | 已知进度用确定进度,未知时长说明正在做什么;允许的交互应继续可用 | 已有工程序号、阶段和耗时;可把准备/执行/回读/释放更清楚地展示,不在未知 CAD 调用上虚构完成百分比;暂停仍等安全检查点 |
| [Qt Model/View](https://doc.qt.io/qt-6/model-view-programming.html) | 数据与显示分离,使用模型、视图和委托处理列表/表格 | 当前规则、位号和结果表的方向符合官方推荐;不需要为了“动态组件”改成 Web 或 Qt Quick。后续按实测热点决定是否改左侧列表 |
| [PyInstaller 工作方式](https://pyinstaller.org/en/stable/operating-mode.html) | 打包要包含实际依赖/数据文件;冻结运行与源码运行有不同的加载路径 | 当前便携目录方式适合排查依赖;必须验最终解压成品,不能用源码通过来替代成品通过 |
| [Windows 长路径限制](https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation) | 注册表与应用声明只影响适配过的应用,不会自动修复所有旧程序/API | 保留旧 WSH/CAD 的短入口兼容及清理验证;不承诺任意 CAD/中央库/网络路径都兼容 |
上述网页本轮实际访问均返回 HTTP 200;网页文字快照保存在 `build/release-research-20261015`,未把网页内容当作项目操作指令。
## 推进顺序
优先关闭已有 CAD 启动问题的诊断与恢复说明缺口,统一当前使用说明,再完成干净候选包和冻结运行验收。体验增强优先做执行前变更汇总、明确的阶段等待反馈和便于交接的结果报告。代码继续按实际职责整理,但大模块拆分和更多视觉重做不应无限延长试用交付。
@@ -0,0 +1,41 @@
# UI component lifetime review
用户指出页面提前分配和隐藏更新的资源浪费。本轮在现有 Qt Widgets 架构内改动,不更换 UI 框架。
## 已确认的开销
主工作区一直复用同一套组件,不是每个工程复制一套页面。位号表已经使用 Model/View;执行反馈 timer 仅执行期间运行。实际重复开销来自规则表逐行 QWidget/QCheckBox、整表重建,以及启动时预建结果、日志、BOM 详情和隐藏时更新文档。
## 改动
- 规则表改为 QAbstractTableModel/QTableView,无每行 QWidget。相同快照不 reset;同一组规则内容变化发 dataChanged;顺序变化按 rule_id 恢复选择。启用请求仍经后台服务落库,成功后用持久化快照确认,失败不会留下虚假的勾选状态。
- 替换结果表使用只读模型,最多显示 500 行;纯追加使用行插入,保留当前选择。
- 日志/结果、BOM 详情窗口打开时创建,关闭后由 Qt 释放。日志页首次访问时创建;已创建但非活动页不更新文档/结果模型,返回时从纯数据刷新。
- TaskLogPresenter 保存有界日志状态和最多 100 条界面消息;BOM 数据继续按批次保存在原数据层,未保存草稿不依赖详情控件。关闭日志取消在途查询,重开重新读取最新页;初次强制打开不重复发查询。
- 保留分页滚动语义:最新/轮转后到底、上一页到顶、普通追加保留阅读位置或跟随底部。
## 资源与耗时
运行 `python tools/measure_ui_components.py --revision 84d8f9c` 与省略 revision 的当前版本。每版独立进程,各三次,表格 1000 条规则;耗时为中位数。
| 指标 | 修改前 | 修改后 |
| --- | ---: | ---: |
| 规则表首次绑定数据 | 405.44 ms | 0.25 ms |
| 相同规则刷新 | 383.80 ms | 0.02 ms |
| 规则表 QWidget 子控件 | 2018 | 18 |
| 独立 QCheckBox | 1000 | 0 |
| 执行面板未打开详情时的 QWidget 子控件 | 49 | 12 |
以上计时包含 populate 的同步工作,不包含窗口首次绘制、数据库读取或 CAD;控件数量不等同于进程内存。新模型仍保存规则数据,只在可见区域绘制。
原始 JSON:`build/ui-components-20261015/before.json`、`after.json`。复现工具已纳入 Git。
## 验证范围
针对 Qt 生命周期、原生委托勾选/服务持久化、选中保留、分页滚动、关闭期间在途查询、立即重开、切换任务、BOM 校验/批次草稿以及原工作区回归进行验证。
最终针对性回归 **63 passed, 30.72s**,范围为 `test_lazy_components.py`、`test_execution_results_view.py`、`test_ui_responsiveness.py`、`test_ui_workspace.py`、`test_replacement_logs.py`、`test_bom_batch.py`、`test_bom_import_report.py`、`test_ui_remediation.py`。新增资源生命周期用例在修改前观察到 4 项预期失败,修改后通过。只读审查指出的分页滚动和结果追加选择丢失均已修正并覆盖。
使用 `tools/probe_workspace_layout.py` 复制 `build/bom-native-roundtrip-fixed-20261015` 证据数据库复放,输出在 `build/ui-components-layout-20261015`。980×700 实际尺寸保持,位号表 viewport 高 135px;执行、BOM 模板、Value 策略可见;执行结果显示已有真实回读记录;跨批报告隐藏、返回恢复;源数据库 SHA256 不变。检查了结果截图。
本轮未运行真实替换、未启动 CAD、未打包或发布。此前 CAD 原生连接偶发阻塞、千步执行性能问题不属于本轮结论。
@@ -0,0 +1,59 @@
# Task 1 report: single-project context and isolated worker
Implemented the backend portion of the single-project workflow without starting
CAD, packaging, or modifying project files.
## Public API
`TaskCenterService.task_context(task_id: str) -> ProjectTaskContext` returns a
fresh immutable context for UI refreshes; only the per-task service facade is
cached. `TaskCenterService.refresh_bound_project(task_id:
str) -> ProjectTaskContext` rereads the task and its bound project from SQLite,
without scanning a directory or attaching COM. A bound task must have one
`primary_project_id` and exactly one project. Historical tasks without that
binding remain available through `task_context` with `legacy=True` and
`project=None`; `refresh_bound_project` rejects them so new execution cannot
accidentally mutate a multi-project record.
`ProjectTaskContext` fields are:
```python
ProjectTaskContext(
task, project, rules, targets, progress, phase,
has_evidence, interrupted, legacy
)
```
The target plan is authoritative for target-plan tasks. An empty or fully
disabled plan produces zero queued items and never falls back to broad mapping
rules.
`IsolatedDesktopWorker` is an opt-in research boundary. Its request contract is
`IsolatedWorkerRequest(protocol_version, task_id, project_path, target_uids,
plan_hash, allow_writes=False)`. `run()` rejects the default disabled mode,
rejects unrelated existing CAD identity, rejects write enablement, and emits
versioned `request.json`/`evidence.json` files when an evidence root is given.
It does not attach COM or launch CAD.
`PrivateDesktop` owns the Windows desktop handle and processes started with
`STARTUPINFO.lpDesktop="winsta0\\<private>"`; launch uses pywin32
`CreateProcess`, a Job Object with kill-on-close, and fails when no private
desktop was created, so there is no input-desktop fallback. Cleanup terminates
only processes created by the worker and closes the owned desktop handle.
`IsolatedDesktopWorker.read_only_probe(request, cad_probe, evidence_root=...)`
is the usable native boundary: it runs the injected native reader inside the
owned private desktop, then checks its `CadIdentity(pid, project_path)` against
the request before `read_only_verified` evidence is published. The worker
refuses unrelated CAD identity and write enablement. It remains opt-in and does
not mutate CAD.
## Verification
- `tests/v1_1/test_project_context.py` and `test_isolated_desktop.py`: **11 passed**.
- Existing target/quick-run checks (`test_service_target_integration.py`,
`test_target_execution.py`): **8 passed**.
- Python bytecode compilation passed for all changed backend modules.
The private desktop path remains research-only until a native DxDesigner build
is validated on a disposable project; no production write claims are made.
@@ -0,0 +1,44 @@
# Single-project UI and background worker implementation plan
> For agentic workers: use subagent-driven-development for the backend task and inline implementation for the UI; review the combined branch before integration.
Goal: implement the approved single-project workflow and research desktop backend without packaging.
Architecture: one context read replaces repeated multi-project UI queries; independent process supervision contains CAD automation. Existing persistence and execution safeguards remain authoritative.
Tech stack: Python 3.12, PySide6, SQLite, Win32/COM, ASCII VBS.
Spec: docs/superpowers/specs/2026-10-14-single-project-ui-background-design.md
## Global constraints
- Keep V1.1.0, do not package; commit each verified feature block.
- One immutable bound project per new task; preserve historical data.
- Default tests remain fast; no full legacy suite or production CAD writes.
- No background claim without native validation; private desktop stays opt-in research.
- No empty target fallback, unsaved-plan execution, unrelated CAD attachment or unsafe write interruption.
## Task 1 — single-project context and isolated worker
Owned by backend implementer: service.py; new project_context.py, isolated_desktop.py, isolated_worker.py; necessary quick_run/native_helper/VBS boundary edits; tests/v1_1/test_project_context.py and test_isolated_desktop.py. No UI files.
- [ ] Prove bound context returns one project and cached task facade; reject mutable project membership on bound tasks. Include empty/disabled target plans and legacy read-only context cases.
- [ ] Produce service.task_context(task_id), service.refresh_bound_project(task_id), and immutable ProjectTaskContext(task, project, rules, targets, progress, phase, has_evidence, interrupted, legacy).
- [ ] Build opt-in private desktop worker using CreateDesktop, STARTUPINFO.lpDesktop, owned process tree and versioned request/evidence. Reject existing unrelated CAD, verify CAD PID/project before COM use and retain safe write-boundary pause semantics. Give root exact API for UI context and backend integration.
- [ ] Run focused context/worker safety tests, write task report, commit only owned files.
## Task 2 — UI cleanup and search
Owned by root: ui/main_window.py, run_panel.py, project_plan.py, target_table.py, task_list.py; new project_summary.py and execution_state.py if useful; UI tests and docs.
- [ ] Add behavior checks for no multi-project controls, current-task scope, Find/Next/Clear preserving hidden plan rows and hidden drafts blocking group execution.
- [ ] Replace task-details project table with immutable summary and refresh; remove manual-run/project-select code and use ProjectTaskContext for local gates.
- [ ] Keep task creation modal; add cached plan search, clear/next, correct visible-row bulk operations and ordered task list.
- [ ] Wire execution/retry/recovery/pause controls with consistent labels and one confirmation summary; prevent conflicting edits while workers run.
- [ ] Run focused UI tests, inspect offscreen screenshot, document workflow and commit.
## Task 3 — review and integration
- [ ] Review combined diffs for target scope, stale UI callbacks, locks, legacy handling and isolated desktop lifecycle. Fix material findings with focused checks.
- [ ] Run default behavior suite plus only impacted safety modules; record counts/times and limitations. No packaging.
- [ ] Commit review fixes and integrate verified changes locally without overwriting user edits.
@@ -0,0 +1,62 @@
# V1.1.0 Project Tasks Implementation Plan
> **For agentic workers:** Use superpowers:subagent-driven-development task-by-task. Steps use checkbox syntax.
**Goal:** Iterate the existing replacement application with single-project tasks, editable per-component plans, optional Excel imports and serial task execution.
**Architecture:** Reuse the existing desktop service/store and native replacement helper. Add focused plan/inventory/queue modules with stable target identities and transactional persistence. Keep historic jobs and an explicit legacy test entry point.
**Tech Stack:** Python 3.12, SQLite, PySide6, ASCII VBScript; openpyxl for XLSX files.
**Spec:** docs/superpowers/specs/2026-10-14-v1.1.0-project-tasks-design.md
## Global Constraints
- Version 1.1.0; retain existing task view and direct editing.
- Each directory-created task owns exactly one .prj; historical tasks are preserved.
- Explicit empty targets never mean all matches.
- UID + schematic + sheet + expected RefDes + old Part Number identify targets.
- Default NC synchronization remains on and is editable in UI/import; independent /NC only.
- Existing Replace Part + Library Wins, backup and saved readback remain required.
- No production CAD writes for interface research or tests.
- Default tests are fast behavior tests; historic regressions are explicit and preserved.
---
## Task 1: Persistence, inventory, plans and target execution
Files: models.py, store.py, service.py, quick_run.py, recovery.py, QuickPartReplace.vbs; create target_plan.py, inventory.py, spreadsheet_plan.py and project_tasks.py as focused modules; tests/v1_1/test_project_tasks.py, test_target_plan.py, test_inventory.py, test_spreadsheet_plan.py, test_target_execution.py.
Interfaces consumed: TaskStore transaction(), create_task(), sync_projects(); QuickRunPreparer and existing sheet discovery. Produced: directory task creation, task inventory, target plan edit/import/export APIs and versioned target-aware queue preparation. Define exact signatures in the implementation report for UI/task queue integration.
- [x] Write failing behavior tests for two .prj files creating two single-project tasks, duplicate scanning not duplicating active tasks, same names differentiated by relative path; run these tests and observe missing APIs.
- [x] Implement transaction-backed group/order/project binding and migrations; maintain legacy constructor defaults. Test transaction rollback and reopen.
- [x] Write failing tests using injected inventory rows for same old part on R1/R2/R3: selecting R1/R3 yields only those UIDs; R2 stays excluded; missing target errors, empty target errors, conflicting imports and equal/chain/cycle rules error.
- [x] Implement component inventory read mode on existing discovery route, collecting effective Value and all stable identifiers without pin/attribute full snapshots; do not save while scanning.
- [x] Implement target rule grouping and target-aware command/snapshot/recovery freeze validation in both Python and VBS. Run isolated VBS contract tests and native_helper mocks; tests must prove selectors survive recovery and stale targets do not become no_match.
- [x] Add openpyxl reader/writer using explicit columns and literal values; parse whole workbook, validate identity and duplicates, then commit atomically. Test roundtrip editing new part, Value and NC plus forged UID and duplicate row rejection.
- [x] Run V1.1 behavior tests and relevant existing inputs/value/recovery tests; commit this task only after covering tests pass and report API signatures and validation limits.
## Task 2: Cross-task scheduler and existing UI integration
Files: task_queue.py; ui/main_window.py, task_list.py, mapping_table.py; tests/v1_1/test_task_queue.py, test_project_task_ui.py.
Consumed APIs: Task 1 report; existing service.execute_quick_run_queue/quick_run_progress and safe pause. Produced APIs: fixed ordered task queue runner and UI directory wizard/inventory target table/Excel optional entry points.
- [x] Write failing scheduler test with fake runner logging starts/ends: A completes before B starts; pause leaves B unstarted; uncertain A prevents B; safe ordinary A failure allows B and summary records both.
- [x] Implement scheduler with per-task evidence paths and fixed IDs/plan fingerprints; reject same-project concurrent tasks, preserve active task evidence on resume.
- [x] Add directory scanner/create dialog to existing New action with project checkboxes and async scan; existing edit/name notes and historical view survive. Show counts and execution order, support ordering and group start/pause.
- [x] Add Collect Targets action and editable target table: per row enabled/new part/custom Value/NC controls; preserve existing rule dialog/full-match path. Excel import/export optional actions use same plan validation; blank typed target lists rejected rather than matching all.
- [x] Verify Qt widgets with offscreen smoke interactions and scheduler failure/lock tests. Commit after tests pass.
## Task 3: Test entry points, version and deliverable verification
Files: pyproject.toml, version.py, packaging/Build-DxPartReplace.ps1, docs/user/v1.1.0-project-tasks.md, tests/conftest.py or tests/legacy/conftest.py, tools/test_v1_1.ps1 and tools/test_legacy.ps1.
- [x] Default testpaths becomes tests/v1_1. Keep existing directories reachable with explicit paths; scripts set local src PYTHONPATH to prevent unrelated installed dx_productivity package collisions.
- [x] Version pyproject and desktop to 1.1.0. Add openpyxl dependency and ensure packaging discovers it; update build QA commands to run V1.1 and meaningful safety regressions rather than reintroducing full slow suite implicitly.
- [x] Document new task/inventory/Excel/NC workflows, previous data migration and real CAD validation limits; include native research report.
- [x] Run default behavior suite, selected safety/Qt/VBS tests, compileall and build/frozen smoke if toolchain available. Review diff for selector fallback, evidence overwrites, migration loss and UI async locks; fix findings.
- [x] Bring verified commits into the main workspace without rewriting user work; supply V1.1.0 ZIP/EXE if build succeeds and distinguish code test results from live CAD acceptance.
Verification and implementation details: v1.1.0-task-1-report.md and v1.1.0-task-2-report.md. Live CAD acceptance remains outside offline verification.
@@ -0,0 +1,28 @@
# 执行响应与模块边界优化
用户已确认上一轮审查提出的优化方向。本计划在现有 V1.1.0 上增量实施,不打包、不推送。
## 设计和约束
- CAD 仍串行执行,保存、关闭、重开回读及不确定状态阻断继续保留。
- 查询与修改分开:任务和日志查询独立后台执行,过期结果不覆盖当前选择;执行过程中允许只读浏览其他任务。
- 日志默认加载最近一页,历史分页加载,实时更新按游标追加;轮转、截断、未完成行和任务切换不能丢失或串日志。
- 目录扫描可取消并显示进度;创建任务复用已选结果,重新校验路径、工程类型和扫描边界,避免重复递归。
- 采集生成的图页发现结果只在工程内容指纹仍一致且料号范围满足时复用;执行前的身份校验保持。
- 按职责提取查询控制器、日志读取、发现缓存及执行反馈接口,避免为了缩短文件破坏事务边界。
- 同工程跨步骤保持 CAD 打开的优化需要改变当前“一步一份持久结果”的恢复协议。本轮先通过发现缓存减少重复打开;不直接合并尚未验证的保存事务。
## 实施
- [x] 目录扫描取消、进度与创建阶段定向复核;验证取消不创建部分任务、边界和排除目录保护。
- [x] 发现缓存和公开执行器接口;验证命中、工程文件变化失效、料号范围及任务隔离。最终使用元数据加 SHA256 内容摘要,覆盖保留时间戳的等长修改。
- [x] 后台任务快照、后台增量分页日志、运行时只读导航及可靠完成回调;验证慢查询下事件循环仍响应、旧请求被丢弃、暂停可用。
- [x] 针对性回归、独立审查与响应计时报告;按功能及时提交 Git。
备份状态及预备份策略独立为 BatchBackupCoordinator,主执行函数约 304 行缩为 170 行。执行反馈使用独立只读快照接口;关闭窗口先废弃查询回调,进程退出前等待查询结束再关闭 SQLite。任务完成强制刷新最终日志,执行 A、查看 B 时明确标注 A 的结果。
审查记录:初审发现慢日志请求饿死和跨任务完成提示归属问题,均补测试修复;终审复现元数据指纹复用负结果漏洞,已改内容摘要并通过复审。完整记录见 `docs/testing/2026-10-15-execution-responsiveness.md`。
## 验证
真实 SQLite 和临时工程目录验证扫描及持久化;模拟外部 CAD 验证发现调用次数和缓存失效;Qt offscreen 用受控慢 I/O 验证事件循环、导航、关闭及回调归属。复用既有队列安全测试,不重复运行整套压力测试或更改原始工程。
@@ -0,0 +1,16 @@
# Packaged acceptance and window-only tutorial
Goal: validate the current frozen candidate and provide an instructional GIF captured solely from the application's own windows.
Scope: local candidate, no tag or remote release; preserve all existing data and user CAD processes. Use independent project/data copies. Do not inject fake successful replacement events.
- [x] Review prior evidence, current packaging and recording dependencies.
- [x] Correct obsolete log-window and historical-interface instructions.
- [x] Run the standard build checks and build the current source.
- [x] Stage a clean candidate, hash it, archive and extract it; use that extracted EXE for acceptance.
- [x] Operate the actual candidate UI to create project tasks, export/fill/import BOM, inspect rejected and accepted rows, edit/save, execute and inspect genuine results.
- [x] Verify saved engineering state, old-data-copy startup, lazy details and owned-process/desktop cleanup.
- [x] Produce window-only GIF(s) with step labels and explicit shortened waits; inspect exported frames.
- [x] Write the acceptance result and limitations in `docs/testing/2026-10-15-packaged-acceptance.md`.
Integration: commit and push the reproducible tooling, report, and GIF on the development branch. No tag or remote release.
@@ -0,0 +1,16 @@
# 私有桌面正式执行实施计划
**目标:** 完成用户已授权的私有桌面替换与释放闭环,不打包,及时提交并推送现有开发分支。
**设计:** `docs/superpowers/specs/2026-10-15-private-desktop-execution-design.md`。
- [x] 原生只读探针确认显式 CAD 启动、COM/窗口 PID 和桌面身份;用户现有 CAD 保持不动。
- [x] 加固 `isolated_desktop.py`:先绑定 Job 再恢复进程;等待退出;异常时逐项清理;验证自有进程及桌面释放。
- [x] 独立隔离执行模块接入 `worker_monitor.py`、`project_session.py` 和只读枚举;补齐 VBS、native helper 身份核验与正常退出。
- [x] 默认正式入口走隔离执行;继续兼容注入模拟执行器;打包入口支持所有必要 worker 参数。
- [x] 独立真实副本验证选中/未选中位号、NC 开关、逐步保存回读、暂停和异常清理,记录前台窗口/输入桌面及资源释放证据。
- [x] 定向回归与审查,记录限制并推送远端;不重复无关基础测试、不放宽既有门槛。
验证范围:私有桌面生命周期、PID 绑定、执行监督器和批量会话回归;原生操作由主代理串行执行。低层 Win32 资源模块可委派独立实现,其余集成由主代理负责,避免共享文件覆盖。
验证详情及未覆盖边界见 `docs/testing/2026-10-15-private-desktop-execution.md`。无活动图页时 ActiveViewHandle 可能陈旧;启动和退出使用显式自有 CAD、私有 ROT 与 GUID,活动图页读写才强制验证 HWND/PID。NC 开/关参与本次真实步骤,但样本没有独立 `/NC` 标记,不声称重新验收了 NC 转换效果。
@@ -0,0 +1,11 @@
# 按工程区分的批量 BOM
用户已明确选择:同批所有工程放在一张表,导入按工程列分配至各任务;先不要发布新版本。本地 1.1.2 旧候选不上传,不创建发布标签,不再次打包。
1. `bom_plan.py` 保留表格格式与单工程兼容,增加工程路径列;分离单次 Excel 解析和位号匹配。空白工程占位行允许未填写;未知工程、歧义位号、重复项及公式拒绝。
2. 新增 `bom_batch.py` 管理同批工程模板和不可变导入预览。模板在未采集时每个工程一行,旧/新料号和位号留空。导入先验证全部工程及可编辑状态;已有清单直接匹配,缺失清单按 BOM 旧料号只读采集。预览不写入数据库。
3. service 暴露整批预览/保存。保存重新检查原任务/工程归属和基线,在单个 SQLite 事务中写入所有受影响任务;一个失败则全部回滚。
4. 现有位号视图保留各任务预览草稿,允许切换任务检查和编辑;显示“保存本批位号计划”,保存整批后统一清理草稿。执行仍沿用每工程一任务和原串行队列,不重新维护多工程链表。
5. 针对测试:未采集即可导出全部工程、两个工程同名位号分别路由、未知工程不采集、不保存半批、新清单仅在确认后写入、未列出工程保持原计划、UI 跨任务预览和整批保存。运行相关回归;提供本地示例文件,及时提交,不发布。
完成:以上五项已实现。额外验证了已有库存不重复采集、任务重排后重导入可保存,以及无预设料号规则时整批保存后执行入口可用。相关回归 252 项通过;审查修正后 BOM/UI 最终定向回归 17 项通过。原生长路径采集 318 字符、13 位号通过;旧候选仅本地留存,未创建 1.1.2 标签或上传包。证据见 `docs/testing/data/2026-10-15-project-bom-and-long-path.json`。
@@ -0,0 +1,30 @@
# 工程会话、统一快照与可取消查询实施计划
用户已明确授权四项优化,在 `codex/execution-responsiveness` 上继续迭代,基线 `bc6b726`;完成后推送同名远端分支,不打包。
## 约束与设计
- 一个工程一个任务,CAD 串行,不能接管用户已打开的工程。
- 会话复用保留每步保存和重开回读检查点;同工程下一步复用上一步回读后仍由工具持有的工程及 worker。结束、暂停、换工程或失败时关闭自有会话,状态不确定则阻断。
- 持久 worker 使用带随机令牌的命令/应答,下一步仍复核冻结命令、图页及状态文件;复用不能绕过目标 UID/位号/旧料号、属性和连接核验。
- 原单步执行器兼容,测试注入的 worker 不强制采用原生持久会话。新 transport 与监控、状态读取独立。
- 一次任务读取使用同一数据库只读快照及同一次证据解析,得出进度、证据位置、中断状态,不能在查询中写入恢复状态。
- 慢查询使用协作取消 token、分段 checkpoint 与有界调度;旧请求失效后尽快退出,单次无法中断的系统 I/O 不冒充已取消。
- 数据库拆分迁移、位号计划等职责,继续共享同一个连接、锁和嵌套事务;协议模型/编解码与快照从 quick_run 分离,保留兼容导出。
## 任务
- [x] 统一文件执行快照与协议模块,改服务为一次读取,保留未知/损坏证据的保护;增加读取次数和一致性回归。
- [x] 可取消查询、分段读取及有界旧请求处理,验证快速切换、关闭、慢 I/O、旧回调隔离。
- [x] 拆分存储职责并新增一致的任务数据读取接口,验证迁移、回滚、目标计划与执行状态事务。
- [x] 持久工程 worker 与 VBS 循环,接入批量调度,验证每步检查点、同页/换页、暂停/失败/超时/外部修改保护。
- [x] 在独立真实工程副本测量单步与复用方式,独立回读选中和未选中位号;记录逐步耗时、启动和打开次数。
- [x] 针对性回归、独立审查、及时提交并推送远端,记录尚存的现场限制。
## 责任边界
快照/协议修改与执行 transport 仅在 quick_run 的导入及各自方法连接,避免覆盖彼此代码。查询 token 是跨 UI、服务和文件读取的公共依赖。存储拆分提供 `read_task_bundle(task_id, read_control=None)`,一次锁/事务返回 task、projects、rules、targets。真实 CAD 验证由主代理串行进行,其他代理只使用临时数据和模拟器。
## 核验记录
集成、快照/存储/监督器、会话及旧单步执行器兼容性去重合计 301 项通过。独立副本的两步实际替换从 113.175 秒降至 100.641 秒,2 个选中及 11 个保留位号均独立回读一致;原生三页未命中及中途关闭、外部编辑/外部工程保护通过。千步用例功能和内存通过,当前 41.516 秒、原基线同环境 42.453 秒,均未达到原 30 秒门槛,不放宽阈值。PON 原单步替换基线存在失败,未作为成功替换性能对照。详见 `docs/testing/2026-10-15-project-session-and-read-model.md`。
@@ -0,0 +1,16 @@
# UI component lifetime implementation plan
**Goal:** Reduce unnecessary UI allocation and hidden-page updates while retaining the existing workflow.
**Architecture:** Reuse the main task workspace. Render rules and results through Qt item models. Keep task logs and BOM report data outside disposable detail dialogs; create views only when opened and render only the active detail tab.
**Constraints:** Remain on the 1.1.2 development branch, preserve BOM/direct editing and batch drafts, do not package or release, do not launch CAD or alter original project/evidence data.
- [x] Establish allocation/timing baseline and failing resource-lifetime regressions.
- [x] Replace per-rule item widgets with QAbstractTableModel/QTableView; keep ordering, rule identity, persisted confirmation, lock gates and selection.
- [x] Extract disposable detail dialogs, lazy-load log tab, retain data independently, invalidate reads on closing and read latest on reopening.
- [x] Migrate UI callers, tests and evidence tools to explicit view/data APIs.
- [x] Verify lifecycle, paging, visible-only rendering, BOM drafts and actual Qt delegate interaction; reproduce UI layout using copied evidence.
- [x] Review changes and record measured results in `docs/reviews/2026-10-15-ui-component-lifetime.md`.
Integration: commit and push these changes on the existing `codex/execution-responsiveness` development branch; no release/tag/package.
@@ -0,0 +1,39 @@
# V1.1.0 Project Tasks Implementation Plan
> **For agentic workers:** Use superpowers:subagent-driven-development task-by-task. Steps use checkbox syntax.
**Goal:** Iterate the existing replacement application with single-project tasks, editable per-component plans, optional Excel imports and serial task execution.
**Architecture:** Reuse the existing desktop service/store and native replacement helper. Add focused plan/inventory/queue modules with stable target identities and transactional persistence. Keep historic jobs and an explicit legacy test entry point.
**Tech Stack:** Python 3.12, SQLite, PySide6, ASCII VBScript; openpyxl for XLSX files.
**Spec:** docs/superpowers/specs/2026-10-14-v1.1.0-project-tasks-design.md
## Global Constraints
- Version 1.1.0; retain existing task view and direct editing.
- Each directory-created task owns exactly one .prj; historical tasks are preserved.
- Explicit empty targets never mean all matches.
- UID + schematic + sheet + expected RefDes + old Part Number identify targets.
- Default NC synchronization remains on and is editable in UI/import; independent /NC only.
- Existing Replace Part + Library Wins, backup and saved readback remain required.
- No production CAD writes for interface research or tests.
- Default tests are fast behavior tests; historic regressions are explicit and preserved.
---
## Task 1: Persistence, inventory, plans and target execution
Files: models.py, store.py, service.py, quick_run.py, recovery.py, QuickPartReplace.vbs; create target_plan.py, inventory.py, spreadsheet_plan.py and project_tasks.py as focused modules; tests/v1_1/test_project_tasks.py, test_target_plan.py, test_inventory.py, test_spreadsheet_plan.py, test_target_execution.py.
Interfaces consumed: TaskStore transaction(), create_task(), sync_projects(); QuickRunPreparer and existing sheet discovery. Produced: directory task creation, task inventory, target plan edit/import/export APIs and versioned target-aware queue preparation. Define exact signatures in the implementation report for UI/task queue integration.
- [ ] Write failing behavior tests for two .prj files creating two single-project tasks, duplicate scanning not duplicating active tasks, same names differentiated by relative path; run these tests and observe missing APIs.
- [ ] Implement transaction-backed group/order/project binding and migrations; maintain legacy constructor defaults. Test transaction rollback and reopen.
- [ ] Write failing tests using injected inventory rows for same old part on R1/R2/R3: selecting R1/R3 yields only those UIDs; R2 stays excluded; missing target errors, empty target errors, conflicting imports and equal/chain/cycle rules error.
- [ ] Implement component inventory read mode on existing discovery route, collecting effective Value and all stable identifiers without pin/attribute full snapshots; do not save while scanning.
- [ ] Implement target rule grouping and target-aware command/snapshot/recovery freeze validation in both Python and VBS. Run isolated VBS contract tests and native_helper mocks; tests must prove selectors survive recovery and stale targets do not become no_match.
- [ ] Add openpyxl reader/writer using explicit columns and literal values; parse whole workbook, validate identity and duplicates, then commit atomically. Test roundtrip editing new part, Value and NC plus forged UID and duplicate row rejection.
- [ ] Run V1.1 behavior tests and relevant existing inputs/value/recovery tests; commit this task only after covering tests pass and report API signatures and validation limits.
@@ -0,0 +1,38 @@
# V1.1.0 Task 1 Backend Report
Task 1 implements single-project persistence, target inventory/plans, Excel interchange, target-aware queue preparation, native selector checks, and recovery bindings.
## APIs for UI and scheduler
- `TaskCenterService.create_project_tasks(root: Path, selected_paths: tuple[Path, ...] | None = None) -> tuple[TaskRecord, ...]`: scans a directory and creates one task per selected `.prj`; each task owns exactly one project. Active unfinished paths are deduplicated. Completed tasks may be recreated with a readable suffix.
- `TaskCenterService.scan_project_directory(root: Path) -> tuple[Path, ...]`: read-only directory scan.
- `TaskCenterService.collect_target_inventory(task_id: str, old_part_numbers: tuple[str, ...] | None = None) -> tuple[TargetPlanRow, ...]`: runs existing owned-project discovery in read mode and records stable `ComponentTarget` baselines. No save is requested from the CAD process.
- `TaskCenterService.target_plan(task_id: str) -> tuple[TargetPlanRow, ...]` and `replace_target_plan(task_id, rows)`: read/edit the plan. `store.record_target_inventory(task_id, targets)` is the trusted initial baseline operation. A plan edit cannot alter project/schematic/sheet/UID/RefDes/old-part/old-Value identity.
- `TaskCenterService.preview_target_plan(task_id, path)` validates an Excel workbook without writing; `import_target_plan(task_id, path)` validates then commits atomically; `export_target_plan(task_id, path)` writes explicit columns.
- `TaskCenterService.for_project_task(task_id) -> TaskCenterService`: returns a facade whose queue evidence root is `storage/tasks/<task_id>/quick-run`; the facade shares the store and logging context. Parent quick-run entry points delegate automatically for bound single-project tasks.
- `TaskCenterService.move_project_task(task_id, offset)` changes group ordering while the group is idle.
- `ComponentTarget(project_path, schematic_name, sheet_number, uid, refdes, old_part_number, old_value)` is immutable identity. `TargetPlanRow(target, enabled=False, new_part_number='', custom_value_enabled=False, custom_value='', sync_nc=True)` contains editable fields. NC defaults to enabled.
## Execution behavior
`TaskRecord.target_plan_mode` is set when inventory is recorded, including an explicitly empty inventory. Execution compiles only enabled target rows into `TargetRule` groups. An empty or all-disabled target plan raises `enabled_rule_required`; it never falls back to old-part full matching. Mixing target and full-match rules is rejected. Target queue rows carry `target_scope=targets` and encoded UID/RefDes/old-Value selectors.
The VBS helper validates selectors against the active project/sheet before capture and native replacement. Python native checks do the same and compare the unselected component baseline (UID, RefDes, Part Number, Value, Part Name, Part Label) before and after mutation. Recovery binds the selector set and snapshot hash to the transaction evidence. Native CAD operations remain uncalled by tests.
## Validation
Commands run from the worktree:
```text
PYTHONPATH=src python -m pytest tests/v1_1 -q
36 passed in 5.06s
PYTHONPATH=src python -m pytest tests/integration/test_quick_part_replace_contract.py tests/trial_task_center/test_recovery.py tests/trial_task_center/test_value_options.py -q
45 passed in 7.57s
```
The V1.1 suite covers transaction rollback/reopen, schema 5 to 6 migration, project deduplication and recreation, target subset isolation, empty target safety, forged identity rejection, Excel roundtrip/atomic validation, per-task evidence roots, native selector checks, unselected-change detection, and purge cleanup.
## Limits
Component inventory depends on the existing `QuickPartReplace.vbs` read-only discovery route and therefore requires a Windows DxDesigner installation for live collection. The test suite uses injected inventory rows and never performs production CAD writes. The native helper cannot prove arbitrary attributes that are not included in the recorded baseline; it checks the documented identity/value fields above.
@@ -0,0 +1,37 @@
# V1.1.0 Project Tasks Implementation Plan
> **For agentic workers:** Use superpowers:subagent-driven-development task-by-task. Steps use checkbox syntax.
**Goal:** Iterate the existing replacement application with single-project tasks, editable per-component plans, optional Excel imports and serial task execution.
**Architecture:** Reuse the existing desktop service/store and native replacement helper. Add focused plan/inventory/queue modules with stable target identities and transactional persistence. Keep historic jobs and an explicit legacy test entry point.
**Tech Stack:** Python 3.12, SQLite, PySide6, ASCII VBScript; openpyxl for XLSX files.
**Spec:** docs/superpowers/specs/2026-10-14-v1.1.0-project-tasks-design.md
## Global Constraints
- Version 1.1.0; retain existing task view and direct editing.
- Each directory-created task owns exactly one .prj; historical tasks are preserved.
- Explicit empty targets never mean all matches.
- UID + schematic + sheet + expected RefDes + old Part Number identify targets.
- Default NC synchronization remains on and is editable in UI/import; independent /NC only.
- Existing Replace Part + Library Wins, backup and saved readback remain required.
- No production CAD writes for interface research or tests.
- Default tests are fast behavior tests; historic regressions are explicit and preserved.
---
## Task 2: Cross-task scheduler and existing UI integration
Files: task_queue.py; ui/main_window.py, task_list.py, mapping_table.py; tests/v1_1/test_task_queue.py, test_project_task_ui.py.
Consumed APIs: Task 1 report; existing service.execute_quick_run_queue/quick_run_progress and safe pause. Produced APIs: fixed ordered task queue runner and UI directory wizard/inventory target table/Excel optional entry points.
- [ ] Write failing scheduler test with fake runner logging starts/ends: A completes before B starts; pause leaves B unstarted; uncertain A prevents B; safe ordinary A failure allows B and summary records both.
- [ ] Implement scheduler with per-task evidence paths and fixed IDs/plan fingerprints; reject same-project concurrent tasks, preserve active task evidence on resume.
- [ ] Add directory scanner/create dialog to existing New action with project checkboxes and async scan; existing edit/name notes and historical view survive. Show counts and execution order, support ordering and group start/pause.
- [ ] Add Collect Targets action and editable target table: per row enabled/new part/custom Value/NC controls; preserve existing rule dialog/full-match path. Excel import/export optional actions use same plan validation; blank typed target lists rejected rather than matching all.
- [ ] Verify Qt widgets with offscreen smoke interactions and scheduler failure/lock tests. Commit after tests pass.
@@ -0,0 +1,20 @@
# V1.1.0 UI, scheduler and delivery report
The existing task view now creates one task per selected project from a directory preview. The original mapping editor remains available beside the new target plan tab. The plan supports direct editing of selected targets, new Part Number, custom Value and NC; Excel import is a draft preview requiring Save. Unsaved drafts survive task switching and block group execution. NC is editable and defaults on, as confirmed by the user.
The task scheduler freezes task order and plan fingerprints, uses isolated per-task evidence, persists checkpoints and holds process/thread execution locks. Safe preflight failures are recorded; uncertainty stops before the next task. A paused UI queue retains the same task IDs including completed entries, allowing durable resume without replaying successful tasks. Target-mode and project-selection state are included in fingerprints.
Independent review identified raw-rule batch fallback, evidence routing differences, disappearing target pages, saved-unverified resume, mutation guards, purge foreign keys and subset rollback comparisons. These were fixed in the backend commits and checked against their focused tests. No live CAD write was performed.
## Verification and artifacts
- Default behavior suite: 36 passed in 5.43 seconds via `tools/Test-V1.1.ps1`.
- Selected existing safety suite: 38 passed in 5.12 seconds.
- Release build QA: combined 74 passed in 8.42 seconds.
- Focused backend VBS/recovery/Value checks: 45 passed in 7.57 seconds; final VBS contract check: 10 passed in 0.14 seconds.
- Python compileall and Git whitespace check passed.
- Offscreen UI screenshot inspected with a Windows Chinese font loaded for the offscreen renderer. It shows selected R1/R3, retained R2/R4/R5/R6 and editable NC. Default splitter proportions give the plan more space.
- PyInstaller 6.22.3 / Python 3.12.10 build succeeded. The frozen application started and shut down cleanly using an isolated temporary data root.
- After the final VBS component-count guard, the release runtime script was refreshed from source, its SHA-256 checked, and the frozen smoke repeated successfully. Final bridge SHA-256: `3BDEC7476762C28D6606825183DAC98505541EE2808B2F4C240577A7E304C72D`.
The historical suite remains explicitly available; it is not part of default development or release checks. Actual central-library replacement, saves/readback and external CAD validation still require a disposable project acceptance run. The included native interface report confirms the installed 7.9.5 typelib lacks a direct ReplacePart method.
@@ -0,0 +1,13 @@
# Single-project task UI and isolated execution
User approved this direction on 2026-10-14. This is continued V1.1.0 source development; do not build or package. Commit verified functional increments promptly.
- New-task dialog scans a root and selects projects; every resulting task owns one immutable project. Task details contain a project summary, refresh action, rules, targets and execution controls, with no project list/select-all/filter/skip/manual-run controls.
- Existing data is preserved. Multi-project historical tasks remain inspectable but are read-only in the new single-project UI; create project tasks through the dialog for further execution.
- Read task context once per refresh, then compute gates locally. UI changes and table search must not reread SQLite/CAD or regenerate log content unnecessarily. A per-task service facade must be reused without mixing evidence roots.
- Target search matches RefDes, UID, old/new part, sheet/schematic and Values case-insensitively; explicit Find filters cached table data, Enter runs Find, Next locates another match, Clear restores all. Filters never remove rows from saved plans. Bulk/select actions operate visible rows while preserving hidden rows.
- Execution commands are Execute current task, Execute batch in order, Pause at safe boundary, Retry failed items and Reconcile interruption. Scope, pending unsaved plans, lifecycle and active worker guards must be coherent. No backup-failure bypass control in the streamlined UI.
- Desktop isolation is an explicit research backend, not automatically enabled. It creates and owns a private desktop/process tree, validates CAD PID/project identity and reuses the existing UID/Library Wins/backup/save/readback safeguards. Never attach an unrelated CAD instance or fall back to the input desktop. No production CAD writes for validation.
- Normal workflows retain direct mapping/target edits, custom Value and default-on editable NC, plus optional spreadsheet import draft followed by explicit save.
Architecture: service produces a frozen ProjectTaskContext; task bindings remain store-compatible. UI is separated into project summary, plan/search table and execution state presentation. Native isolated worker is an independent backend boundary with evidence and cleanup. Safety checks remain at services and native code as well as UI gates.
@@ -0,0 +1,31 @@
# DxPartReplace V1.1.0 单工程任务与位号计划
已获用户授权开始迭代;本设计记录当前对话决定,不新增审批步骤。
## 产品流程
保留现有任务列表与规则编辑体验。新建入口支持选择目录、扫描 .prj、勾选工程、一次创建多个任务;每个新任务绑定且只绑定一个工程。同名工程使用相对路径区分。任务组只是目录创建与排序的组织单位。历史多工程任务保留,不能在迁移中重写执行证据。
用户在任务内填写旧料号、新料号,点击采集位号。使用已有只读图页发现链路读取真实器件的图页、UID、RefDes、Part Number、有效 Value。采集不调用替换、不保存。图页不同、层级不同或同名位号不能只靠 RefDes 合并。采集只读进程必须有界结束并关闭其拥有的工程。
用户可在原界面直接编辑/选择目标位号,不必导出。Excel 导入是可选入口;可导出同样的计划用于 Excel 编辑,但不会要求导出后才能执行。一行代表一个真实器件,保留工程、原理图、图页、UID、位号、旧料号、旧 Value,用户可编辑启用、新料号、自定义 Value、NC 同步。基线身份列不可重新解释;导入必须完整校验后原子提交,不得部分写入。
## 规则与执行
规则支持明确的全匹配范围与显式目标范围。旧规则迁移为全匹配;新目标规则使用已采集的 UID 与图页/位号作为预期状态。空目标集合不能退化为全匹配。同一旧料号允许不同位号子集和不同目标料号;重叠目标、全匹配与目标子集混用、链式/循环映射拒绝。一个目标可写独立自定义 Value;按图页/旧料号/新料号/Value/NC 策略编译分组再执行。
NC 保留现有可选语义并补齐任务视图编辑及 Excel 导入,默认开启;仅独立 /NC 段识别,禁止重复追加,写入和保存后回读均检验。保留模式的真实含义沿用现有原生库 Value 语义,不凭名为 preserve 推断会恢复旧文字。自定义模式明确写入用户给出的新值。
保持已有原生 Replace Part + Library Wins 写入路径与备份/连接/位置/保存回读/不确定保护。Python 计划携带 UID 清单,VBScript 在选取前校验 UID、RefDes、源料号、图页;目标缺失/状态变化必须失败而不是 no_match。未选器件的变化必须检测。目标绑定加入命令、快照、恢复与输入冻结校验。
跨任务执行采用已确认的任务 ID 顺序并固定计划。一个任务完成收尾/关闭后才进入下一个;普通失败在工程已安全关闭时可继续,未确定结果、恢复保护、关闭失败停止。各任务持有独立队列、备份、日志,不能用共享目录覆盖上一任务的未完成状态。规则、选择和任务操作在活动执行期间锁定,暂停在安全项边界。
## 结构与迁移
添加聚焦的 project_tasks、target_plan、inventory、spreadsheet_plan、task_queue 模块;复用 TaskStore/TaskCenterService 与 Qt 视图;不得复制旧多工程控制器或实现另一套 CAD 写入引擎。数据库使用事务迁移,新增字段有兼容默认值。版本从 1.1.0 起,EXE 标题、构建清单、依赖版本同步。
原生接口调研代理独立只读:检查当地官方类型库与帮助、已有探针以及公开资料,报告已证实能力/待验证能力;不对当前 CAD 会话或生产工程发起写操作。实验接口不自动成为默认后端。
## 验证
重建测试入口:默认只运行 V1.1.0 的行为级快速核心测试和必要的现有安全回归。旧测试保留为显式 legacy 回归入口,不删掉证据、不把过长模拟睡眠放入默认测试。无需 CAD、真实 COM 或网络即可测试导入原子性、目标隔离、顺序、重启/暂停、NC 和协议绑定。VBS 契约验证、Qt 交互和冻结 EXE 冒烟单独报告。现场原生替换与单元测试结论必须区分。
@@ -0,0 +1,11 @@
# 私有桌面正式执行闭环
用户在说明研究框架未接入后明确要求“那就把这一套执行好”。本轮在 `codex/execution-responsiveness` 上完成原执行器的私有桌面接入,不再停留于准备协议或回调探针。
生产入口的工程枚举和批量替换都必须在独立 Windows desktop 启动本工具持有的 CAD/worker。冻结任务、UID 选择、Library Wins、NC/Value 策略、连接保护、逐步保存重开回读和串行任务语义继续沿用。CAD 的 COM 对象必须验证窗口 PID、私有桌面与本次创建的进程身份;不能使用用户的其他 CAD 或静默回退普通桌面。保留模拟执行器注入用于自动化回归。
生命周期为:创建随机命名 desktop/job → 显式启动并绑定自有 CAD → 私有 desktop 中运行监督脚本及 helper → 保存并独立回读 → 正常退出 CAD → 等待进程退出 → 回收残余自有子进程 → 关闭 job、进程和 desktop 句柄。暂停仅在安全检查点收尾。异常、超时、身份冲突和释放失败保留证据并明确阻断;不得误报成功。主桌面不调用 SwitchDesktop、不注入键鼠,用户其他 CAD 进程和文件保持不动。
实施前首先用独立进程只读验证当前 EE7.9.5 的显式启动、私有桌面和 COM 绑定;真实替换只使用独立副本。验证至少包括成功、暂停、异常、进程退出、桌面消失以及主桌面前台窗口不被切换。不能用创建 desktop 的单元测试代替原生实际执行证明。
实现核实:普通显式启动 CAD 可提供私有 ROT,`-Embedding` 不可用。活动工程严格验证活动图页 HWND/PID;没有活动工程时 ActiveViewHandle 可能陈旧,启动和 Quit 改用显式自有 CAD 启动、私有 ROT/GUID 绑定。生产模块为 `isolated_cad.py`,原研究用 `isolated_worker.py` 不作为正式执行后端。实际结果及边界见 `docs/testing/2026-10-15-private-desktop-execution.md`。
@@ -0,0 +1,99 @@
# BOM 界面流程、长路径与完成任务重跑
本轮使用 1.1.2 开发源码;没有打包、打标签或发布。所有 CAD 写入都在两份独立副本上完成,原工程和原 CAD 进程 PID 18732 不参与执行。证据目录为 `build/bom-native-roundtrip-fixed-20261015`,`report.json` 保留历次失败与恢复记录。
## 验证方式
`tools/probe_bom_live_roundtrip.py` 通过真实 Qt 控件点击新建、扫描、选择工程、导出模板、导入 BOM、保存、执行和开始新一轮。操作系统文件选择的返回路径和确认框由探针提供;界面使用 offscreen 渲染,因此这属于自动模拟用户操作,并非人工逐次操作鼠标。实际读取、Replace Part、保存和回读均调用本机 DxDesigner;未用模拟 CAD 代替。
| 项目 | 实际输入与结果 |
| --- | --- |
| 工程 | Audio_D2128、Audio_T605A,一工程一任务 |
| 工程完整路径 | 分别 302、138 个字符 |
| 默认模板路径 | 284 个字符,实际导出和重新导入成功 |
| 模板 | 沿用 11 列,填写导出的真实单元格,不另造模板 |
| 替换范围 | 两工程各选择 RV05;同旧料号 RV11 不替换 |
| 第一轮 | `4100-CA0000-T7` → `4100-CA0000-T0` |
| 第二轮 | `4100-CA0000-T0` → `4100-CA0000-T7` |
探针在自身进程内禁用 8.3 路径回退,强制验证目录 junction 入口;不修改 Windows 长路径设置或持久环境变量。命令、快照、任务库始终使用原工程身份,运行短入口只用于旧式文件接口与 CAD 打开工程,结束后删除入口。
## 导入与再次编辑
1. 从弹窗扫描目录、创建两个任务,耗时 0.565 秒。
2. 点击 BOM 模板,实际导出带两个工程区分的 11 列默认文件到 284 字符路径。
3. 填写两个有效 RV05 替换项,另加不存在的 `R_DOES_NOT_EXIST`:3 行中 2 行通过、1 行失败,报告准确标出 Excel 第 4 行及无法唯一匹配的原因。失败导入既不写入库存,也不保存部分计划。
4. 删除错误项重新导入:2 行通过、0 失败,复用仍有效缓存,耗时 2.680 秒。预览后点击保存,两个工程共保存 4 个库存器件、2 个启用目标。
5. 第一轮完成核验后点击“开始新一轮”,同批两个已完成任务均恢复为草稿;旧计划、命令、快照、执行及恢复证据归档到各任务的 `rounds/<round_id>/`,新轮清除过期器件基线,保留绑定及料号默认规则。界面操作耗时 0.332 秒。
6. 按当前工程状态填写第二轮 BOM:每工程一条启用 RV05 和一条停用 RV11,共 4 行全部通过。重新采集并核对当前库存耗时 348.311 秒;该步骤不能沿用第一轮旧基线。
界面报告区持续显示行数、工程数、通过/失败/未检查数量及逐行原因;通过只代表已暂存预览,点击保存后才写入计划。有错误时整批不生成新的可保存预览。
## 现场发现并修复的问题
- 旧 WSH 的 FSO 对真实存在的长路径返回不存在。补齐实际工程路径的短入口;首次打开、保存后的重新打开和恢复都走同一入口。单独跑真实 FSO 回归验证了保存重开边界。
- 部分 COM 绑定把 `GetProjectFilePath` 暴露为字符串属性,退出代码却按方法调用。统一兼容属性/方法两种形式,私有会话能够正常结束。
- 原生修改后的失败曾被当作可直接重试:首轮长路径任务停在 `pin_promotion_started`,原生报告缺少异常信息。独立读取确认 RV05 已是新料号,不能依据“不保存关闭”推断工程已回滚。新增中断判定,阻止归档、直接重试、继续下一步或下一任务,必须先核验恢复;已核验的原生回滚仍可解除该类保护。
- 核验恢复原来不识别 `batch_failed` 的修改证据,且拒绝自动队列产生的 FAILED 工程。补齐选择中断步骤、严格绑定原快照和事务、允许恢复原生失败工程以及成功后的任务状态同步;手动失败流程仍拒绝混用。
- Windows 同时读取报告或命令文件时会短暂拒绝原子替换。通过真实 Win32 文件共享句柄复现后,补齐最长 1 秒的 PermissionError 重试。原始 helper 中止的根因仍无法单凭旧报告确定;此修复不被描述为已证明解决原始中止。
- 千步队列还复现了 `status.tsv` 短暂拒绝读取。新增最长 1 秒的只读打开重试;打开后仍核对文件身份、偏移、长度、完整行及前后时间戳,持续拒绝或真实内容变化仍停止并保留不确定保护。真实 Win32 独占句柄回归通过。
- 原生 helper 增加退出码、引脚提升阶段和 fault 日志。任务上下文的批规则同时纳入一次数据库只读快照,避免在已有快照后再读另一代任务数据。
恢复使用原来的长路径副本,没有重复制工程掩盖失败。旧构建已经把原始修改证据归档,因此仅在这个可抛弃测试任务中,将原证据逐字节校验后放回当前队列,把后续预检失败保留到历史,再通过界面的“核验并恢复”执行;操作记录位于该任务根目录 `manual-evidence-selection-for-regression.json`。
未勾选复制 Value 时,沿用既有语义:保留原生替换后的目标 Value,不强制恢复旧 Value。选中器件的空 Value 不能单独作为替换失败依据;未选中 RV11 则应保持料号、位号、UID 和 Value 不变。
后续补测已开启复制开关,真实替换后独立读取确认 `Part Label=0R`、`Value=0R`,详见 [Part Label 实测记录](2026-10-15-part-label-live.md)。
## 最终回读与回归
两个任务第二轮均返回 `saved_ok / session_verified`,包括真实保存、关闭、重开回读;之后另开全新后台 CAD 独立读取,得到:
| 工程 | 位号 / UID | 最终料号 | 最终 Value | 独立读取耗时 |
| --- | --- | --- | --- | ---: |
| Audio_T605A | RV05 / `$2I2014` | 4100-CA0000-T7 | 空,保留原生目标 Value 策略 | 106.165 秒(本工程合计) |
| Audio_T605A | RV11 / `$2I2022` | 4100-CA0000-T7 | 0R,与原值一致 | 同上 |
| Audio_D2128(302 字符路径) | RV05 / `$2I2014` | 4100-CA0000-T7 | 空,保留原生目标 Value 策略 | 108.927 秒(本工程合计) |
| Audio_D2128(302 字符路径) | RV11 / `$2I2022` | 4100-CA0000-T7 | 0R,与原值一致 | 同上 |
最后两次独立读取前曾连续三次遇到 `GetActiveObject` 启动阻塞,尚未打开工程或调用替换;各失败会话均通过拥有的 job/desktop 清理,没有触碰主桌面 CAD。调用栈证据已保留。单独启动探针也曾成功建立绑定,不能据此认定原阻塞根因已消除。启动等待从 75 秒调整为有界的 120 秒,保留取消和强制收尾,新增 90 秒成功及持续无响应的虚拟时钟回归。最终两次实际启动身份确认分别约 64.906、67.109 秒,读取和退出均 `clean=true`;**这次成功不能证明增加预算就是之前偶发阻塞的唯一修复原因**。
`report.json` 最终 `verified=true`、`source_projects_unchanged=true`、`aliases_removed=true`,别名清理无错误。最终观察到的 11 个后台 CAD PID 均确认退出、11 个私有 desktop 均确认不存在;主输入桌面始终为 Default,845 次采样均能读取主桌面文件,未观察到自有 CAD 抢前台或出现在输入桌面。第二轮全流程的上一份观察另外保存在 `desktop-observation-second-round.json`,19 个已观察自有 CAD/desktop 均释放。最后系统仅留下原始 `viewdraw.exe` PID 18732。
- 默认完整回归:**303 passed,168.18 秒**,在增加最后两条启动等待用例和状态读取重试前完成,后续改动由对应专项核验。此前一条多工程模拟器将“修改前失败”错误写成“已开始原生修改但缺少报告”,已校正模拟协议;生产保护未放宽。
- 启动/退出、COM 路径 getter 与新增有界等待专项:**18 passed,13.52 秒**。
- 恢复与快照专项:**33 passed**;随后新增状态文件占用后的 I/O 与快照专项:**14 passed**。
- 千步队列最终确实执行完 **20 工程 × 5 图页 × 10 规则 = 1000 步**,91 步保存、909 步未命中,作业编号无重复、顺序与状态断言全部通过,峰值分配约 **1.98 MiB**。但耗时 **52.434 秒**,约 **19.07 步/秒**,**未通过既有 `<30 秒` 的性能断言**。未放宽阈值或把该测试标为通过;这属于本轮尚未达到的性能目标。此前并行 CAD 时的另一轮为 32.313 秒,不作为当前性能结论。
现场探针结束后只重做独立读取,没有重新执行任何已完成的替换任务。再次运行这个探针的 `--resume` 会识别第二轮已完成记录,并自动只读核验。源码测试过程将 TEMP、TMP、LOCALAPPDATA 仅对测试进程指向 F 盘;原本在 C 盘的本仓库旧 pytest 产物经哈希校验后迁移到 F 盘 build 目录保留,没有清理用户工程或原始 BOM。
可查看的短路径证据:
- `build/bom-native-roundtrip-fixed-20261015/bom-default-template.xlsx`
- `build/bom-native-roundtrip-fixed-20261015/bom-with-invalid-row.xlsx`
- `build/bom-native-roundtrip-fixed-20261015/bom-first-round.xlsx`
- `build/bom-native-roundtrip-fixed-20261015/bom-second-round.xlsx`
- `build/bom-native-roundtrip-fixed-20261015/06-import-current-engineering-state.png`
- `build/bom-native-roundtrip-fixed-20261015/07-second-round-completed.png`
前述短路径 XLSX 是本轮实际文件的副本;长路径原件完整保留。初次截图因 offscreen 中文字体缺失不适合审阅,恢复探针显式加载微软雅黑后生成的第二轮截图可以正常显示中文。
## 第二轮执行计时
两任务顺序完成的墙钟时间为 465.509 秒。下列时间来自真实任务事件和私有会话元数据,不是模拟执行;完整阶段与历史失败项由 `execution-measurements.csv` 导出。
| 阶段 | Audio_D2128 长路径(秒) | Audio_T605A(秒) |
| --- | ---: | ---: |
| CAD 启动身份确认 | 58.578 | 48.562 |
| 打开工程累计(含重开) | 31.000 | 20.281 |
| 打开图页累计 | 19.344 | 16.141 |
| 原生替换 | 43.344 | 36.125 |
| 属性恢复预检 | 14.437 | 9.875 |
| 属性字段恢复 | 8.828 | 5.766 |
| 保存关闭阶段累计 | 8.515 | 4.969 |
| 单步总耗时 | 252.992 | 192.477 |
| 整个任务耗时 | 262.275 | 202.886 |
| 任务速率(任务/分钟) | 0.229 | 0.296 |
| 私有会话收尾 | 3.281 | 2.797 |
控制器总耗时、worker 子阶段和启动/收尾属于不同计时层,不能跨层相加。阶段数据还受本机 CAD 启动、COM 调用及现场负载影响;本次用于证明真实步骤与定位耗时,不据此宣称性能提升。BOM 的首次读取和新轮读取会重新验证工程稳定性,缓存有效的纠错导入则无需重复启动 CAD。
@@ -0,0 +1,38 @@
# 任务导航与 CBB BOM 格式转换(1.1.2 开发中,未发布)
## 任务导航
左侧支持按任务名称、目录、备注搜索,以及执行顺序、名称正反序、创建时间正反序、最近更新排序。名称按自然顺序排列,例如 Board2 在 Board10 前面。排序选择在重启后保留。
搜索、排序在缓存的任务列表上进行,不重复查询数据库,也不改写批次执行位置。隐藏当前任务时保留右侧上下文,清空搜索后恢复选中。顺序执行仍处理原批次的全部任务。清空搜索、选择执行顺序后,才可用上移/下移调整执行位置。
## 本次转换
输入:`F:\ABS-file\ABS-file\CBB_BOM_替换清单2026.10.12(1).xlsx`。
以“结果”表为主,共 1803 行、104 种工程标签。转换使用现有 `write_bom_template`,没有修改模板的 11 列、工作表结构或导入约定,也没有修改原文件、任务数据库或 CAD 工程。
复现命令:
```powershell
python tools/convert_cbb_bom.py 'F:/ABS-file/ABS-file/CBB_BOM_替换清单2026.10.12(1).xlsx' --project-root 'F:/Sync Tool Skyworth/Work Maps/Skyworth_CBB_Lib/CBB' --output-dir 'dist/CBB-BOM-converted'
```
M 列作为方案候选,V 列只保留作对照,不在 M 缺失时自动补入 V。V 与“缓存”表 O 列的 1803 行一致;M/V 有 90 行同时为明确料号但不同,其中 88 行是 `4300-CB1040-A100` 与 `4300-CC1040-7100` 的差异,另外 2 行以 `431R` 开头。列用途是基于数据关系作出的判断,不代表电气可替换性已经确认。
输出位于 `dist/CBB-BOM-converted`,不随源码提交原始业务数据:
| 文件 | 内容与限制 |
| --- | --- |
| CBB_转换模板_全量待核对.xlsx | 441 行候选、1019 个位号;未定位的工程路径留空,需补齐后才能批量导入 |
| CBB_转换模板_已匹配工程.xlsx | 当前目录能定位的候选:10 个工程、63 行、170 个位号;50 行启用,13 行存在差异,默认停用 |
| CBB_逐行转换核对.csv | 保留所有 1803 行原始数据、原行号、路径匹配结果和转换说明;不是导入文件 |
| conversion-report.json | 转换计数与文件位置 |
当前指定的 CBB 目录可定位 14 种工程标签,其中 10 种有可转换行。没有新料号、包含“删除该CBB”“不可更换”等说明的行保留在核对清单,不转换为替换操作。M 中仅含一个料号的说明文字可提取为停用候选;多料号、公式和系列后缀不自动解释。M/V 差异、手工处理、未绑定路径等候选默认停用。完成标记不用于删除或筛选行,原 VALUE 不自动写入 custom_value,NC 同步使用原模板默认开启。原行号、M/V、完成标记、VALUE 和相关备注保存在新料号单元格批注中。
## 验证与尚待完善
27 项针对任务搜索/排序、选中状态、设置持久化、异步响应、原 BOM 导入和此次转换的检查通过(13.16 秒)。两份输出由工具实际的 `read_bom_records` 重新解析,并检查列名、单工作表、无公式、自动换行以及已匹配路径存在。没有启动 CAD,也没有验证这些业务料号在当前工程/中央库中的实际替换结果;导入仍需同批工程绑定与位号采集匹配。
建议后续补充:导入时选择工作表与列映射;工程名称到任务路径的匹配预览;一次列出全部未命中、跨页重号和冲突行;在界面展示转换来源和停用原因。它们属于后续功能,本次没有改动 BOM 模板或导入界面。
@@ -0,0 +1,52 @@
# CBB BOM 真实工程导入验证
2026-10-15,1.1.2 开发版本,未打包发布。原始 BOM 和原工程未改动,没有执行 Replace Part。
## 结论
原转换文件的 63 条候选不能整表通过当前工程校验:15 条在 7 个工程中完整匹配,另外 48 条未完整匹配。不能将格式解析成功等同于真实位号匹配成功。
使用原生采集到的真实 UID、位号、图页、旧料号、Value,在隔离任务库里回放导入这 15 条规则,已走通 **界面导入 → 跨任务预览 → 批量保存 → 关闭数据库 → 重新打开核对**。7 个工程共保存 39 个采集位号,其中 25 个启用,其余保留或停用;11 条启用规则展开为 25 个实际替换目标。预览没有改写已有库存或保存计划。
这次测试分成真实 CAD 采集和界面回放两层。界面回放复用实际采集的库存,没有伪造 UID 或位号,也没有再次启动 CAD。它证明导入、分配和持久化正确,不代表所有工程在最终版本上重新完成了完整原生采集,更不代表电气替换已经验证。
## 实际输入与证据
- 原始文件:`F:\ABS-file\ABS-file\CBB_BOM_替换清单2026.10.12(1).xlsx`。
- 转换文件:`dist/CBB-BOM-converted/CBB_转换模板_已匹配工程.xlsx`。
- 原始工程复制到 `build/cbb-bom-import-live-20261015/projects`。副本仅将 CentralLibrary 改到本机已存在的库路径;测试表仅将工程路径改到副本。
- 原始表的多个工作表、全量转换表缺少工程路径,均在启动 CAD 前被明确拒绝,任务计划没有部分写入。
- `build/cbb-bom-import-verified-20261015/report.json`:10 个工程的原生诊断、导入拒绝和局部导入日志。
- `build/cbb-native-verified-input/evidence.json`:每个工程最近两次成功原生采集的证据目录。只有这两次的图页和器件集合一致时才接受快照;完整旧料号请求范围也保留在证据中。
- `build/cbb-bom-ui-verified-7-projects/report.json`:最终 7 工程界面回放和保存回读结果。
- `build/cbb-cache-fixed-native/report.json`:最终代码在 `1PEF7071_PHY` 上再次进行的新鲜原生采集,5 个真实器件通过并成功复用缓存。
## 修复的问题
1. **原生只读打开也更新数据库**。ICDB 会更新 `database/icdb.dat`,自动备份会更新日志及备份文件。旧校验会反复打开工程并拒绝采集。现在排除明确的备份审计输出;数据库仍计算完整哈希。仅数据库在读取期间变化时,需要两次原生采集结果一致,而且其他设计文件跨两次读取保持稳定。首次工程配置规范化后允许一次额外读取完成这两次核验。库存不同、设计文件持续变化、不可验证等情况仍拒绝使用;数据库后续变化也仍使缓存失效。
2. **失败提示无法判断是哪一个工程**。采集及匹配异常现在带工程名称和完整路径,保留原错误编号。VBS 也记录枚举、打开图页、查询器件、读取器件、关闭图页与关闭工程的阶段。
诊断过程中 `1GPHY_RTL8211F_A` 曾返回 COM 服务器异常;其他成功采集记录提供了该工程两份一致的真实库存。该异常没有被认定为已修复。另有工程的旧料号库存为空,原因需结合原表与当前工程版本核对,不能直接假定为已经替换。
## 耗时与资源
| 检查 | 结果 / 耗时 |
| --- | --- |
| 原表格式拒绝 | 0.136 秒,未写计划 |
| 未绑定路径拒绝 | 0.155 秒,未写计划 |
| 最终 7 工程界面预览 | 0.282 秒 |
| 最终 7 工程批量保存 | 0.364 秒 |
| 最终代码新鲜原生采集 | 76.998 秒,5 个器件 |
| 同工程缓存复用 | 0.266 秒,库存一致 |
| 原生诊断期间界面计时器最大间隔 | 0.234 秒 |
| 最终界面回放期间计时器最大间隔 | 0.112 秒 |
原生采集仍是主要耗时点:诊断阶段单工程耗时约 62–134 秒,包含 CAD 启动、多次读取和关闭。首次诊断是在完整兼容修复之前运行,失败耗时不能当成最终版本的成功吞吐量。后续应优先研究连续采集时复用受控 CAD 会话,并补充逐工程进度与安全取消。
私有桌面观察确认诊断轮的 19 个会话均已退出,桌面均已释放;最终新鲜采集也独立观察清理结果。输入桌面始终为 Default,受控 CAD 未成为前台或出现在主桌面;原 CAD 进程 18732 保留。原工程文件哈希保持不变。
## 交付与回归
`dist/CBB-BOM-converted/真实工程验证` 中包含按原模板 11 列导出的匹配行、全部 63 条候选逐行核对 CSV、统计和保存后的界面截图。匹配行文件恢复为原工程路径,没有覆盖原转换文件,也没有改变原模板列。
75 项针对缓存、BOM、任务导航、异步界面、库存和目标执行的回归检查通过(19.37 秒)。没有构建、更新发布包或创建版本标签。
@@ -0,0 +1,52 @@
# 2026-10-15 执行响应与模块优化验证
在原 V1.1.0 工具上迭代,开发分支 `codex/execution-responsiveness`,基线 `d79250b`。本轮不打包、不推送,也不修改真实原理图工程。
## 最终行为
- 任务列表、任务详情、日志和执行反馈通过独立后台查询读取;同一通道最多一个活动查询和一个最新待处理请求,旧结果不能覆盖当前选择。
- CAD 执行仍串行;执行过程中可以切换任务只读查看、选择和查找位号,修改和重复启动继续禁用,暂停作用于实际执行队列。
- 完成/失败提示明确任务归属,查看 B 时不会把 A 的结果当成 B 的完成记录。完成后强制读取最终日志,避免被执行前尚未返回的旧快照覆盖。
- 日志初次加载最近 200 条事件,历史向前分页;实时增量读取并追加,保留 UTF-8 未完成行的读取位置。实时累计到 400 条事件后,下一次刷新重取最近一页以限制显示规模。所有保留历史仍可分页访问;文件轮转、截断或重建时更新游标。旧的完整日志 API 保持兼容。
- 目录扫描显示已扫描目录和发现工程数量,可取消和关闭;取消不返回部分候选。任务创建只复核已选工程、路径边界、排除目录、重解析点和祖先工程的扫描规则,不重复递归无关目录。
- 只读采集和执行准备可复用图页发现结果,缓存仅限当前任务执行器。工程树内容摘要或元数据变化、扩大料号范围、缺少组件信息会重新发现;执行修改前主动失效。
- 新的 `BatchBackupCoordinator` 管理备份状态、失败策略和单工程预备份,`execute_batch` 从约 304 行降至 170 行。保留原生执行、保存关闭重开回读、失败/中断保护及既有事务边界。
- 查询回调在窗口关闭时失效;退出应用时等待后台读取结束后再释放共享 SQLite 连接。
## 响应计时
在本机一次运行的 **模拟数据 / Qt offscreen** 测量,不是 CAD 性能数据。生成 5000 条事件、40000 条位号修改明细,日志 2,122,783 字节;完整显示采用此前的 QTextEdit,全量读取并格式化。新显示采用 QPlainTextEdit 和分页;单次测量受磁盘缓存等因素影响,不作为通用提速比例。
| 场景 | 本次耗时 |
| --- | ---: |
| 原方式:全量读取、格式化、显示 | 851.482 ms |
| 最近 200 条:读取、格式化、显示 | 42.178 ms |
| 未变化日志的增量轮询(后台) | 27.748 ms |
| 新界面异步显示最近日志的端到端时间 | 28.263 ms |
| 注入 400 ms 慢读取后,open_task 返回 | 1.362 ms |
| 注入慢读取后,任务实际加载完成 | 444.039 ms |
| 慢读取期间 20 ms 心跳计时器触发次数 | 22 |
| 心跳最大间隔 | 21.601 ms |
分页遍历独立核对恢复了全部 5000 条事件。原始测量:`build/ui-response/report.json`。
复现:`python -X utf8 tools/measure_responsiveness.py --output build/ui-response/report.json`。脚本只创建独立临时数据,不连接 CAD。
缓存采用内容摘要有额外读取成本。独立临时目录 65 个文件、总计 32 MiB 的五次指纹测量约 149~203 ms,中位数约 169 ms;缓存命中需要读取包含文件一次,发现缓存未命中会在发现前后各读取一次。大工程和慢盘需以现场数据判断收益。本轮未重新测量 CAD 实际替换耗时,不能把界面数据或缓存命中次数等同于原生替换提速。
## 回归与审查
- `build/responsiveness-final.xml`:219 passed、1 deselected,103.09 秒。覆盖 V1.1、队列、备份、暂停/恢复、执行安全、监控、应用启动退出和日志;单独排除 1000 步压力用例。
- `build/responsiveness-stress.xml`:压力用例单独运行通过,测试总耗时 24.32 秒;执行段 22.376 秒,1000 步、44.69 步/秒,内存峰值 1,995,169 字节(约 1.90 MiB)。91 步保存成功、909 步正常未命中,无重复调度。使用模拟 CAD、备份桩和 tracemalloc,不代表 CAD 速度。
- 两部分合计 **220 个不同用例通过**,未放宽原 `<30 秒`、`<128 MiB` 门槛。
- 开发期间在并行运行其他任务时,压力用例曾测得 36.32 秒并失败;保留这一事实,最终单独运行通过,不把负载影响说成稳定提速。
- 独立审查发现:慢初始日志反复刷新可能饿死;执行与查看任务不同导致提示归属错误;仅元数据缓存无法识别 Windows 保留时间戳的等长修改。这些问题均补充行为回归并修复。内容摘要修复及最终反馈/退出路径复审通过,无剩余必须修复项。
~~~powershell
python -m pytest tests/v1_1 tests/trial_task_center/test_batch.py tests/trial_task_center/test_execution_safety.py tests/trial_task_center/test_recovery.py tests/trial_task_center/test_worker_monitor.py tests/trial_task_center/test_application.py tests/trial_task_center/test_logging_setup.py -q -k 'not thousand_item_multisheet_mixed_queue' --junitxml=build/responsiveness-final.xml
python -m pytest tests/trial_task_center/test_batch.py::test_thousand_item_multisheet_mixed_queue_has_bounded_runtime_and_memory -q --junitxml=build/responsiveness-stress.xml
~~~
## 后续边界
同工程跨步骤持续持有 CAD 会话尚未实施:当前每步以保存、关闭、重开回读后的持久结果作为恢复边界。合并会话需要升级该协议,并用真实多图页、多规则工程验证中断和保存失败行为。本轮通过安全复用发现结果先减少重复枚举,保留既有保存核验保证。历史 controller、store 和 VBS 的完整拆分也未在本轮完成。
@@ -0,0 +1,112 @@
# 2026-10-15 多工程执行与速率回归
本次在 DxDesigner 7.9.5 上使用 3 个不同真实工程的独立副本,实际执行了原生 Replace Part、保存关闭和重开回读;另以模拟 CAD 执行器检验多工程、多图页、多规则队列及压力场景。两类速率分开报告。
代码提交:`0225787`。真实 CAD 数据在短路径修复和计时接入后测得;此后继续优化了 Python 队列开销,并用自动回归验证。没有再次替换这 3 个已验证副本,不能把软件压力测试的改善比例当作 CAD 实际速度改善比例。
真实工程来自 `Skyworth_CBB_Lib/CBB`,测试副本仅将失效的 `S:\mentor_lib.lmc` 改为本机现有中央库的绝对路径。未用历史 CAF 或人工构造 UID 充当真实替换证据。下述为本机一次实测,部分测量与自动回归同时进行,不是重复采样的硬件基准。
## 真实多工程队列
| 顺序 | 工程 | 实际修改位号 | 旧料号 | 新料号 | 回读结果 |
| --- | --- | --- | --- | --- | --- |
| 1 | 1GPHY_8211 | RL02 | 4100-CA3300-T7 | 4100-CA3300-2200 | saved_ok / batch_closed |
| 2 | Audio_D2128 | RV05 | 4100-CA0000-T7 | 4100-CA0000-T0 | saved_ok / batch_closed |
| 3 | Audio_T605A | RV05 | 4100-CA0000-T7 | 4100-CA0000-T0 | saved_ok / batch_closed |
3 个任务顺序结束,无暂停、失败或未确认状态。队列耗时 **187.174 秒**,即 **0.962 个工程/分钟**;包含前置库存采集与准备的运行总耗时 221.145 秒。每个工程本次只有一个启用的图页/规则步骤,不能据此推断所有工程规模的平均速度。
### 每一步耗时(秒)
| 工程 | 只读采集 | 图页枚举及队列准备 | 备份 | 替换步骤(含保存回读) | 进度同步 | 本次任务执行合计 |
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
| 1GPHY_8211 | 10.191 | 12.851 | 1.211 | 62.814 | 0.012 | 77.059 |
| Audio_D2128 | 12.586 | 8.851 | 0.981 | 42.971 | 0.011 | 52.910 |
| Audio_T605A | 10.222 | 11.012 | 0.958 | 44.812 | 0.012 | 56.894 |
任务合计包含枚举、备份、替换、进度和日志开销,不包含先前的只读采集;它与子步骤不能重复相加。整批队列另外包含任务切换和检查点开销。
### 保存后独立回读
| 工程 | 已验证的计划位号 | 实际改变 | 其余保留原料号 | 独立回读耗时(秒) |
| --- | ---: | ---: | ---: | ---: |
| 1GPHY_8211 | 13 | 1 | 12 | 10.530 |
| Audio_D2128 | 2 | 1 | 1 | 9.993 |
| Audio_T605A | 2 | 1 | 1 | 11.254 |
所有比对均通过:按工程、图页、UID、位号和料号逐个核对,3 个目标变更,14 个未勾选匹配位号保留。两个 Audio 工程都含 RV05,结果分别归属于各自任务。上述独立回读在队列结束后另行执行,不包含在队列耗时中。
### 执行器内部阶段(秒)
进度监控按阶段切换计时,同名阶段多次出现时累计;这是互斥时间段,不是每个同名函数的完整调用时长。例如保存回读内再次打开工程的时间会累计到 open_project。非常短的阶段可显示为 0.000。
| 阶段 | 1GPHY_8211 | Audio_D2128 | Audio_T605A |
| --- | ---: | ---: | ---: |
| starting | 0.297 | 0.390 | 0.235 |
| session_startup | 1.109 | 0.985 | 0.843 |
| check_project | 0.032 | 0.015 | 0.047 |
| open_project | 15.374 | 12.719 | 13.563 |
| open_sheet | 2.438 | 2.876 | 2.359 |
| session_ready | 0.016 | 0.046 | 0.047 |
| query_components | 0.297 | 0.454 | 0.469 |
| index_components | 3.249 | 1.406 | 1.562 |
| find_components | 0.937 | 0.406 | 0.766 |
| index_pins | 2.906 | 1.859 | 1.704 |
| snapshot_attributes | 0.189 | 0.219 | 0.407 |
| capture | 2.515 | 1.500 | 1.390 |
| before_native | 0.079 | 0.062 | 0.063 |
| native_replace | 24.000 | 12.672 | 13.547 |
| restore_preflight | 2.624 | 1.406 | 1.608 |
| before_restore_transaction | 0.219 | 0.219 | 0.235 |
| restore_attribute_fields | 0.625 | 0.625 | 0.640 |
| restore_attributes | 0.031 | 0.000 | 0.000 |
| verify_restoration | 0.063 | 0.094 | 0.172 |
| verify_attribute_fields | 0.140 | 0.141 | 0.156 |
| finished | 1.750 | 1.077 | 1.218 |
| save_and_close | 3.891 | 3.751 | 3.720 |
| verify_saved_project | 0.000 | 0.015 | 0.031 |
## 软件队列回归与压力测试
模拟 CAD 场景仍使用真实 SQLite、XLSX、计划编译、命令/状态文件、备份及任务日志,模拟执行器只按收到的真实 UID 选择器修改内存器件模型并返回协议结果。其速率不能代表 DxDesigner 替换速度。
| 场景 | 工程数 | 实际执行步骤 | 修改模型器件数 | 保留的未选器件数 | 总流程耗时(秒) |
| --- | ---: | ---: | ---: | ---: | ---: |
| failure_continue (case-failure_continue) | 3 | 12 | 22 | 12 | 4.017 |
| pause_resume (case-pause_resume) | 3 | 12 | 24 | 12 | 3.275 |
| success (case-success) | 3 | 12 | 24 | 12 | 4.556 |
| uncertain_stop (case-uncertain_stop) | 3 | 1 | 0 | 12 | 1.730 |
| success (scale-10-final) | 10 | 120 | 240 | 120 | 38.722 |
3 工程场景覆盖:串行顺序、失败继续下一工程、未确认结果阻断后续工程、暂停续跑不重复、同名位号按工程/图页隔离、BOM 一行多个位号以及日志完整归属。10 工程场景为每工程 3 张图页、每图页 4 条规则,共 120 步;240 个选中模型器件改变、120 个未选模型器件保留。
1000 步兼容性压力场景使用历史单任务多工程队列(20 工程 × 5 图页 × 10 规则),开启 tracemalloc,真实备份由桩替代。它单独检查队列开销与内存,不是新版多任务调度或 CAD 吞吐量。最终全部 1000 步完成:91 步模拟保存成功、909 步未命中正常跳过,无重复调度;耗时 **27.764 秒**,速率 **36.02 步/秒**,tracemalloc 峰值 **1.865 MiB**。原有 `<30 秒` 和 `<128 MiB` 检查均通过,未放宽阈值。
## 本次发现和修复
1. 监控握手路径长 264 字符时,Python 可见文件而 VBS FileSystemObject.FileExists 返回 False,造成约 20 秒后报 supervisor did not authorize startup。改用系统短路径后,真实项目枚举和替换均可执行;没有可用短路径的系统会在 CAD 启动前给出短目录提示。原有证据目录保持不变。
2. 每步重复解析整份命令与状态文件,40 步检测到 41 次命令读取,1000 步耗时 228.154 秒。改为每会话缓存命令、按追加量读取状态;在每次启动 worker 前检查状态文件身份、大小及修改时间,外部插入状态会在下一次写入前阻断。
3. 缓存工程备份根目录和项目 ID,避免在后续备份查找中重复解析文件路径;没有后续备份候选后不再反复扫描。每步计时合并到原执行结果事件中,避免重复刷写日志。
## 原始证据和复现
本机证据目录:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\build\multitask-regression-20261015`。
- `native-live-results.json`:3 个真实任务及队列状态。
- `native-timings.csv` / `native-timings.json`:18 条真实阶段计时。
- `native-worker-stages.csv`:69 条真实执行器阶段计时。
- `native-post-verification.json`:17 个计划位号的独立回读比较。
- `native-data-live/tasks/<task-id>/quick-run/`:每个真实任务的命令、状态、备份、快照及原生报告。
- `scale-10-final/timings.csv`:10 工程、120 步及流程/任务统计;layer 标明流程计时和执行计时,二者不能重复相加。
- `case-*/report.json`:故障、阻断、暂停续跑及成功场景的断言与每次调度。
- `stress-timings.csv` / `stress-final.json`:1000 步逐项统计和内存峰值。
- `regression-before-queue-cache.xml`:首次回归中的两个性能失败,保留用于回溯。
最终验证覆盖 **188 个不同用例,全部通过**:`regression.xml` 记录 187 项通过(单独排除已执行的压力项),`performance-final.xml` 记录压力项及 7 项相关检查通过;两个文件有 7 项重叠,去重为 188 项。包含串行调度、BOM、结果日志、长路径真实 VBS、监控超时清理、状态外部改动保护、失败/暂停/恢复及连接保护。
~~~powershell
python -m pytest tests/v1_1 tests/trial_task_center/test_worker_monitor.py tests/trial_task_center/test_batch.py tests/trial_task_center/test_execution_safety.py tests/trial_task_center/test_recovery.py tests/part_replace/test_verification.py -q -k 'not thousand_item_multisheet_mixed_queue'
python -m pytest tests/trial_task_center/test_batch.py::test_thousand_item_multisheet_mixed_queue_has_bounded_runtime_and_memory tests/v1_1/test_execution_metrics.py tests/v1_1/test_replacement_logs.py -q
~~~
源码计时记录保存在任务事件中;真实数据 CSV 已逐项展开,模拟 120 步的 CSV 保留了每个 job_id、工程、图页、料号、结果、耗时及速率。测试期间未重新打包。真实中央库替换依赖现场库;本次未进行 Packager、ERC 或网表验收。
@@ -0,0 +1,64 @@
# 1.1.2 本机冻结候选验收与窗口教程
结论:**本轮列出的本机成品验收通过,可用于限定环境的小范围试用交付**。不是所有 CAD、中央库和机器环境的稳定性认证;没有创建远端 Release 或版本标签。
## 候选身份
- 构建提交:`a16914bc7221dbc62c467b7a89e06ab0c40c1fbc`;产品代码与此前通过源码检查的 `ce574dd` 一致,期间仅增加发布评估和说明文档。
- 标准构建脚本源码检查:**369 passed,1 warning,63.39 秒**;PyInstaller 构建与冻结 EXE 启动/退出检查通过。
- 候选从 `dist/DxPartReplace` 另复制到干净 staging,排除 `data`,再压缩、解压。实际操作的是 `build/packaged-acceptance-20261015/extracted/DxPartReplace/DxPartReplace.exe`。运行进程路径、EXE 哈希和副本工程身份另行核对。
- EXE SHA256:`73d6deb81d52ce34ce9c6d2958275a9b7376f316ae1872552882f0d65070ce75`。
- VBS SHA256:`9997d8a41ad3820e7fd905c8024fc10c765c0e6218eb7f3c091301e3c73db9dc`,与源码一致。
- ZIP SHA256:`bfbc089c4362a9a9c43320b81ee9d4f7af0750bee6da25d16fc58733130319c2`,52,589,346 字节。
候选、完整工程副本、原始记录均在 `build/packaged-acceptance-20261015`。候选 ZIP 为本地验收包,不改变当前已发布版本。
## 实际操作及断言
使用 Windows UI Automation 定位真实控件,向目标窗口发送鼠标消息,操作原生文件选择与确认弹窗。没有导入产品内部 UI 类驱动主流程,没有模拟 CAD worker,也没有向数据库或日志注入成功状态。数据库检查使用只读连接。
| 验收项 | 结果 |
| --- | --- |
| 创建任务 | 实际创建弹窗读取 Audio_D2128、Audio_T605A 的独立副本;一工程一任务 |
| 长路径 | 两工程路径分别 297、131 字符;长路径实际采集、替换、保存重开与独立读取均完成;本轮使用本机可用的 8.3 短入口,未重复强制 junction 路线 |
| 默认 BOM | 点击导出原模板,确认 11 列、两个工程;只填写原表单元格,不改模板结构 |
| 错误导入 | 两条有效 RV05 + 不存在的 R_DOES_NOT_EXIST:通过 2、失败 1、未检查 0,明确 Excel 第 4 行;没有部分保存 |
| 修正导入 | 通过 2、失败 0、未检查 0;预览不写计划,点击保存后形成 4 个库存位号,只有两个 RV05 启用 |
| 任务搜索 | T605A 过滤为 1 个,清空后恢复 2 个;执行成员未变 |
| Value 策略 | 逐任务通过界面启用 Part Label → Value,并核对数据库中的选项持久化 |
| 顺序执行 | 实际确认两个工程范围,分别执行原生 Replace Part、保存、关闭和重开核验;两工程各一条真实 saved_ok 事件,均含 RV05 的旧新料号 |
| 结果/日志 | 实际结果单元格包含 RV05、新料号和“已保存并核验”;切换完整日志、关闭再打开,结果仍正确 |
| 独立读取 | 使用全新私有 CAD 会话读取实际保存工程,结果如下;启动/退出 helper 使用同一冻结 EXE,属性读取器为独立源码诊断脚本 |
| 新轮次 | 独立核验后实际点击开始新一轮,两任务恢复 draft,旧目标计划清空;两份 plan.json 及执行证据归档保留;本轮不重复执行已完成的原生替换 |
| 旧版数据兼容 | 实际 1.1.1 发布 EXE 创建两个元数据测试任务;复制其数据库交给候选打开,正常退出,两个任务 ID/名称均保留,旧数据库未变;不是对任意历史数据的全量迁移认证 |
| 工程与资源 | 两个原工程的全部文件 SHA256 未变;10 个观察到的自有 CAD 进程退出、10 个私有桌面释放,无观察错误,未抢主桌面;最后仅保留用户原 CAD PID 18732 |
| 应用退出 | 验收和录制后候选主窗口正常关闭,没有遗留候选 GUI 或自有 CAD |
独立实际结果:
| 工程 | 位号 | UID | 实际保存料号 | Part Label | Value |
| --- | --- | --- | --- | --- | --- |
| Audio_D2128 | RV05 | $2I2014 | 4100-CA0000-T0 | 0R | 0R |
| Audio_D2128 | RV11(保留) | $2I2022 | 4100-CA0000-T7 | 0R | 0R |
| Audio_T605A | RV05 | $2I2014 | 4100-CA0000-T0 | 0R | 0R |
| Audio_T605A | RV11(保留) | $2I2022 | 4100-CA0000-T7 | 0R | 0R |
## 耗时及记录
- 含错误项的首次 BOM 导入和实际库存核验:285.406 秒;修正后有效缓存下重新导入:5.735 秒。
- 点击确认执行到两工程完成并恢复界面:258.984 秒,约 4 分 19 秒;这是两个工程合计,包含原生处理及保存回读,不代表每个位号都需要同等耗时。
- 独立读取:37.922、46.172 秒,分别包含全新会话启动、打开读取和退出。
- 阶段计时:`execution-measurements.csv`;实际状态、导入标题、保存事件及调试尝试保存在 `ui-acceptance.json`,失败的驱动适配尝试没有删除。驱动修正没有修改产品代码或绕过原生核验。
- 其他记录:`candidate-manifest.json`、`independent-report.json`、`source-integrity.json`、`v111-upgrade-report.json`、`desktop-observation-{bom,execute,independent}.json`、`tutorial-report.json`。
## 窗口 GIF
[打开操作教程](../user/media/v1.1.2-window-bom-tutorial.gif):20 个步骤,47.5 秒,约 2.65 MB,1280×980。
GIF 由本轮实际窗口操作的分步截图组成,使用 PrintWindow 仅读取指定候选进程的主窗口及其弹窗,不读取桌面图像,不包含 Excel 或 CAD 窗口。模板填项在窗口录制之外由脚本完成。字幕说明实际等待被压缩;数分钟的 CAD 等待没有按实时长度保留。抽查了导出 GIF 中的错误报告、成功回读和新轮次帧,中文及内容可读。
可复用工具:`packaged_window_driver.py`、`accept_packaged_ui.py`、`probe_packaged_upgrade.py`、`verify_packaged_saved_state.py`、`finalize_window_tutorial.py`。工具有副本路径和成品身份守卫,执行错误时不自动重复替换。UIA 与窗口绘制接口仍属于同步调用,本次工具用于有人监督的本机验收,不作为具有硬超时保证的无人值守门禁。
## 保留的限制
既有 COM 偶发启动阻塞的根因仍未解决;本轮所有会话最终成功并释放,不能据此证明问题消失。超长任务名称在执行反馈中占用较多空间、任务列表状态在批次结束前可能滞后,是后续体验改善项,不影响本轮真实回读结论。未新增其他库版本、其他机器或 Packager/ERC 验收。之前千步性能单次 29.517 秒达标的范围仍仅为模拟 worker,不与本轮实际 CAD 时间混用。
@@ -0,0 +1,42 @@
# Part Label 写入 Value 的实际替换验证
本次补测开启“替换后将 Part Label 写入 Value”的路径。功能代码没有修改;新增可重复运行的探针 `tools/probe_part_label_live.py`。证据位于 `build/part-label-live-20261015`,没有打包或发布。
使用原始 Audio_T605A 的新副本,导出默认 BOM 模板后填写 RV05 替换项,通过界面导入、保存、勾选复制开关,再点击执行当前任务。Qt 使用真实鼠标事件,文件选择返回值由探针注入,Excel 单元格用 openpyxl 编辑;CAD 替换、保存和读取均为本机真实 DxDesigner 调用。第一次探针鼠标坐标落在复选框留白,停在修改前;修正探针点击坐标后复用已保存计划继续,实际替换只执行一次。
## 结果
| 检查项 | 实际结果 |
| --- | --- |
| BOM 导入 | 1 行通过、0 行失败;库存 RV05、RV11 共 2 项,只启用 RV05 |
| 界面开关 | 已勾选,并持久化到任务 |
| 实际执行策略 | 命令的 `value_mode`、`base_value_mode` 均为 `part_label`;自定义 Value 关闭 |
| RV05 料号 | `4100-CA0000-T7` → `4100-CA0000-T0` |
| RV05 独立读取 | UID `$2I2014`,Part Label **0R**,Value **0R** |
| RV11 未选中 | UID `$2I2022`、料号 `4100-CA0000-T7`、Value **0R** 均保持原样 |
| 保存核验 | 原生替换、属性回读、保存、关闭、重开核验通过,任务完成 |
| 额外独立核验 | 另开全新私有 CAD 会话,直接读新料号、Part Label 和 Value;成功后不保存关闭 |
| 原工程 | 全目录文件哈希未变,且与上一轮对照测试的原工程哈希一致 |
| 主桌面及释放 | 1231 次采样均能读取主桌面文件,输入桌面保持 Default,自有 CAD 未抢前台;观察到的 7 个自有 CAD PID、7 个私有 desktop 均释放 |
本次没有出现 CAD 启动超时,独立读取会话启动约 27.484 秒、收尾约 1.531 秒。最终系统仍只有用户原来的 CAD PID 18732,临时路径别名清理无错误。
与上一轮相同料号替换的对照:
| 复制开关 | 替换后的料号 | 独立取得的 Value |
| --- | --- | --- |
| 关闭(上轮) | 4100-CA0000-T0 | 空,保留原生目标 Value |
| 开启(本轮) | 4100-CA0000-T0 | **0R,与 Part Label 一致** |
关闭时的证据来自上一轮 `report.json` 的新轮采集结果;本次检查了两轮原工程哈希一致。对照数据另存为 `control-comparison.json`。因此本次验证了开关实际改变写入结果,而不只是界面状态或命令字段发生变化。
## 耗时与证据
- BOM 导入及真实库存采集:126.910 秒。
- 点击执行至保存重开核验完成:231.631 秒,包含重新确认库存、启动 CAD 和实际替换。
- 全新会话独立读取及退出:45.771 秒。
- 分阶段计时:`execution-measurements.csv`;原生事务、日志和私有会话记录保存在任务 `quick-run` 及 `quick-run-history` 中。
- 独立结果:`independent-attributes.json`;最终 `report.json` 为 `verified=true`、`source_project_unchanged=true`。
- 界面截图:`01-part-label-enabled.png`、`02-part-label-completed.png`。
本次仅补齐普通 Part Label 复制路径的真实验证,没有把既有 COM 偶发启动阻塞或千步性能目标记作已解决,也没有重新跑整套基础测试。
@@ -0,0 +1,50 @@
# 2026-10-15 私有桌面正式执行验证
> 本文记录源码接入阶段的验证;后续 1.1.1 成品已完成打包,见 [1.1.1 版本说明](../releases/v1.1.1.md)。下文“本轮没有打包”保留该阶段的实际边界。
任务中心源码已把私有桌面接入自动采集、单步替换、批量工程会话及中断恢复,完成成功、暂停和异常退出的资源清理。本轮没有打包;此前 EXE 不包含这些更新。
实现提交:`5c0f6a3`、`f26e868`、`fee1aff`、`48ad7b3`。原始工程未修改,原生测试仅操作 `build/private-desktop-native` 下独立副本。环境为 Windows、Python 3.12、DxDesigner EE 7.9.5;中央库使用本机已安装库。压缩证据及原始文件 SHA-256 见 [JSON 数据](data/2026-10-15-private-desktop-execution.json)。不提交工程、中央库或大型供应商文件。
## 实际接入与资源边界
显式普通启动 `viewdraw.exe`,通过随机私有 desktop 中的 ROT 连接自有实例,再绑定会话 GUID。`-Embedding` 启动没有提供可用 ROT,`DispatchEx` 也不能作为本机可靠的私有启动方式,正式执行没有沿用这两条路径。
活动工程读写校验 desktop、GUID 和活动图页 HWND 所属 PID。关闭最后工程后,CAD 的 ActiveViewHandle 可能保留已销毁或已复用的窗口值;无活动图页的启动与退出使用显式自有 CAD 启动、私有 ROT 和 GUID,不声称此时也有可靠的活动图页 PID 校验。身份不符立即停止,不回退主桌面或创建未受控的 COM 实例。
进程以挂起状态创建,先加入本工具持有的 Job,再恢复运行。正常收尾先要求工程关闭,再请求 CAD Quit 并等待退出;随后清理自有进程树、关闭句柄,枚举 window station 确认私有桌面消失。保留每次会话证据,避免恢复或重试覆盖前一次释放记录。释放失败会留下不确定状态,不能作为正常任务成功。
单步入口现在也先备份,再保存、重开回读及关闭,避免后台退出丢弃尚未保存的修改。恢复入口可以重新打开绑定工程,完成属性核验、保存与回读后关闭,不需要用户去隐藏桌面手动保存。
## 原生实测
| 用例 | 实际结果 | 耗时 |
| --- | --- | ---: |
| 同一工程两步替换 | RL02、RL05 分别替换;NC 开、关各一步;均 saved_ok;1 个持久 worker | 任务合计 284.208 秒 |
| 保存后的独立枚举 | 按 UID、位号、料号检查 13 项:2 项变更,11 项保留 | 独立运行,不计入任务合计 |
| 公开单步入口 | 仅 RL06 修改,备份、保存、重开核验、关闭及 CAD 释放通过 | 168.765 秒 |
| 模拟保存后中断并恢复 | 仅在副本任务状态中注入中断;恢复 restored_ok,清除保护锁,无重复原生替换 | 104.998 秒 |
| 恢复后独立枚举 | 13 项全部匹配:RL06 已变更,其余 12 项保留原料号 | 另开独立后台 CAD 读取 |
| 多页队列暂停 | PON 的 block、01_POWER、02_ZX279133L 三页 no_match 后在 3/18 暂停;1 个 worker,退出并释放 | 83.992 秒 |
| 启动取消 | 0.8 秒发取消,尚未运行工程 worker,退出自有进程并释放桌面 | 含实际 CAD 启动尝试 |
| watchdog 超时 | 模拟卡住的 worker 及其子进程被自有 Job 清理;CAD 退出、桌面释放,保护状态保留 | 含实际 CAD 启动与退出 |
两步替换各耗时 157.410、121.297 秒,原生 Replace Part 阶段分别为 32.797、33.953 秒。任务准备 0.037 秒,备份 0.352 秒,两次进度同步为 0.013、0.009 秒。子步骤、内部阶段和任务合计存在包含关系,不应重复相加;JSON 保留每一步的内部阶段耗时。
本机成功启动私有 CAD 约 22~35 秒,正常退出约 1.8~2.7 秒。私有桌面解决前台隔离和所有权问题,不承诺提升原生 CAD 吞吐量,也不能把此前主桌面的多工程测量直接当作当前后端的速率。
## 主桌面与释放观测
暂停、单步/恢复/独立读回、取消/超时三个观测组共 **1997 次采样、6 次 CAD 会话**。每次采样都成功读取普通文件;输入桌面前后均为 Default,自有 CAD 没有成为主桌面前台,也未出现在输入桌面窗口清单。原来主桌面的 CAD PID 18732 保持原样。6 个自有 CAD 均确认退出,6 个私有桌面均确认消失。
这证明本次测试中没有抢占主桌面,普通文件可读取;不是所有系统负载和第三方 CAD 插件场景的性能保证。目标工程仍须保存关闭,不允许主桌面和后台同时编辑同一工程;许可证、CPU、磁盘和中央库仍共享。
## 自动回归、审查及测量问题
运行 `python -m pytest tests/v1_1 tests/trial_task_center/test_batch.py tests/trial_task_center/test_application.py tests/trial_task_center/test_quick_run.py tests/trial_task_center/test_recovery.py tests/trial_task_center/test_worker_monitor.py -q -x -k 'not thousand_item_multisheet_mixed_queue'`,结果 **310 passed、1 deselected,88.93 秒**。随后补充的会话证据留存及隐藏 helper 入口回归在 `test_isolated_cad.py` 中执行,**10 passed,4.47 秒**;与前述数量重叠,不相加。
桌面资源测试包含真实 Win32 进程树退出及另一个进程保留 desktop 句柄时不得报告释放成功。独立代理只读审查未发现新增可操作问题。未重复无关的千步模拟压力测试:此前本机基线和优化分支均超过原有时间门槛,门槛未修改;这条记录不能作为本轮全量压力测试通过的声明。
两步替换首次成功运行后,观测器在收尾时未识别 `pywintypes.error(2)`,因此没有写出 report.json。该用例结论由仍完整保留的 status、事件计时及独立 components.tsv 重建;不补造其前台采样记录。随后修正了原生错误捕获,完成暂停、单步/恢复和异常用例观测。异常观测第一轮另遇 Windows 替换状态文件时短暂拒绝读取;观测器加入短暂重试,重跑通过。测量脚本现在即使观测器失败也保留报告。
边界:本轮真实替换使用单工程两步及独立单步;此前三个不同工程的实测见 [旧后端多工程回归](2026-10-15-multi-project-regression.md),不混称当前私有后端多工程实测。多页暂停用例是 no_match,不是跨页替换。NC 开关传递已覆盖,但所选真实样本没有独立 `/NC` 标记,未重新验收该标记的转换效果。没有执行新的 Packager、ERC、网表验收,也没有生成发布包。
@@ -0,0 +1,49 @@
# 工程会话、统一快照与可取消查询验证
本轮在原 V1.1.0 上实施用户批准的四项优化,基线为 `bc6b726`,分支为 `codex/execution-responsiveness`。完成后推送同名远端分支,不打包。真实 CAD 操作全部针对 `build/session-live-20261015` 下的独立副本。
## 实现
1. 同工程多步骤保留一个受监督的 VBS worker。每次修改仍保存、关闭、重开并回读校验,下一步复用回读后的工程;暂停、完成和换工程时关闭自有会话。随机令牌、冻结命令和图页确认继续有效。注入的模拟执行器保留原单步协议。
2. `TaskBundle` 用一个 SQLite 只读事务读取任务、工程、规则和位号计划;`QuickRunSnapshot` 复用一次证据文件解析,检查读取前后文件代次,最多重试三次,持续变化时禁止给出续跑坐标。创建任务 facade 复用已初始化 runner,避免查询触发启动恢复写入。
3. UI 查询最多两个运行项、一个合并后的最新待办项。切换或关闭时取消旧 token;文件分块读取、逐行解析、数据库锁和日志锁等待均检查取消。底层单次系统调用仍需返回后才能退出,线程数量保持有界。
4. 拆出协议、快照、只读工程枚举、会话 transport、数据库迁移、位号计划存储和任务读取模块。`quick_run.py` 从 2100 行降至 1866 行,`store.py` 从 1364 行降至 1083 行;剩余执行状态机继续保留在原模块。
工程首次打开可能规范化数据库。发现已知内容变化后丢弃该次枚举,只允许重试一次;仍不稳定则阻断。缓存仅精确排除 `database/cdbsvr/{log,plog,events}` 运行审计目录,权威数据库及图页仍校验内容哈希;初次无法取得指纹时允许一次全新、不缓存的枚举。
## 真实替换对照
工程为 CBB `1GPHY_8211.prj` 的两份独立副本;同页 `RL02` 与 `RL05` 分两步执行,分别测试 NC 同步开、关。旧料号 `4100-CA3300-T7`,新料号 `4100-CA3300-2200`。两种方式均独立重新枚举确认:2 个选中位号改为新料号,11 个未选中位号保持旧料号。
| 指标 | 原单步方式 | 会话复用 |
| --- | ---: | ---: |
| 整个队列 | 113.175 秒 | 100.641 秒 |
| 第一步 | 64.371 秒 | 56.797 秒 |
| 第二步 | 47.418 秒 | 41.168 秒 |
| worker 启动次数 | 2 | 1 |
| OpenProject 调用次数 | 4 | 3 |
| 成功保存并重开验证 | 2 | 2 |
| 独立回读核对 | 13/13 | 13/13 |
这一次本机样本总耗时减少 11.1%;有 CAD 缓存与机器负载差异,不能推广为所有项目的固定提升。统计含队列准备、备份和最终关闭;独立验证不计入队列耗时。逐步原生阶段耗时见 `build/session-live-20261015/{small-baseline,small-reuse}/report.json`。
## 图页、暂停与外部操作保护
PON 的 18 页清单中,连续验证 `block`、`01_POWER`、`02_ZX279133L` 三个图页,耗时分别为 16.364、4.627、10.181 秒;一个 worker,三个 `no_match` 检查点,完成 3/18 后退出会话并确认工程关闭。总计 34.737 秒,证据为 `build/session-live-20261015/multi-page/report.json`。此测试验证原生换页和中途关闭,不作为跨页实际替换成功的证据。
独立副本上的三项原生边界探针均通过:正常关闭自有工程;等待期间外部修改 Value 时中止并保留编辑;等待期间切换至其他工程时中止并保留其他工程。不能确认关闭时写入 `uncertain.flag`。证据为 `build/session-live-20261015/guards2/{clean,edit,foreign}/guard-report.json`。
PON 的原单步替换基线尝试耗时 166.381 秒,三步中一项成功、一项原生替换失败、一项保存后回读失败。失败原生报告停在 `pin_promotion_started`,尚不能证明 COM 崩溃等具体原因。本轮没有把它计作成功性能对照,也没有反复重跑状态不确定的副本。首次尝试还遇到测量脚本未传递 PYTHONPATH 的问题,修正测试脚本后才进行上述统计。
## 自动化回归
- 集成回归:224 passed,1 deselected,84.85 秒。范围为 V1.1 界面、日志、取消、工程发现,以及原 store、service、batch;单独排除千步性能用例。
- 快照、数据库只读事务和监督器定向回归:42 passed,13.06 秒。
- 后续增加 worker 失败后重建的回归,会话专用 6 项通过,4.90 秒;此前集成已覆盖其中 5 项。原单步执行器兼容性回归另有 34 项通过,4.52 秒;自动化去重合计 301 项通过。
- 千步压力测试:20 个工程 × 5 页 × 10 条规则,共 1000 步,91 项保存、909 项未命中,全部任务唯一执行并正确完成,峰值 1.94 MiB。当前耗时 41.516 秒(24.09 步/秒),未通过 30 秒门槛。
- 原基线 `bc6b726` 在同机、同一个用例、同样启用 tracemalloc 条件下的对照为 42.453 秒,也未通过 30 秒门槛。原子命令写入和事件日志在两版没有变化,快照解析不在逐步循环内;未发现新增热点导致退化。旧记录的 22.376 秒不能替代本次实测,不放宽阈值,不把耗时检查记为通过。
- F 盘指定临时目录的一次压力尝试在第 139 步发布命令时遇到 WinError 5,安全停止,未形成完整性能数据。随后 C/F 盘各 120 次 fsync+replace 探针未复现,不能据此断言具体占用进程;保留该现场限制。
版本化的逐步阶段耗时、回读摘要及保护探针结果见 `docs/testing/data/2026-10-15-project-session.json`;完整原生执行证据保留在上述本机构建目录中。
可复用的原生测量脚本为 `tools/measure_project_session.py`,保护探针为 `tools/probe_project_session_guards.py`,多页探针为 `tools/probe_project_session_pages.py`。它们运行前要求当前 CAD 没有打开工程。
@@ -0,0 +1,37 @@
# 全流程审查修复记录
1.1.2 开发版,修复 2026-10-15 审查确认的八项问题;本轮不打包、打标签或发布。
| 审查问题 | 修复后的行为 |
| --- | --- |
| 修改规则与实际执行不一致 | 修改默认值时,更新仍沿用旧默认值的位号;保留手动新料号、NC、Value 和勾选。界面说明实际执行依据保存的位号计划。Value 开关及文本作为一组覆盖。删除或停用默认规则不删除用户已保存计划。 |
| 本批规则实际上只作用于当前任务 | 增删改及排序在同一事务中作用于未删除的同批任务;冻结成员阻止整个修改。历史缺失规则可合并,冲突规则须显式统一;合并规则仍执行链式替换、循环校验。 |
| 首次保存后不能补充旧料号 | 缺少请求旧料号时,重新采集既有与新增旧料号的合集;验证既有身份全部未变再扩展库存,保留编辑。BOM 预览不写数据库。 |
| 成员变化后旧 BOM 预览无法恢复 | 新预览替换重叠范围;未重新导入的编辑保留。已删除成员保留其暂存库存及基线,恢复后可保存或通过新导入合并;永久删除才清理其草稿。 |
| 关闭窗口静默丢草稿 | 检查所有任务的当前表格、隐藏草稿及暂存 BOM;保存全部、放弃、取消。保存全部为一个事务,任一失败整体回滚且窗口保留草稿。 |
| 无入口恢复删除任务 | 左侧新增独立回收站按钮,支持搜索、排序、恢复、永久删除。原状态下拉框继续隐藏。新建任务后返回正常任务列表。 |
| 原生枚举顺序变化误报工程变化 | 按图页、匹配内容及完整器件身份比较,忽略枚举顺序;拒绝重复身份及真实字段变化,保留 ICDB 全量指纹和两次读取核验。 |
| 采集及 BOM 导入没有进度和取消 | 显示工程序号、名称及读取阶段;取消传到原生启动及监控。只读脚本先在安全边界退出,再释放自有 CAD 会话;异常清理保留诊断并阻止自动关闭。 |
另补齐恢复保护对 `native_replace_applied`、`pin_promotion_started` 的识别;工程继续指令因 Windows 短暂共享拒绝而读取失败时有界重试,token 与 checkpoint 校验不变。
## 验证
- 适用的完整默认回归:**260 passed,57.34 秒**。最后补充回收站中新建任务返回正常列表后,相关界面回归 **24 passed,12.79 秒**。
- 原生控制、规则事务和会话监控专项(含默认套件之外的 worker-monitor 检查):**36 passed,11.03 秒**。
- 子代理交叉审查发现并修复“保存全部部分提交”“恢复任务缺失暂存库存”“历史规则合并漏检链式替换”;对应回归及复审通过。
- 真实 WSH 读取被 Windows 独占打开的控制文件:短暂拒绝后成功读取;使用真实子进程检查协作取消确认收尾,再返回结果。无 CAD 或用户工程写入。
本机 C 盘在首轮完整回归中已无剩余空间,SQLite 报 disk full。最终测试仅在测试进程中将 TEMP、TMP、LOCALAPPDATA 指向 F 盘隔离目录,未修改用户环境变量或清理用户文件。
## 七工程 CBB 复放
复用先前实际原生采集并核对过的库存,运行真实 Qt 导入与保存界面:
- 7 个工程、39 个库存位号、25 个启用目标。
- 预览前后保存计划一致;跨任务预览、批量保存、关闭数据库并重新打开核对全部通过。
- 输入工程哈希未变;没有启动新的 CAD 会话,没有执行本轮实际替换。
- 本次与完整回归并行时预览 6.060 秒、保存 4.515 秒;这些受并发负载影响的数字不作为性能提升结论。
- 完整证据:`build/cbb-review-remediation-replay-20261015/report.json`,同目录包含预览与保存后截图。
该复放只使用先前完整匹配的 15 条 BOM 记录。原表其余 48 条与工程信息不完整匹配的问题仍需核对数据;本轮没有猜测位号或伪造匹配。此前出现过的 COM 服务器异常亦未据此宣称根因已修复。
@@ -0,0 +1,42 @@
# 1.1.2 工作区与结果展示优化验证
本轮为开发版迭代,不打包、不新增 tag 或 release。
## 已修复
- BOM 校验报告按导入发起批次归属;跨批次隐藏,切回同批任务恢复。导入回调捕获批次,不按回调时的选中任务猜测归属。
- BOM 数量摘要留在主界面,详细报告和执行日志可独立打开、关闭,不再挤占位号表。重新打开已完成任务不强制展开日志。
- 上方保留本批规则与位号计划。Value 策略独立可见,表格的“新 Value”改为“自定义内容”,避免误解为实际回读值。
- 工程路径单行省略,完整路径可通过 tooltip 和复制按钮获取;内部 quick_run_result 状态不直接显示给用户。
- 默认 BOM 模板保持直接入口;原位号 Excel 导入/导出收进菜单。批量替换/保留明确作用于当前工程或搜索可见行。
- 位号表支持表头排序,排序/筛选后的编辑、勾选和批量修改仍映射原始 UID;QTableView 使用一致的表格和选中样式。
- 执行确认说明更新为当前受监督私有桌面方式,要求待处理工程不被其他 CAD 会话占用。
- 结果窗口显示日志页内实际执行回读的图页、位号、旧料号、回读料号和核验状态。失败、未命中及未执行计划不生成成功记录;每页结果视图最多显示最近 500 条,完整日志可翻页。
- 日志序号仅在文件身份、大小、mtime、ctime 均未变化时复用;外部追加、替换、轮转或写入失败后重新读取。缓存最多 64 个文件,保留原有 flush/fsync。
## 界面复放
默认回归套件:313 passed,261.25 秒。最后补充的无数据行表头错误用例及相关 BOM/结果用例:12 passed,10.45 秒;结果/日志末尾微调:10 passed。未为样式修改重跑 CAD 或重复整套测试。
执行命令:
```powershell
python tools/probe_workspace_layout.py --source build/bom-native-roundtrip-fixed-20261015 --output build/ui-workspace-final-20261015
```
脚本只复制历史测试数据库与证据进行复放,不启动 CAD。原测试数据库 SHA-256 未变化。
- 使用含 302 字符工程路径的两工程真实执行证据。
- 1280×880 与 980×700 均检查;窄窗口位号表 viewport 为 135 像素(修复前为 0),最小尺寸提示高度从 850 降为 650。
- 执行、开始新一轮、BOM 模板、Value 开关均在主窗口范围内;表格与下方批量按钮无重叠。
- 跨批次无前批工程报告残留,切回恢复报告。
- 实际结果页显示 RV05:4100-CA0000-T0 → 4100-CA0000-T7,状态为已保存并核验。
- 截图与机器可读结果位于上述 output 目录。历史列宽设置会继续保留,窄窗口可横向滚动。
## 性能边界
千步原测试:20 工程 × 5 图页 × 10 规则,模拟执行器并启用 tracemalloc。共 1000 步,91 saved、909 no_match,顺序与唯一编号断言全部通过。
本次耗时 **33.387 秒,29.95 步/秒,峰值 2,201,853 字节**。原 `<30 秒` 性能断言仍失败,未调整阈值。定位证据 `build/queue-before.prof` 显示文件 open/stat、原子发布和持久写入为主要开销;文件锁与同步盘环境会影响耗时。此次序号缓存减少重复尾部读取,不能据此声称整体吞吐已达标。未移除持久写入或核验保护。
COM 启动偶发阻塞的根因和跨进程采集缓存仍待独立优化;本轮没有扩大启动时限,也没有减少采集一致性检查。历史日志没有单独记录的实际 Value 不由计划或库信息推算。本轮采用真实执行证据复放验证界面,原生替换与私有桌面释放沿用此前的实机验证证据。
@@ -0,0 +1,485 @@
{
"date": "2026-10-15",
"implementation_commit": "48ad7b3",
"platform": "Windows / DxDesigner EE 7.9.5 / Python 3.12",
"batch": {
"reconstructed_from_persistent_evidence": true,
"observer_finalization_failed": "pywintypes.error(2) was not caught; report.json was not written. Business status, per-step events and independent inventory remain available. Fixed observer used by later cases.",
"task_id": "5efd57e0-3de1-4f9a-850f-42a5593e301b",
"task_total_seconds": 284.20772400000715,
"worker_starts": 1,
"steps": [
{
"refdes": "RL02",
"sync_nc": true,
"state": "saved_ok",
"seconds": 157.4097580999951,
"worker_stage_seconds": {
"starting": 0.9370000000053551,
"session_startup": 1.422000000020489,
"check_project": 0.046999999962281436,
"open_project": 14.14000000001397,
"open_sheet": 12.548000000009779,
"session_ready": 0.046000000002095476,
"query_components": 2.125,
"index_components": 13.01600000000326,
"find_components": 2.8439999999827705,
"index_pins": 11.437999999994645,
"snapshot_attributes": 0.75,
"capture": 7.60999999998603,
"before_native": 0.26500000001396984,
"native_replace": 32.796999999991385,
"restore_preflight": 7.139999999984866,
"before_restore_transaction": 1.1570000000065193,
"restore_attribute_fields": 3.0460000000020955,
"restore_attributes": 0.0,
"verify_restoration": 0.4380000000237487,
"verify_attribute_fields": 0.7810000000172295,
"finished": 7.2339999999676365,
"save_and_close": 2.0940000000118744,
"verify_saved_project": 0.0,
"session_wait": 0.0
}
},
{
"refdes": "RL05",
"sync_nc": false,
"state": "saved_ok",
"seconds": 121.29693060001591,
"worker_stage_seconds": {
"check_project": 0.061999999976251274,
"open_sheet": 10.09299999999348,
"query_components": 1.1570000000065193,
"index_components": 8.51600000000326,
"find_components": 2.3589999999967404,
"index_pins": 11.39100000000326,
"snapshot_attributes": 0.7659999999741558,
"capture": 12.437000000005355,
"before_native": 0.34400000001187436,
"native_replace": 33.95299999997951,
"restore_preflight": 7.985000000015134,
"before_restore_transaction": 1.0780000000086147,
"restore_attribute_fields": 3.202999999979511,
"restore_attributes": 0.0,
"verify_restoration": 0.5000000000291038,
"verify_attribute_fields": 0.6719999999913853,
"finished": 16.264999999984866,
"save_and_close": 4.219000000011874,
"verify_saved_project": 0.01600000000325963,
"open_project": 6.047000000020489,
"session_wait": 0.0
}
}
],
"comparisons": [
{
"uid": "$1I362",
"refdes": "RL02",
"expected": "4100-CA3300-2200",
"actual": "4100-CA3300-2200"
},
{
"uid": "$1I551",
"refdes": "RL05",
"expected": "4100-CA3300-2200",
"actual": "4100-CA3300-2200"
},
{
"uid": "$1I559",
"refdes": "RL06",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"uid": "$1I567",
"refdes": "RL07",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"uid": "$1I575",
"refdes": "RL08",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"uid": "$1I583",
"refdes": "RL09",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"uid": "$1I584",
"refdes": "RL10",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"uid": "$1I585",
"refdes": "RL11",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"uid": "$1I586",
"refdes": "RL12",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"uid": "$1I615",
"refdes": "RL13",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"uid": "$1I616",
"refdes": "RL14",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"uid": "$1I617",
"refdes": "RL15",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"uid": "$1I618",
"refdes": "RL16",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
}
],
"session": {
"desktop": "dx-0e24d247e2bb44fc9d2cfb865751d03b",
"token": "0e24d247e2bb44fc9d2cfb865751d03b",
"state": "released",
"cad_pid": 26884,
"guid": "{AC2760DDx0ECCx4125x902Ax58D3762F7FD0}",
"clean": true
}
},
"single_and_recovery": {
"single_step_seconds": 168.76488050000626,
"single_step_state": "saved_ok",
"recovery_seconds": 104.99790590000339,
"recovery_state": "restored_ok",
"single_step_session": {
"desktop": "dx-ef24499c663e4059bb88ca4c5480428b",
"token": "ef24499c663e4059bb88ca4c5480428b",
"state": "released",
"cad_pid": 5188,
"guid": "{E07B201BxC81Dx4624xB0D2xE684F407C972}",
"startup_seconds": 34.312999999994645,
"clean": true,
"shutdown_seconds": 1.8590000000258442
},
"recovery_session": {
"desktop": "dx-b09cc37f113e48abbe4f1e8a6fbc493b",
"token": "b09cc37f113e48abbe4f1e8a6fbc493b",
"state": "released",
"cad_pid": 51976,
"guid": "{6418A6B6x512Bx434ExAC8Ax7C518FCFAA9E}",
"startup_seconds": 21.98399999999674,
"clean": true,
"shutdown_seconds": 1.9689999999827705
},
"comparisons": [
{
"refdes": "RL02",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL05",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL06",
"expected": "4100-CA3300-2200",
"actual": "4100-CA3300-2200"
},
{
"refdes": "RL07",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL08",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL09",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL10",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL11",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL12",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL13",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL14",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL15",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL16",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
}
],
"verified": true
},
"pause": {
"project": "F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\build\\private-desktop-native\\pages-pause\\project\\PON.prj",
"steps": [
{
"sheet": [
"PON",
"block"
],
"state": "no_match",
"seconds": 46.64777720000711
},
{
"sheet": [
"PON",
"01_POWER"
],
"state": "no_match",
"seconds": 10.285367300006328
},
{
"sheet": [
"PON",
"02_ZX279133L"
],
"state": "no_match",
"seconds": 20.456011000002036
}
],
"passed": true,
"closed_between_steps": true,
"worker_starts": 1,
"paused": true,
"completed_items": 3,
"total_items": 18,
"seconds": 83.99234019999858
},
"faults": {
"startup_cancelled": true,
"watchdog_timeout": true,
"worker_exit_confirmed": {
"parent": true,
"child": true
},
"passed": true
},
"desktop_observations": {
"single_and_recovery": {
"samples": 1440,
"file_read_samples": 1440,
"input_desktop_before": "Default",
"input_desktop_after": "Default",
"foreground_pids": [
10104
],
"owned_cad_became_foreground": false,
"owned_cad_on_input_desktop": false,
"baseline_default_cad_pids": [
18732
],
"observed_default_cad_pids": [
18732
],
"cad_exit_confirmed": {
"5188": true,
"51976": true,
"55520": true
},
"desktop_absent": {
"dx-ef24499c663e4059bb88ca4c5480428b": true,
"dx-b09cc37f113e48abbe4f1e8a6fbc493b": true,
"dx-ae937db569b34cb9827ba6ec481be55e": true
},
"sessions": {
"dx-ef24499c663e4059bb88ca4c5480428b": {
"desktop": "dx-ef24499c663e4059bb88ca4c5480428b",
"token": "ef24499c663e4059bb88ca4c5480428b",
"state": "released",
"cad_pid": 5188,
"guid": "{E07B201BxC81Dx4624xB0D2xE684F407C972}",
"startup_seconds": 34.312999999994645,
"clean": true,
"shutdown_seconds": 1.8590000000258442,
"evidence_path": "data\\tasks\\94da06ed-1f50-4396-9340-7df8f616e71c\\quick-run\\private-desktop.json"
},
"dx-b09cc37f113e48abbe4f1e8a6fbc493b": {
"desktop": "dx-b09cc37f113e48abbe4f1e8a6fbc493b",
"token": "b09cc37f113e48abbe4f1e8a6fbc493b",
"state": "released",
"cad_pid": 51976,
"guid": "{6418A6B6x512Bx434ExAC8Ax7C518FCFAA9E}",
"startup_seconds": 21.98399999999674,
"clean": true,
"shutdown_seconds": 1.9689999999827705,
"evidence_path": "data\\tasks\\94da06ed-1f50-4396-9340-7df8f616e71c\\quick-run-history\\recovery-29865845abda42de8392273c2490efcf\\worker\\private-desktop.json"
},
"dx-ae937db569b34cb9827ba6ec481be55e": {
"desktop": "dx-ae937db569b34cb9827ba6ec481be55e",
"token": "ae937db569b34cb9827ba6ec481be55e",
"state": "released",
"cad_pid": 55520,
"guid": "{71E521C8xD25Ex4028x9C35xAA7FB9D692F2}",
"startup_seconds": 28.59399999998277,
"clean": true,
"shutdown_seconds": 1.7660000000032596,
"evidence_path": "independent-read\\quick-run-history\\sheet-discovery-1103116427664f7a9db30fb37a5d2fa5\\private-desktop.json"
}
},
"observer_errors": []
},
"pause": {
"samples": 375,
"file_read_samples": 375,
"input_desktop_before": "Default",
"input_desktop_after": "Default",
"foreground_pids": [
10104
],
"owned_cad_became_foreground": false,
"owned_cad_on_input_desktop": false,
"baseline_default_cad_pids": [
18732
],
"observed_default_cad_pids": [
18732
],
"cad_exit_confirmed": {
"54972": true
},
"desktop_absent": {
"dx-3284592a031c46c28d1c0ac187b9c6ed": true
},
"sessions": {
"data\\tasks\\351d9922-f28c-429e-bce1-862e31b3aef4\\quick-run\\private-desktop.json": {
"desktop": "dx-3284592a031c46c28d1c0ac187b9c6ed",
"token": "3284592a031c46c28d1c0ac187b9c6ed",
"state": "released",
"cad_pid": 54972,
"guid": "{32D71CB0xC1B6x4A8BxAF96x35B4051FC236}",
"startup_seconds": 35.25,
"clean": true,
"shutdown_seconds": 2.687999999994645
}
},
"observer_errors": []
},
"faults": {
"samples": 182,
"file_read_samples": 182,
"input_desktop_before": "Default",
"input_desktop_after": "Default",
"foreground_pids": [
10104
],
"owned_cad_became_foreground": false,
"owned_cad_on_input_desktop": false,
"baseline_default_cad_pids": [
18732
],
"observed_default_cad_pids": [
18732
],
"cad_exit_confirmed": {
"56876": true,
"53404": true
},
"desktop_absent": {
"dx-96332c0efe8c40dcbd1e0fb98be3116e": true,
"dx-c35da69cb8434bbebdb3af729be91516": true
},
"sessions": {
"dx-96332c0efe8c40dcbd1e0fb98be3116e": {
"desktop": "dx-96332c0efe8c40dcbd1e0fb98be3116e",
"token": "96332c0efe8c40dcbd1e0fb98be3116e",
"state": "released",
"cad_pid": 56876,
"clean": false,
"startup_error": "private CAD startup was cancelled before execution",
"evidence_path": "data\\tasks\\startup-cancel\\quick-run\\private-desktop.json"
},
"dx-c35da69cb8434bbebdb3af729be91516": {
"desktop": "dx-c35da69cb8434bbebdb3af729be91516",
"token": "c35da69cb8434bbebdb3af729be91516",
"state": "released",
"cad_pid": 53404,
"guid": "{814B8CF2x0B4Fx486DxBD1ExBE0B1A5B29CD}",
"startup_seconds": 32.84399999998277,
"error": "Command '('C:\\\\Users\\\\ABS_Windows\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python312\\\\python.exe', '-u', 'F:\\\\Sync Tool Skyworth\\\\Work Maps\\\\dxdesigner-part-replacement\\\\build\\\\private-desktop-native\\\\failures-retry\\\\data\\\\tasks\\\\timeout\\\\quick-run\\\\stalled-worker.py', 'F:\\\\Sync Tool Skyworth\\\\Work Maps\\\\dxdesigner-part-replacement\\\\build\\\\private-desktop-native\\\\failures-retry\\\\data\\\\tasks\\\\timeout\\\\quick-run', 'C:\\\\Users\\\\ABS_Windows\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python312\\\\python.exe', '', 'timeout')' timed out after 3.0 seconds",
"clean": false,
"shutdown_seconds": 4.280999999988126,
"evidence_path": "data\\tasks\\timeout\\quick-run\\private-desktop.json"
}
},
"observer_errors": []
}
},
"automated_regression": {
"passed": 310,
"deselected": 1,
"seconds": 88.93,
"deselected_test": "thousand_item_multisheet_mixed_queue",
"reason": "Unchanged simulated stress test exceeds host timing gate on both baseline and earlier optimization checkout; threshold not changed.",
"followup_isolated_cad_tests": {
"passed": 10,
"seconds": 4.47
}
},
"limitations": [
"No new package built.",
"No Packager/ERC/netlist qualification performed.",
"NC toggle on/off exercised; this real fixture contains no independent /NC marker.",
"Private batch evidence uses one project, two real replacement steps. Prior three-project evidence used the previous backend.",
"Pause covers actual multi-page no_match steps, not multi-page replacements.",
"Startup/quit of empty CAD bind explicit PID-owned launch and private ROT/GUID; active view PID is verified only with an open project."
],
"raw_source_sha256": {
"build\\private-desktop-native\\replacement3\\data\\tasks\\5efd57e0-3de1-4f9a-850f-42a5593e301b\\events.jsonl": "d5438645d0441b71e0b761bb570586c4b5a6debf86c8877203150646f7f00728",
"build\\private-desktop-native\\replacement3\\data\\tasks\\5efd57e0-3de1-4f9a-850f-42a5593e301b\\quick-run\\command.tsv": "9586b5a449089da81b9517793900bda76c98be20a31644a788e60d59cc996643",
"build\\private-desktop-native\\replacement3\\data\\tasks\\5efd57e0-3de1-4f9a-850f-42a5593e301b\\quick-run\\status.tsv": "7efec1a407ec23606fbdd4569a0b36d57db441fa9506850cbd91e125d3439f47",
"build\\session-live-20261015\\small-inventory.json": "38783d947877e657a2c443496f95ab39f32182f84af1f25d444fffd7f9fe8159",
"build\\private-desktop-native\\replacement3\\independent-read\\quick-run-history\\sheet-discovery-4159ca5ab5404a1f893247cf74b07ebf\\components.tsv": "788a2c87178edd2fab065d3cf405a4cabbec0f0f1b5f3f12f3da3145807f7b51",
"build\\private-desktop-native\\single-recovery\\report.json": "c1a41f935d438e1bfe65a7d67dbafca41ce441aa0ce3a0cad0530c76ebf7d779",
"build\\private-desktop-native\\pages-pause\\report.json": "d7e6a965d1accbdb8af402fa0ab370121fe7a062c5445cbac480e0d447f37e3c",
"build\\private-desktop-native\\failures-retry\\report.json": "c6d2144f8a8593c5e0860ec4a9645411c55cffdd0de49e8c3f473068c102f0cd",
"build\\private-desktop-native\\single-recovery\\desktop-observation.json": "73d2ec95e802044050ef26f020ae331ea336129493b5fe57a2f9f9fd6e3e133f",
"build\\private-desktop-native\\pages-pause\\desktop-observation.json": "62406dfd60d66e2bb854d5ed62d9988afa200464a8a7a59df9867cb610241568",
"build\\private-desktop-native\\failures-retry\\desktop-observation.json": "448ce3317928e6ae547e662b551afcfba61fe17f95b95b9d1120b31aa2cb36ba",
"build\\private-desktop-native\\replacement3\\data\\tasks\\5efd57e0-3de1-4f9a-850f-42a5593e301b\\quick-run\\private-desktop.json": "d929b5a2d81b628866dc8a57af59356ce30e58f9be82933da531cae986d00918"
}
}
@@ -0,0 +1,124 @@
{
"release_status": "development only; user explicitly stopped packaging/publication",
"bom_contract": "one workbook for all projects in imported group; project name/path prefilled; preview and atomically confirm per-task plans",
"regression": {
"prior_related_passed": 252,
"prior_related_seconds": 53.67,
"final_bom_ui_passed": 17,
"final_bom_ui_seconds": 5.62,
"counts_overlap": true
},
"covered_behaviors": [
"export before inventory",
"route identical refdes by project",
"unknown project rejected before collection",
"no DB plan change during preview",
"automatic read-only collection when inventory absent",
"reuse existing inventory",
"atomic rollback of all affected tasks",
"stale preview rejection",
"untouched project scaffolds ignored",
"task reorder and reimport",
"cross-task UI editing and batch save",
"execution enabled after confirmed import without separately entered rules"
],
"native_long_evidence_path": {
"passed": true,
"seconds": 54.78491889999714,
"sheets": [
[
"1GPHY_8211",
"8211_1GPHY_48PIN"
]
],
"component_count": 13,
"evidence_path_length": 318,
"alias_paths": [
"C:\\Users\\ABS_Windows\\AppData\\Local\\DxProductivity\\path-links\\dxp-qyr7umy5\\9e4825fbe28f7eeec038"
],
"aliases_removed": true,
"original_evidence_retained": true,
"session": {
"desktop": "dx-325ab7da547e495abda9e92ae53c51c0",
"token": "325ab7da547e495abda9e92ae53c51c0",
"state": "released",
"cad_pid": 21520,
"guid": "{EE1C86F6x9590x41D1x90DAxF4116093AC87}",
"startup_seconds": 34.171999999991385,
"clean": true,
"shutdown_seconds": 1.75
}
},
"native_desktop_observation": {
"samples": 250,
"file_read_samples": 250,
"input_desktop_before": "Default",
"input_desktop_after": "Default",
"foreground_pids": [
10104
],
"owned_cad_became_foreground": false,
"owned_cad_on_input_desktop": false,
"baseline_default_cad_pids": [
18732
],
"observed_default_cad_pids": [
18732
],
"cad_exit_confirmed": {
"21520": true
},
"desktop_absent": {
"dx-325ab7da547e495abda9e92ae53c51c0": true
},
"sessions": {
"dx-325ab7da547e495abda9e92ae53c51c0": {
"desktop": "dx-325ab7da547e495abda9e92ae53c51c0",
"token": "325ab7da547e495abda9e92ae53c51c0",
"state": "released",
"cad_pid": 21520,
"guid": "{EE1C86F6x9590x41D1x90DAxF4116093AC87}",
"startup_seconds": 34.171999999991385,
"clean": true,
"shutdown_seconds": 1.75,
"evidence_path": "independent-read\\quick-run-history\\sheet-discovery-7f404713e9ed4ac7b59ea68d6973e118\\private-desktop.json"
}
},
"observer_errors": []
},
"example_template": {
"example": "F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\dist\\按工程区分BOM模板示例.xlsx",
"rows": [
{
"project_name": "工程A/board.prj",
"project_path": "F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\build\\project-bom-template-preview\\projects\\工程A\\board.prj",
"old_part_number": null,
"new_part_number": null,
"refdes": null,
"schematic_name": null,
"sheet_number": null,
"uid": null,
"enabled": true,
"custom_value": null,
"sync_nc": true
},
{
"project_name": "工程B/board.prj",
"project_path": "F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\build\\project-bom-template-preview\\projects\\工程B\\board.prj",
"old_part_number": null,
"new_part_number": null,
"refdes": null,
"schematic_name": null,
"sheet_number": null,
"uid": null,
"enabled": true,
"custom_value": null,
"sync_nc": true
}
],
"sha256": "4e573f3eb920651d7482beadc7b2056939ef16c85de993b99099ef19d5e4bd2c",
"cad_started": false,
"published": false
},
"publication": "No v1.1.2 release/tag/upload; old candidate quarantined locally; v1.1.1 retained."
}
@@ -0,0 +1,518 @@
{
"baseline_commit": "bc6b726",
"note": "Single paired native sample; copied projects only. Thousand-step time gate remains failed in both versions.",
"native": {
"small-baseline": {
"queue_seconds": 113.17540310000186,
"worker_starts": 2,
"open_project_calls": 4,
"verified": true,
"readback_seconds": 9.846703400020488,
"comparisons": [
{
"refdes": "RL02",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-2200",
"actual": "4100-CA3300-2200"
},
{
"refdes": "RL05",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-2200",
"actual": "4100-CA3300-2200"
},
{
"refdes": "RL06",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL07",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL08",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL09",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL10",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL11",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL12",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL13",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL14",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL15",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL16",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
}
],
"steps": [
{
"old_part_number": "4100-CA3300-T7",
"new_part_number": "4100-CA3300-2200",
"sheet": "8211_1GPHY_48PIN",
"phase": "execute_step",
"unit": "step",
"completed_units": 1,
"state": "saved_ok",
"schematic_name": "1GPHY_8211",
"sheet_number": "8211_1GPHY_48PIN",
"job_id": "99f533d93c4a4dcabeb687b2311658af_0",
"worker_stage_seconds": {
"starting": 0.9839999999967404,
"session_startup": 2.4690000000118744,
"check_project": 0.0159999999741558,
"open_project": 15.78100000001723,
"open_sheet": 3.5310000000172295,
"session_ready": 0.0629999999946449,
"query_components": 0.75,
"index_components": 5.203000000008615,
"find_components": 0.7969999999913853,
"index_pins": 4.514999999984866,
"snapshot_attributes": 0.40700000000651926,
"capture": 2.6559999999881256,
"before_native": 0.07800000000861473,
"native_replace": 17.01600000000326,
"restore_preflight": 2.812000000005355,
"before_restore_transaction": 0.25,
"restore_attribute_fields": 0.6089999999967404,
"restore_attributes": 0.0,
"verify_restoration": 0.14199999999254942,
"verify_attribute_fields": 0.1870000000053551,
"finished": 1.9839999999967404,
"save_and_close": 4.062999999994645,
"verify_saved_project": 0.0
},
"elapsed_seconds": 64.37054100001114,
"units_per_minute": 0.932103398043363
},
{
"old_part_number": "4100-CA3300-T7",
"new_part_number": "4100-CA3300-2200",
"sheet": "8211_1GPHY_48PIN",
"phase": "execute_step",
"unit": "step",
"completed_units": 1,
"state": "saved_ok",
"schematic_name": "1GPHY_8211",
"sheet_number": "8211_1GPHY_48PIN",
"job_id": "99f533d93c4a4dcabeb687b2311658af_1",
"worker_stage_seconds": {
"starting": 0.42199999999138527,
"session_startup": 1.2810000000172295,
"check_project": 0.03199999997741543,
"open_project": 10.96799999999348,
"open_sheet": 2.0789999999979045,
"session_ready": 0.015000000013969839,
"query_components": 0.3129999999946449,
"index_components": 2.1559999999881256,
"find_components": 1.0310000000172295,
"index_pins": 3.6719999999913853,
"snapshot_attributes": 0.25,
"capture": 4.578000000008615,
"before_native": 0.125,
"native_replace": 14.51600000000326,
"restore_preflight": 1.327999999979511,
"before_restore_transaction": 0.21899999998277053,
"restore_attribute_fields": 0.5940000000118744,
"restore_attributes": 0.0,
"verify_restoration": 0.061999999976251274,
"verify_attribute_fields": 0.0940000000409782,
"finished": 1.25,
"save_and_close": 2.4060000000172295,
"verify_saved_project": 0.0
},
"elapsed_seconds": 47.418164899980184,
"units_per_minute": 1.2653378747692758
}
],
"other_phases": [
{
"phase": "prepare_queue",
"unit": "step",
"completed_units": 2,
"state": "completed",
"elapsed_seconds": 0.07470610001473688,
"units_per_minute": 1606.2945325258345
},
{
"phase": "backup_project",
"unit": "operation",
"completed_units": 1,
"state": "completed",
"elapsed_seconds": 0.9657479999877978,
"units_per_minute": 62.12800854959896
},
{
"phase": "persist_progress",
"unit": "operation",
"completed_units": 1,
"state": "completed",
"job_id": "99f533d93c4a4dcabeb687b2311658af_0",
"elapsed_seconds": 0.008863399998517707,
"units_per_minute": 6769.411287997185
},
{
"phase": "persist_progress",
"unit": "operation",
"completed_units": 1,
"state": "completed",
"job_id": "99f533d93c4a4dcabeb687b2311658af_1",
"elapsed_seconds": 0.00932809998630546,
"units_per_minute": 6432.178052131272
},
{
"phase": "task_total",
"unit": "task",
"completed_units": 1,
"state": "completed",
"completed_steps": 2,
"saved_steps": 2,
"failed_steps": 0,
"elapsed_seconds": 113.10993500001496,
"units_per_minute": 0.5304573820150464
}
]
},
"small-reuse": {
"queue_seconds": 100.6405139999988,
"worker_starts": 1,
"open_project_calls": 3,
"verified": true,
"readback_seconds": 10.346642499993322,
"comparisons": [
{
"refdes": "RL02",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-2200",
"actual": "4100-CA3300-2200"
},
{
"refdes": "RL05",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-2200",
"actual": "4100-CA3300-2200"
},
{
"refdes": "RL06",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL07",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL08",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL09",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL10",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL11",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL12",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL13",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL14",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL15",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
},
{
"refdes": "RL16",
"sheet": "8211_1GPHY_48PIN",
"expected": "4100-CA3300-T7",
"actual": "4100-CA3300-T7"
}
],
"steps": [
{
"old_part_number": "4100-CA3300-T7",
"new_part_number": "4100-CA3300-2200",
"sheet": "8211_1GPHY_48PIN",
"phase": "execute_step",
"unit": "step",
"completed_units": 1,
"state": "saved_ok",
"schematic_name": "1GPHY_8211",
"sheet_number": "8211_1GPHY_48PIN",
"job_id": "246f84be443e4ae2a55a0df40dc4899f_0",
"worker_stage_seconds": {
"starting": 0.28099999998812564,
"session_startup": 1.0,
"check_project": 0.0,
"open_project": 12.10999999998603,
"open_sheet": 2.812000000034459,
"session_ready": 0.01600000000325963,
"query_components": 0.28099999998812564,
"index_components": 2.702999999979511,
"find_components": 0.875,
"index_pins": 4.593000000022585,
"snapshot_attributes": 0.42199999996228144,
"capture": 4.094000000011874,
"before_native": 0.125,
"native_replace": 19.155999999988126,
"restore_preflight": 2.109000000025844,
"before_restore_transaction": 0.28200000000651926,
"restore_attribute_fields": 0.75,
"restore_attributes": 0.014999999984866008,
"verify_restoration": 0.14100000003236346,
"verify_attribute_fields": 0.1879999999946449,
"finished": 3.2189999999827705,
"save_and_close": 1.562000000005355,
"verify_saved_project": 0.01600000000325963,
"session_wait": 0.0
},
"elapsed_seconds": 56.79680049998569,
"units_per_minute": 1.0563975342240468
},
{
"old_part_number": "4100-CA3300-T7",
"new_part_number": "4100-CA3300-2200",
"sheet": "8211_1GPHY_48PIN",
"phase": "execute_step",
"unit": "step",
"completed_units": 1,
"state": "saved_ok",
"schematic_name": "1GPHY_8211",
"sheet_number": "8211_1GPHY_48PIN",
"job_id": "246f84be443e4ae2a55a0df40dc4899f_1",
"worker_stage_seconds": {
"check_project": 0.015000000013969839,
"open_sheet": 2.187999999965541,
"query_components": 0.4220000000204891,
"index_components": 2.9210000000020955,
"find_components": 0.6089999999967404,
"index_pins": 3.532999999995809,
"snapshot_attributes": 0.24900000003981404,
"capture": 2.85999999998603,
"before_native": 0.07800000000861473,
"native_replace": 16.264999999984866,
"restore_preflight": 1.687999999994645,
"before_restore_transaction": 0.2659999999741558,
"restore_attribute_fields": 0.6870000000053551,
"restore_attributes": 0.0,
"verify_restoration": 0.12600000001839362,
"verify_attribute_fields": 0.10899999999674037,
"finished": 1.687000000005355,
"save_and_close": 1.7039999999979045,
"verify_saved_project": 0.015000000013969839,
"open_project": 5.625,
"session_wait": 0.0
},
"elapsed_seconds": 41.16839780000737,
"units_per_minute": 1.4574285910147629
}
],
"other_phases": [
{
"phase": "prepare_queue",
"unit": "step",
"completed_units": 2,
"state": "completed",
"elapsed_seconds": 0.025570099998731166,
"units_per_minute": 4692.981255683576
},
{
"phase": "backup_project",
"unit": "operation",
"completed_units": 1,
"state": "completed",
"elapsed_seconds": 0.32834000000730157,
"units_per_minute": 182.73740634301555
},
{
"phase": "persist_progress",
"unit": "operation",
"completed_units": 1,
"state": "completed",
"job_id": "246f84be443e4ae2a55a0df40dc4899f_0",
"elapsed_seconds": 0.010178099997574463,
"units_per_minute": 5895.009875546375
},
{
"phase": "persist_progress",
"unit": "operation",
"completed_units": 1,
"state": "completed",
"job_id": "246f84be443e4ae2a55a0df40dc4899f_1",
"elapsed_seconds": 0.009127400000579655,
"units_per_minute": 6573.613514931916
},
{
"phase": "task_total",
"unit": "task",
"completed_units": 1,
"state": "completed",
"completed_steps": 2,
"saved_steps": 2,
"failed_steps": 0,
"elapsed_seconds": 100.6060615000024,
"units_per_minute": 0.5963855368694516
}
]
}
},
"multi_page": {
"steps": [
{
"sheet": [
"PON",
"block"
],
"state": "no_match",
"seconds": 16.36403070000233
},
{
"sheet": [
"PON",
"01_POWER"
],
"state": "no_match",
"seconds": 4.627093000017339
},
{
"sheet": [
"PON",
"02_ZX279133L"
],
"state": "no_match",
"seconds": 10.180998900003033
}
],
"passed": true,
"closed_between_steps": true,
"worker_starts": 1,
"completed_items": 3,
"total_items": 18,
"seconds": 34.73681229999056
},
"guards": {
"clean": {
"mode": "clean",
"closed_cleanly": true,
"passed": true
},
"edit": {
"mode": "edit",
"previous_value": "100NF/16V",
"external_edit_written": true,
"error_code": "quick_run_uncertain",
"preserved_external_state": true,
"passed": true
},
"foreign": {
"mode": "foreign",
"error_code": "quick_run_uncertain",
"preserved_external_state": true,
"passed": true
}
},
"stress": {
"current": {
"mode": "simulated_worker_with_tracemalloc",
"projects": 20,
"sheets_per_project": 5,
"rules_per_sheet": 10,
"steps": 1000,
"saved_steps": 91,
"elapsed_seconds": 41.516500700003235,
"peak_bytes": 2036758,
"steps_per_second": 24.086808453004377,
"functional_assertions_passed": true,
"time_gate_seconds": 30,
"time_gate_passed": false
},
"baseline": {
"mode": "simulated_worker_with_tracemalloc",
"projects": 20,
"sheets_per_project": 5,
"rules_per_sheet": 10,
"steps": 1000,
"saved_steps": 91,
"elapsed_seconds": 42.45326560002286,
"peak_bytes": 1992249,
"steps_per_second": 23.555313963867636,
"functional_assertions_passed": true,
"time_gate_seconds": 30,
"time_gate_passed": false
}
}
}
+19
View File
@@ -0,0 +1,19 @@
# V1.1.0 测试入口
默认 `python -m pytest -q` 仅运行 `tests/v1_1` 的功能行为测试。pytest 固定使用本仓库 src,避免与同名 dx_productivity 安装包混淆。
`tools/Test-V1.1.ps1` 是日常入口;`-Safety` 增加连接/引脚/非目标修改校验、执行互斥及应用启动回归。发布构建必须执行新测试和安全子集,失败立即停止,不继续打包。
`tools/Test-Legacy.ps1` 保留历史测试入口,`-TestPath` 可以指定某个旧模块。全量历史回归包含 subprocess/VBS/旧 UI 等耗时路径,默认开发循环不调用它。历史测试未删除,也没有被替换成伪通过。
新测试使用真实 SQLite 迁移、真实 XLSX 往返及真实计划验证,CAD/原生进程边界使用注入数据与协议桩。默认不启动 Mentor、不访问生产工程、不等待模拟的真实 150 秒无进展预算。Qt 核验设置 QT_QPA_PLATFORM=offscreen。
打包后的 `--smoke-test --data-root <临时目录>` 单独验证启动、数据存储和退出。真实中央库器件替换、保存回读和外部 Packager/ERC 验收由独立副本现场探针完成。
多工程性能回归入口:`python tools/measure_task_queue.py --output build/queue-measure-001 --projects 10 --sheets 3 --rules 4`。输出目录须为新目录,结果为 `report.json` 和 UTF-8 BOM 编码的 `timings.csv`。默认覆盖任务创建、库存、BOM、计划保存、串行执行及未勾选位号保留;`--behavior` 可选 `failure_continue`、`uncertain_stop`、`pause_resume`。此入口使用真实 SQLite、XLSX、备份、队列和日志,仅 CAD 执行器为模拟,不能用其吞吐量代表现场 CAD 替换速率。
真实多工程测量与压力回归记录见 [2026-10-15 多工程回归](2026-10-15-multi-project-regression.md)。
私有桌面正式后端的原生替换、恢复、暂停及资源释放见 [2026-10-15 私有桌面执行验证](2026-10-15-private-desktop-execution.md)。`tools/probe_private_single_step.py` 验证独立副本单步保存及故障注入后的恢复,`tools/probe_private_failures.py` 验证启动取消和 watchdog 超时后的进程/桌面释放。两者会真实启动 CAD,须单独、串行运行;普通 pytest 不启动 CAD。
1.1.2 的 `tools/probe_long_path_discovery.py` 在独立真实工程副本上强制走无 8.3 短名的兼容分支,读取长目录下的工程采集证据,检查 CAD/桌面释放、短入口清理及原证据保留;不会更改 Windows 的短文件名设置。
+2
View File
@@ -1,5 +1,7 @@
# 自动启动 DxDesigner(2026.09.06-R7)
> **V1.1.1 已更新后台执行**:当前任务中心自动执行改为显式启动私有桌面中的自有 CAD,采集、单步、批量和恢复均接入;不会复用主桌面 CAD。目标工程须关闭,其他文件可正常查看。完成与暂停会退出 CAD 并验证私有桌面释放。详见 [后台运行说明](v1.1.0-project-tasks.md)、[真实验证记录](../testing/2026-10-15-private-desktop-execution.md) 和 [1.1.1 版本说明](../releases/v1.1.1.md)。以下保留 R7 的历史启动行为,不能作为当前版本的操作说明。
> 连续队列会在原理图精简备份后自动枚举多图页工程,并逐页打开明确绑定的原理图名和页号。精简备份排除 PCB、CES、历史工程备份和运行日志。下文“只处理单页”的内容是 R7 历史边界,不再适用于当前连续队列;人工单步流程仍只操作当前活动页。
点击“开始自动替换”后,工具先从已确认的队列项读取工程路径,再执行以下准备流程:
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

+3 -1
View File
@@ -1,5 +1,7 @@
# DxPartReplace 器件批量替换
> 本文保留早期多工程任务、人工证据及 CLI 的历史说明。**当前 V1.1.x 主界面请按 [一工程一任务使用说明](v1.1.0-project-tasks.md) 操作**:通过创建弹窗选择工程,编辑位号计划,执行当前任务或顺序执行同批任务。下文早期按钮名称不代表当前界面仍提供相应入口。
本工具用于 DxDesigner 7.9.5 工程的器件批量替换。正式桌面流程在任何写入前创建并校验原理图精简备份,按“工程 → 图页 → 规则”严格串行执行;不会并发打开或同时修改多个工程。精简备份不复制 PCB、CES 日志、历史工程备份和数据库运行日志。桌面程序、人工证据流程和原批处理 CLI 是三条不同路径,工作范围和安全保障不能混用。
## 启动与诊断位置
@@ -39,7 +41,7 @@
## 人工证据流程
界面中保留的 **启动任务 / Capture Before / Capture After / Retry** 属于 `TrialRunner` 人工证据流程,不是桌面一键自动替换的第二阶段。
早期界面中的 **启动任务 / Capture Before / Capture After / Retry** 属于 `TrialRunner` 人工证据流程,当前 V1.1.x 主界面不再显示这些入口;它不是自动替换的第二阶段。
1. 启动任务并对当前项目执行 Capture Before。
2. 由操作员在 DxDesigner 中完成受控替换,不保存。
+62
View File
@@ -0,0 +1,62 @@
# DxPartReplace V1.1.2 中文使用说明
V1.1.0 沿用原有任务视图和料号规则编辑,增加按工程拆分的任务、按位号选择的替换计划及可选 Excel 操作。
[窗口 GIF 操作教程](media/v1.1.2-window-bom-tutorial.gif):创建任务、导出/导入 BOM、错误行提示、保存、顺序执行、查看结果和开始新一轮。仅含工具窗口及其弹窗,实际 CAD 等待已压缩。
## 日常流程
1. 点击“新建”,填写或选择根目录,点击“读取工程”。勾选要处理的 `.prj` 后创建任务,每个工程对应一个任务。已存在未完成任务的工程不会重复创建。
2. 在任务详情的“料号规则”页填写旧料号、新料号。新建任务只绑定一个工程;历史多工程任务仅供查看。
3. 打开“位号计划”,点击“采集所有匹配位号”。采集读取工程中的器件 UID、位号、图页、旧料号和原 Value,不保存工程。
4. 在表格中勾选需要替换的位号,其余行保持不勾选。查找框支持位号、UID、图页、料号和 Value,查找只过滤当前显示,不删除计划行。可逐行填写不同新料号、自定义 Value 和“同步 NC”,也可对可见行批量填写新料号。采集后的位号默认保留,避免误替换。
5. 点击“保存位号计划”。有未保存的编辑时无法执行;切换任务会保留编辑草稿。重新采集会核对工程身份并保留已保存计划;有未保存编辑时会提示丢弃草稿。
6. 点击“执行当前任务”只处理当前绑定工程,或点击“顺序执行本批任务”按任务顺序处理同批工程。上下移动按钮调整顺序。每次仅处理一个工程,暂停在当前步骤收尾后生效。
执行状态、失败重试和中断核验集中在底部操作区。界面不再维护当前任务的工程选择列表,避免工程范围和按钮范围混淆。
## 执行日志与修改明细
任务执行结束或暂停后,可以在“替换结果 / 日志”窗口查看修改明细。每个完成步骤按位号列出旧、新物料号,例如:`图页 MAIN:1 · 已保存并核验 · 位号 R1:4100-CA0000-T7 → 4100-CA0000-T0`;识别到 NC 并同步时另列说明。未命中、失败和保存后待核验分别显示状态,不计为成功修改。
明细来自执行器实际回读结果,不以勾选计划代替执行结果。同一工程的不同图页、规则分别保留记录;重新打开已完成任务时保留计划工作区,点击“替换结果 / 日志”按需查看。日志每页读取 200 条事件,可用“上一页日志”和“最新日志”翻页,包括保留的轮转记录;结果表最多显示当前页最近 500 条位号回读记录。详情窗口关闭后释放,重新打开读取最新页。历史版本未记录的中间步骤无法事后补全。
执行日志同时记录采集、图页枚举及队列准备、工程备份、每个“图页 × 规则”步骤、进度同步和任务合计的耗时及速率。一个步骤可能修改多个位号,步骤速率不等于器件替换速率;失败或暂停不会计为成功完成的任务。执行器的进度阶段耗时随该步骤证据保留,用于区分打开工程、原生替换、属性恢复、保存与回读的时间。任务合计包含子步骤,统计时不能重复相加。
## 可选 Excel 操作
无需导出也能完成全部编辑。读取工程创建任务后,点击“BOM 模板”会生成同批所有工程的一张表:工程名称和工程路径自动填写,每个工程预留一行,旧料号、新料号和位号留空,不要求先采集或填写规则。需要同一工程多条替换时复制该工程行;工程路径用于唯一分配任务,应保持原样。发布附件另提供通用空表;已创建任务时优先使用工具生成的本批模板。
表头批注包含中文填写说明,一行可以填写多个位号(逗号、分号、空格或顿号分隔),并填写替换开关、Value 和同步 NC。只填写工程信息的空白行会被忽略,未填写替换行的工程保留原计划。需要导出已采集的完整数据时,保存编辑后使用“导出位号计划”。
导入先核对所有工程归属,再按工程匹配位号;缺少清单时,按该工程 BOM 中的旧料号只读采集。不会执行替换。切换任务可查看、编辑各自预览,点击“保存本批位号计划”才一次写入所有受影响任务。保存失败全部回滚,预览期间不改已保存计划。工程、图页、UID、位号、旧料号及原 Value 用于身份校验,未知工程、重复器件或跨工程目标都会拒绝;不接受公式。布尔选项可使用 TRUE/FALSE 或 是/否。
BOM 首次采集或新增的位号默认“不替换”;已有计划中未列出的行保留原勾选和编辑状态,不会因后续 BOM 省略而自动停用。如果本次仅执行 BOM 列出的目标,请在预览中检查并取消其他启用行,或在 BOM 中显式填写对应的 `enabled=FALSE` 行。每个填写的位号须在当前工程清单中唯一匹配;同名位号跨图页时应填写图页或 UID。导入失败不会改变已保存计划。
“同步 NC”默认勾选,可以按行关闭;仅按原规则识别独立 `/NC` 标记。Value 复制选项和每行自定义 Value 延续原工具的处理方式。替换计划不允许旧、新料号相同,也不允许同批链式或循环替换。
## 保存、恢复及旧任务
执行前保留原工具的备份流程,替换后保存、关闭并重新打开核验。执行证据按任务存放。目标 UID、位号、原 Value 或旧料号变化时会停止校验,绝不会退回替换全部同料号器件。保存结果不确定时停止队列,先使用核验恢复入口处理。
旧数据库自动升级并保留任务、状态、规则。未采集位号计划的历史任务沿用旧流程;采集后,即使没有勾选位号,也不会触发全量替换。建议首次使用新版本前自行复制原工具的 data 文件夹;不同版本不要同时打开同一数据目录。
## 验证范围
快速测试覆盖任务拆分、SQLite 迁移、位号筛选、Excel 往返、串行调度和界面编辑;发布构建另检查执行保护及冻结程序启动。测试不会修改生产 CAD 工程。
本机 7.9.5 的真实 TypeLib 没有可直接调用的 ReplacePart 方法,生产替换仍沿用原生对话框及 Library Wins。详见 `docs/research/v1.1.0-native-interface-probe.md`。实际中央库、器件替换和保存回读仍需用工程副本现场验收。
## 后台运行与释放(1.1.1)
任务中心的自动采集、替换和中断核验恢复已默认接入私有 Windows 桌面。工具显式启动并持有自己的 CAD,通过私有桌面、会话 GUID 和活动图页窗口所属 PID 校验连接,不接管主桌面已有 CAD,也不自动退回主桌面执行。
主桌面可以继续查看其他文件。开始前仍须保存并关闭本次目标工程,运行中不要在其他软件内打开或修改同一工程;共享的许可证、CPU、磁盘和中央库资源仍会影响速度。本机不同轮次的私有 CAD 启动约 22~67 秒,也曾出现启动阻塞;1.1.2 的启动等待有 120 秒上限和取消检查,超时后收尾并保留诊断,不把增加等待上限视为已修复阻塞根因。
同一工程连续步骤复用后台会话,任务仍顺序执行。界面显示“启动后台 CAD”和“关闭 CAD 并释放后台会话”。任务完成或在步骤检查点暂停后,工具关闭自有工程、正常退出 CAD,确认进程退出,再清理自有 Job 子进程及句柄,并确认私有桌面消失。每次会话的启动、退出和清理证据单独保留在 `private-desktop-sessions` 下。
单步入口也执行备份、保存、重开核验和关闭。恢复成功会显示属性已保存并重开回读,无需用户另开后台工程手动保存。启动阶段尚未进入工程执行且清理成功时可以重试;执行超时、状态不确定或清理失败仍保留保护状态,由核验恢复入口处理。
该后端已在独立真实副本上完成替换、保存回读、暂停、恢复、启动取消及超时退出验证,详见 [验证记录](../testing/2026-10-15-private-desktop-execution.md)。1.1.1 发布包已包含此更新,详见 [版本说明](../releases/v1.1.1.md)。
1.1.2 增加执行证据长路径兼容:系统没有可用短文件名时,程序自动通过内部短目录入口访问,原任务数据、备份和日志仍在原目录;正常退出后清理入口。无需为了执行证据路径过长而先搬动工具目录。该兼容不代表旧版 CAD 支持任意长度的工程文件或中央库路径,相关路径仍受 CAD 本身限制。冻结 EXE 的长路径及 BOM 流程详见 [成品验收](../testing/2026-10-15-packaged-acceptance.md)。
+433 -31
View File
@@ -32,6 +32,10 @@ Dim QP_BatchSaveCommitted
Dim QP_DiscoveryMode, QP_TargetSchematic, QP_TargetSheet
Dim QP_FailureNumber, QP_FailureSource, QP_FailureDescription
Dim QP_NcSyncSummary
Dim QP_SessionMode, QP_SessionToken, QP_SessionProject, QP_MonitorJobId
Dim QP_OwnedProjectPath, QP_SessionWaiting, QP_SessionExternalChange
Dim QP_CheckpointSchematic, QP_CheckpointSheet
Dim QP_ProjectAccess, QP_AccessProject
Dim FailureState, CloseError
Set QP_Fso = CreateObject("Scripting.FileSystemObject")
QP_RootTemplate = "%LOCALAPPDATA%\DxProductivity\trial-task-center\quick-run"
@@ -67,6 +71,11 @@ QP_ComponentIndexContext = ""
QP_CurrentJobId = ""
QP_ExitCode = 0
QP_Stage = "session_startup"
QP_SessionMode = False
QP_OwnedProjectPath = ""
QP_SessionWaiting = False
QP_SessionExternalChange = False
QP_MonitorJobId = QP_ExpectedJobId
Set QP_App = Nothing
On Error Resume Next
@@ -86,8 +95,14 @@ Else
If QP_DiscoveryMode Then
QPDiscoverSheets
Else
QPMain
If Err.Number = 0 And QP_BatchMode Then QPFinishBatchItem
Do
QPMain
If Err.Number <> 0 Then Exit Do
If QP_BatchMode Then QPFinishBatchItem
If Err.Number <> 0 Or Not QP_SessionMode Then Exit Do
QPSessionNext
If Err.Number <> 0 Or Not QP_SessionMode Then Exit Do
Loop
End If
If Err.Number <> 0 Then
QP_FailureNumber = Err.Number
@@ -96,7 +111,7 @@ Else
If QP_DiscoveryMode Then QPCleanupDiscoveryFailure
FailureState = "hard_failure"
CloseError = ""
If QP_BatchMode Then
If QP_BatchMode Or QP_SessionMode Then
QPDiscardFailedBatchProject CloseError
If Len(CloseError) = 0 Then
If QP_BatchSaveCommitted Then
@@ -110,7 +125,7 @@ Else
QP_FailureDescription = QP_FailureDescription & "; failed project close was not verified: " & CloseError
End If
End If
WScript.StdErr.WriteLine CStr(QP_FailureSource) & ": " & CStr(QP_FailureDescription)
WScript.StdErr.WriteLine "stage=" & QP_Stage & " " & CStr(QP_FailureSource) & ": " & CStr(QP_FailureDescription)
QPFail QP_Root, FailureState, QP_FailureNumber, QP_FailureSource, QP_FailureDescription
If Len(CStr(QP_CurrentJobId)) = 0 Then
QP_ExitCode = 3
@@ -142,7 +157,15 @@ Sub QPMain()
If QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "recovery.request")) Then
If Trim(QPReadUtf8(QP_Fso.BuildPath(QP_Root, "recovery.request"))) <> QP_CurrentJobId Then _
Err.Raise vbObjectError + 864, "QuickPartReplace.Recovery", "recovery job mismatch"
If Len(CStr(CreateObject("WScript.Shell").Environment("PROCESS")("DXPART_DESKTOP"))) > 0 Then QP_BatchMode = True
QPRecoverSavedJob Command, SnapshotPath
If QP_BatchMode Then
If QP_BatchState = "restored_ok" Then
QPFinishBatchItem
Else
QP_BatchMode = False
End If
End If
QPProgress "finished", 1, 1
Exit Sub
End If
@@ -173,17 +196,20 @@ Sub QPBootstrapSession()
Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "sheet discovery authorization does not match this job"
QP_DiscoveryMode = True
End If
QPReadSessionRequest
QPProgress "session_startup", 0, 0
TargetPath = QPConfirmedProjectPath()
If QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "recovery.request")) Then
If QPDesignerProcessCount() <> 0 Then _
If Len(CStr(CreateObject("WScript.Shell").Environment("PROCESS")("DXPART_DESKTOP"))) = 0 And QPDesignerProcessCount() <> 0 Then _
Err.Raise vbObjectError + 864, "QuickPartReplace.Recovery", _
"recovery requires a fresh CAD session; close existing DxDesigner first without discarding wanted edits"
If Len(CStr(CreateObject("WScript.Shell").Environment("PROCESS")("DXPART_DESKTOP"))) > 0 Then QP_BatchMode = True
End If
If Len(TargetPath) = 0 Then
Set QP_App = GetObject(, "Viewdraw.Application")
Set QP_App = QPAttachOrStart(QPDesignerProcessCount())
Else
Set QP_App = QPAttachOrStart(QPDesignerProcessCount())
If QP_SessionMode Then WScript.ConnectObject QP_App, "QPEvent_"
QPEnsureProject QP_App, TargetPath
End If
QP_Stage = "session_ready"
@@ -193,7 +219,9 @@ End Sub
Sub QPCleanupDiscoveryFailure()
On Error Resume Next
If QP_OwnedProject And Not QP_App Is Nothing Then QP_App.CloseProject
If QP_OwnedProject And Not QP_App Is Nothing Then
If QPCanonicalPath(QPProjectPath()) = QPCanonicalPath(QP_OwnedProjectPath) Then QP_App.CloseProject
End If
QP_OwnedProject = False
Err.Clear
On Error GoTo 0
@@ -220,15 +248,21 @@ Sub QPWaitForMonitor()
End Sub
Sub QPProgress(ByVal Stage, ByVal Done, ByVal Total)
Dim Safe, StopPath
Dim Safe, StopPath, Job, Suffix
If Len(CStr(QP_AttemptToken)) = 0 Then Exit Sub
Safe = 0
If Not CBool(QP_NativeMutationPossible) And Not CBool(QP_RestoreTransactionOpen) And _
Not CBool(QP_NativeCallActive) Then Safe = 1
QP_ProgressSequence = CLng(QP_ProgressSequence) + 1
Job = QP_ExpectedJobId
Suffix = ""
If QP_SessionMode Then
Job = QP_MonitorJobId
Suffix = vbTab & QP_ExpectedJobId
End If
WScript.StdOut.WriteLine "DX_PROGRESS" & vbTab & QP_AttemptToken & vbTab & _
QP_ExpectedJobId & vbTab & CStr(QP_ProgressSequence) & vbTab & Stage & _
vbTab & CStr(Done) & vbTab & CStr(Total) & vbTab & CStr(Safe)
Job & vbTab & CStr(QP_ProgressSequence) & vbTab & Stage & _
vbTab & CStr(Done) & vbTab & CStr(Total) & vbTab & CStr(Safe) & Suffix
If Safe = 1 And Stage <> "finished" Then
StopPath = QP_Fso.BuildPath(QP_Root, "monitor-" & QP_AttemptToken & ".stop")
If QP_Fso.FileExists(StopPath) Then
@@ -239,6 +273,111 @@ Sub QPProgress(ByVal Stage, ByVal Done, ByVal Total)
End If
End Sub
Sub QPReadSessionRequest()
Dim Path, Fields, Index, Character
Path = QP_Fso.BuildPath(QP_Root, "project-session.request")
If Not QP_Fso.FileExists(Path) Then Exit Sub
If Not QP_BatchMode Or QP_DiscoveryMode Or _
QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "recovery.request")) Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "invalid project session mode"
Fields = Split(Trim(QPReadUtf8(Path)), vbTab)
If UBound(Fields) <> 2 Then Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "invalid session request"
QP_SessionToken = CStr(Fields(0))
If Len(QP_SessionToken) <> 32 Or Fields(2) <> QP_ExpectedJobId Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "session authorization mismatch"
For Index = 1 To 32
Character = Mid(QP_SessionToken, Index, 1)
If InStr(1, "0123456789abcdef", Character, vbBinaryCompare) = 0 Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "invalid session token"
Next
QP_SessionProject = CStr(Fields(1))
If QPCanonicalPath(QPConfirmedProjectPath()) <> QPCanonicalPath(QP_SessionProject) Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "session project mismatch"
QP_SessionMode = True
End Sub
Sub QPSessionNext()
Dim Path, Fields, Attempt, TargetPath, Documents, Document, View
Path = QP_Fso.BuildPath(QP_Root, "project-session-next.tsv")
QPProgress "session_wait", 1, 1
For Attempt = 1 To 1500
If QP_Fso.FileExists(Path) Then
Fields = Split(Trim(QPReadContinuation(Path)), vbTab)
If UBound(Fields) <> 1 Then Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "invalid continuation"
If Fields(0) <> QP_SessionToken Then Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "continuation token mismatch"
QP_Fso.DeleteFile Path, True
QPRequireSessionCheckpoint
QP_SessionWaiting = False
If Fields(1) = "close" Then
QPCloseBatchProject QP_SessionProject, False
QP_SessionMode = False
Exit Sub
End If
QP_ExpectedJobId = CStr(Fields(1))
QP_CurrentJobId = QP_ExpectedJobId
QP_BatchMode = True
QP_BatchState = ""
QP_BatchSaveCommitted = False
QP_NativeMutationPossible = False
If Trim(QPReadUtf8(QP_Fso.BuildPath(QP_Root, "batch.request"))) <> QP_ExpectedJobId Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "next batch authorization mismatch"
TargetPath = QPConfirmedProjectPath()
If QPCanonicalPath(TargetPath) <> QPCanonicalPath(QP_SessionProject) Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "cannot switch project inside a session"
Set View = QP_App.ActiveView
If Not View Is Nothing Then
If CStr(View.GetName(0)) <> QP_TargetSchematic Or CStr(View.Block.SheetNum) <> QP_TargetSheet Then
Set Documents = QP_App.SchematicSheetDocuments()
If Documents.Count <> 1 Then Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "owned sheet set changed"
Set Document = Documents.Item(1)
Document.Close False, ""
End If
End If
QPEnsureProject QP_App, TargetPath
Exit Sub
End If
WScript.Sleep 100
Next
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "supervisor did not release project checkpoint"
End Sub
Sub QPEvent_DocumentModified()
If QP_SessionWaiting Then QP_SessionExternalChange = True
End Sub
Sub QPEvent_BlockModified(ByVal Block)
If QP_SessionWaiting Then QP_SessionExternalChange = True
End Sub
Sub QPEvent_ProjectModified(ByVal NewProject)
If QP_SessionWaiting Then QP_SessionExternalChange = True
End Sub
Sub QPEvent_BeforeProjectModified()
If QP_SessionWaiting Then QP_SessionExternalChange = True
End Sub
Sub QPEvent_SourceFileModified(ByVal FileName)
If QP_SessionWaiting Then QP_SessionExternalChange = True
End Sub
Sub QPRequireSessionCheckpoint()
Dim Documents, View
If Not QP_OwnedProject Or Len(QP_OwnedProjectPath) = 0 Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "session project ownership was lost"
If QPCanonicalPath(QPProjectPath()) <> QPCanonicalPath(QP_OwnedProjectPath) Or _
QPCanonicalPath(QP_OwnedProjectPath) <> QPCanonicalPath(QP_SessionProject) Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "active project changed; no automatic save or close"
If QP_SessionExternalChange Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "project modified outside worker at checkpoint; no automatic save or close"
Set Documents = QP_App.SchematicSheetDocuments()
Set View = QP_App.ActiveView
If Documents.Count <> 1 Or View Is Nothing Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "owned sheet set changed at checkpoint"
If CStr(View.GetName(0)) <> QP_CheckpointSchematic Or CStr(View.Block.SheetNum) <> QP_CheckpointSheet Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "active sheet changed at checkpoint"
End Sub
Sub QPInvalidatePinIndex()
Set QP_PinIndex = Nothing
QP_PinContext = ""
@@ -382,6 +521,7 @@ Function QPConfirmedProjectPath()
Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "confirmed sheet columns are incomplete"
If (Len(QP_TargetSchematic) = 0) <> (Len(QP_TargetSheet) = 0) Then _
Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "confirmed sheet identity is incomplete"
TargetPath = QPProjectAccessPath(TargetPath)
If Not QP_Fso.FileExists(TargetPath) Then _
Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "confirmed project file does not exist: " & TargetPath
If LCase(QP_Fso.GetExtensionName(TargetPath)) <> "prj" Then _
@@ -405,7 +545,24 @@ Function QPTryAttach()
End Function
Function QPAttachOrStart(ByVal ProcessCount)
Dim App, Attempt
Dim App, Attempt, Environment, PrivateDesktop, ExpectedGuid
Set Environment = CreateObject("WScript.Shell").Environment("PROCESS")
PrivateDesktop = CStr(Environment("DXPART_DESKTOP"))
ExpectedGuid = CStr(Environment("DXPART_CAD_GUID"))
If Len(PrivateDesktop) = 0 And (Len(ExpectedGuid) > 0 Or Len(CStr(Environment("DXPART_CAD_PID"))) > 0 Or _
Len(CStr(Environment("DXPART_SESSION_TOKEN"))) > 0) Then _
Err.Raise vbObjectError + 874, "QuickPartReplace.PrivateDesktop", "incomplete private CAD identity"
If Len(PrivateDesktop) > 0 Then
If Len(ExpectedGuid) = 0 Or Len(CStr(Environment("DXPART_CAD_PID"))) = 0 Or _
Len(CStr(Environment("DXPART_SESSION_TOKEN"))) <> 32 Then _
Err.Raise vbObjectError + 874, "QuickPartReplace.PrivateDesktop", "incomplete private CAD identity"
Set App = QPTryAttach()
If App Is Nothing Then Err.Raise vbObjectError + 874, "QuickPartReplace.PrivateDesktop", "owned private CAD is unavailable"
If LCase(CStr(App.Guid())) <> LCase(ExpectedGuid) Then _
Err.Raise vbObjectError + 874, "QuickPartReplace.PrivateDesktop", "private CAD GUID mismatch; no project was changed"
Set QPAttachOrStart = App
Exit Function
End If
If ProcessCount > 1 Then _
Err.Raise vbObjectError + 851, "QuickPartReplace.Session", "multiple DxDesigner instances; no project was changed"
Set App = QPTryAttach()
@@ -413,6 +570,7 @@ Function QPAttachOrStart(ByVal ProcessCount)
If ProcessCount = 0 Then
QP_Stage = "launch_designer"
QPLog QP_Root, "INFO", "stage=launch_designer method=COM"
QPProgress "launch_designer", 0, 1
Set App = CreateObject("Viewdraw.Application")
App.Visible = True
Else
@@ -433,15 +591,17 @@ End Function
Sub QPEnsureProject(ByRef App, ByVal TargetPath)
Dim ProjectData, CurrentPath, Opened, View, Documents
Dim Schematics, Schematic, Sheets, Sheet, SheetCount, OnlySchematic, OnlySheet, Document
TargetPath = QPProjectAccessPath(TargetPath)
If Not QP_Fso.FileExists(TargetPath) Then _
Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "confirmed project file does not exist: " & TargetPath
QP_Stage = "check_project"
QPLog QP_Root, "INFO", "stage=check_project target=" & QPLogField(TargetPath)
QPProgress "check_project", 0, 1
Set ProjectData = App.GetProjectData()
CurrentPath = ""
If Not ProjectData Is Nothing Then CurrentPath = CStr(ProjectData.GetProjectFilePath())
If Len(Trim(CurrentPath)) > 0 Then
If QP_BatchMode Then Err.Raise vbObjectError + 870, "QuickPartReplace.Batch", _
If QP_BatchMode And Not (QP_SessionMode And QP_OwnedProject) Then Err.Raise vbObjectError + 870, "QuickPartReplace.Batch", _
"batch cannot take over an already open project; save your wanted edits and close the project before starting the queue"
If QPCanonicalPath(CurrentPath) <> QPCanonicalPath(TargetPath) Then _
Err.Raise vbObjectError + 853, "QuickPartReplace.Session", _
@@ -449,9 +609,11 @@ Sub QPEnsureProject(ByRef App, ByVal TargetPath)
Else
QP_Stage = "open_project"
QPLog QP_Root, "INFO", "stage=open_project target=" & QPLogField(TargetPath)
QPProgress "open_project", 0, 1
Opened = App.OpenProject(CStr(TargetPath))
If Not Opened Then Err.Raise vbObjectError + 854, "QuickPartReplace.Session", "DxDesigner refused to open the target project"
QP_OwnedProject = True
QP_OwnedProjectPath = TargetPath
End If
Set ProjectData = App.GetProjectData()
If ProjectData Is Nothing Then _
@@ -460,6 +622,7 @@ Sub QPEnsureProject(ByRef App, ByVal TargetPath)
Err.Raise vbObjectError + 854, "QuickPartReplace.Session", "opened project does not match the confirmed target"
If QP_DiscoveryMode Then Exit Sub
QP_Stage = "open_sheet"
QPProgress "open_sheet", 0, 1
Set View = App.ActiveView
If Not View Is Nothing And Not QP_BatchMode Then Exit Sub
Set Documents = App.SchematicSheetDocuments()
@@ -496,6 +659,7 @@ Sub QPDiscoverSheets()
Dim Documents, Schematics, Schematic, Sheets, Sheet, Text, Count
If Not QP_DiscoveryMode Or Not QP_OwnedProject Then _
Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "sheet discovery does not own the project"
QP_Stage = "discovery_enumerate_sheets"
Set Documents = QP_App.SchematicSheetDocuments()
Set Schematics = Documents.GetAvailableSchematics()
Text = "project_path" & vbTab & "schematic_name" & vbTab & "sheet_number" & vbCrLf
@@ -514,6 +678,7 @@ Sub QPDiscoverSheets()
QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "sheets.tsv"), Text
If QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "inventory-request.tsv")) Then _
QPDiscoverInventory Documents
QP_Stage = "discovery_close_project"
QP_App.CloseProject
If Len(CStr(QP_App.GetProjectData().GetProjectFilePath())) > 0 Then _
Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "project did not close after sheet discovery"
@@ -523,15 +688,20 @@ End Sub
Sub QPDiscoverInventory(ByRef Documents)
Dim Requested, Schematics, Schematic, Sheets, Sheet, Document, View
Dim Components, Comp, PartAttr, PartNumber, PartKey, HitKey, Seen, Text, Count
Dim Components, Comp, PartAttr, ValueAttr, PartNumber, PartKey, HitKey, Seen, Text, Count
Dim ComponentText, ValueText, ComponentMode
Set Requested = QPReadInventoryRequest()
Set Seen = CreateObject("Scripting.Dictionary")
Text = "project_path" & vbTab & "schematic_name" & vbTab & "sheet_number" & vbTab & "old_part" & vbCrLf
ComponentMode = QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "component-inventory.request"))
ComponentText = "project_path" & vbTab & "schematic_name" & vbTab & "sheet_number" & vbTab & _
"uid" & vbTab & "refdes" & vbTab & "old_part" & vbTab & "old_value" & vbCrLf
Count = 0
Set Schematics = Documents.GetAvailableSchematics()
For Each Schematic In Schematics
Set Sheets = Documents.GetAvailableSheets(CStr(Schematic))
For Each Sheet In Sheets
QP_Stage = "inventory_open_sheet " & CStr(Schematic) & ":" & CStr(Sheet)
Set Document = Documents.Open(CStr(Schematic), CStr(Sheet))
If Document Is Nothing Then Err.Raise vbObjectError + 872, _
"QuickPartReplace.Discovery", "inventory sheet could not be opened"
@@ -541,13 +711,26 @@ Sub QPDiscoverInventory(ByRef Documents)
"QuickPartReplace.Discovery", "inventory sheet did not become active"
If CStr(View.GetName(0)) <> CStr(Schematic) Or CStr(View.Block.SheetNum) <> CStr(Sheet) Then _
Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "inventory sheet identity changed"
QP_Stage = "inventory_query " & CStr(Schematic) & ":" & CStr(Sheet)
Set Components = View.Query(VDM_COMP, VD_ALL)
For Each Comp In Components
QP_Stage = "inventory_read_component " & CStr(Schematic) & ":" & CStr(Sheet)
PartNumber = ""
Set PartAttr = QPFindCurrentAttribute(Comp, "Part Number")
If Not PartAttr Is Nothing Then PartNumber = QPEffectiveAttributeValue(PartAttr)
PartKey = LCase(CStr(PartNumber))
If Requested.Exists(PartKey) Then
If ComponentMode Then
ValueText = ""
Set ValueAttr = QPFindCurrentAttribute(Comp, "Value")
If Not ValueAttr Is Nothing Then ValueText = QPEffectiveAttributeValue(ValueAttr)
If Len(CStr(Comp.UID)) = 0 Or Len(CStr(Comp.Refdes)) = 0 Then _
Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "component identity is incomplete"
ComponentText = ComponentText & QPEncode(QPProjectPath()) & vbTab & _
QPEncode(CStr(Schematic)) & vbTab & QPEncode(CStr(Sheet)) & vbTab & _
QPEncode(CStr(Comp.UID)) & vbTab & QPEncode(CStr(Comp.Refdes)) & vbTab & _
QPEncode(CStr(PartNumber)) & vbTab & QPEncode(CStr(ValueText)) & vbCrLf
End If
HitKey = QPSheetKey(Schematic, Sheet) & Chr(30) & PartKey
If Not Seen.Exists(HitKey) Then
Seen.Add HitKey, True
@@ -557,12 +740,14 @@ Sub QPDiscoverInventory(ByRef Documents)
End If
End If
Next
QP_Stage = "inventory_close_sheet " & CStr(Schematic) & ":" & CStr(Sheet)
Document.Close False, ""
Count = Count + 1
QPProgress "inventory_sheets", Count, 0
Next
Next
QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "inventory.tsv"), Text
If ComponentMode Then QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "components.tsv"), ComponentText
End Sub
Function QPReadInventoryRequest()
@@ -658,7 +843,9 @@ End Sub
Sub QPCloseBatchProject(ByVal ExpectedPath, ByVal SaveChanges)
Dim Documents, Document
If Not QP_OwnedProject Or QP_RestoreTransactionOpen Then _
Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "project ownership or restoration transaction is not safe to close"
Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "project ownership or restoration transaction is not safe to close"
If QPCanonicalPath(ExpectedPath) <> QPCanonicalPath(QP_OwnedProjectPath) Or QP_SessionExternalChange Then _
Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "owned project changed; no automatic close"
If QPCanonicalPath(QPProjectPath()) <> QPCanonicalPath(ExpectedPath) Then _
Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "active project changed before save and close"
Set Documents = QP_App.SchematicSheetDocuments()
@@ -672,6 +859,7 @@ Sub QPCloseBatchProject(ByVal ExpectedPath, ByVal SaveChanges)
If Len(CStr(QP_App.GetProjectData().GetProjectFilePath())) > 0 Then _
Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "project did not close; queue stopped"
QP_OwnedProject = False
QP_OwnedProjectPath = ""
QPInvalidatePinIndex
QPInvalidateComponentIndex
End Sub
@@ -679,9 +867,9 @@ End Sub
Sub QPDiscardFailedBatchProject(ByRef ErrorDescription)
Dim ErrorNumber, ErrorSource, Description
ErrorDescription = ""
If Not QP_BatchMode Or Not QP_OwnedProject Or QP_App Is Nothing Then Exit Sub
If (Not QP_BatchMode And Not QP_SessionMode) Or Not QP_OwnedProject Or QP_App Is Nothing Then Exit Sub
On Error Resume Next
QPCloseBatchProject QPProjectPath(), False
QPCloseBatchProject QP_OwnedProjectPath, False
ErrorNumber = Err.Number
ErrorSource = Err.Source
Description = Err.Description
@@ -711,6 +899,7 @@ Sub QPFinishBatchItem()
SnapshotPath = QPJobSnapshotPath(QP_CurrentJobId)
QPRequireCommandSnapshot Command, SnapshotPath
Set Records = QPReadSnapshot(SnapshotPath)
QPVerifyUntouched Records
Set ValueStates = CreateObject("Scripting.Dictionary")
For Index = 0 To Records.Item("components").Count - 1
Set Record = Records.Item("components").Item(CStr(Index))
@@ -720,12 +909,15 @@ Sub QPFinishBatchItem()
ValueStates.Item(CStr(Index)).Add "custom_value", QPCustomValue(Command)
Next
End If
QPCloseBatchProject TargetPath, True
QP_BatchSaveCommitted = True
If FinalState = "restored_ok" Or Not QP_SessionMode Then
QPCloseBatchProject TargetPath, True
QP_BatchSaveCommitted = True
End If
If FinalState = "restored_ok" Then
QPProgress "verify_saved_project", 0, 1
QPEnsureProject QP_App, TargetPath
QPRequireCommandSnapshot Command, SnapshotPath
QPVerifyUntouched Records
Set Plans = CreateObject("Scripting.Dictionary")
For Index = 0 To Records.Item("components").Count - 1
Set Record = Records.Item("components").Item(CStr(Index))
@@ -735,12 +927,29 @@ Sub QPFinishBatchItem()
Plans.Add CStr(Index), Candidate
Next
QPVerifyRestoredPlans Command, Records, Plans, ValueStates
QPCloseBatchProject TargetPath, True
If Not QP_SessionMode Then QPCloseBatchProject TargetPath, True
FinalState = "saved_ok"
QP_BatchMessage = QP_BatchMessage & " Saved, reopened for readback, and closed."
If QP_SessionMode Then
QP_BatchMessage = QP_BatchMessage & " Saved and reopened for readback; owned project checkpoint verified."
Else
QP_BatchMessage = QP_BatchMessage & " Saved, reopened for readback, and closed."
End If
End If
QP_BatchMode = False
QPWriteStatus QP_Root, QP_CurrentJobId, FinalState, "batch_closed", QP_BatchMessage
If QP_SessionMode Then
QP_NativeMutationPossible = False
QP_SessionExternalChange = False
QP_CheckpointSchematic = QP_TargetSchematic
QP_CheckpointSheet = QP_TargetSheet
QP_SessionWaiting = True
QPWriteStatus QP_Root, QP_CurrentJobId, FinalState, "session_verified", QP_BatchMessage
QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "project-session-result.tsv"), _
QP_SessionToken & vbTab & QP_CurrentJobId & vbTab & FinalState & vbTab & "session_verified"
ElseIf QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "recovery.request")) Then
QPWriteStatus QP_Root, QP_CurrentJobId, "restored_ok", "recovery_saved_verified", QP_BatchMessage
Else
QPWriteStatus QP_Root, QP_CurrentJobId, FinalState, "batch_closed", QP_BatchMessage
End If
QPProgress "finished", 1, 1
End Sub
@@ -794,6 +1003,7 @@ Sub QPNativeReplace(ByRef Command, ByVal SnapshotPath)
QP_NativeCallActive = True
QPProgress "native_replace", 0, 1
ExitCode = Shell.Run(CommandLine, 0, True)
QPLog QP_Root, "INFO", "native_helper_exit code=" & CStr(ExitCode)
QP_NativeMutationPossible = QPNativeReportShowsMutation(SnapshotPath & ".native.json")
QP_NativeCallActive = False
QPInvalidatePinIndex
@@ -808,7 +1018,7 @@ Sub QPNativeReplace(ByRef Command, ByVal SnapshotPath)
"; report: " & SnapshotPath & ".native.json"
Else
Err.Raise vbObjectError + 839, "QuickPartReplace", _
"automatic native replacement failed; see " & SnapshotPath & ".native.json"
"automatic native replacement failed (exit=" & CStr(ExitCode) & "); see " & SnapshotPath & ".native.json"
End If
End If
End Sub
@@ -848,8 +1058,10 @@ Sub QPRollbackNativeReplacement(ByVal SnapshotPath)
Lines = Split(QPReadUtf8(SnapshotPath), vbLf)
Expected = ""
For LineIndex = 1 To UBound(Lines)
If Len(Replace(Lines(LineIndex), vbCr, "")) > 0 Then _
Expected = Expected & Replace(Lines(LineIndex), vbCr, "") & vbCrLf
If Len(Replace(Lines(LineIndex), vbCr, "")) > 0 Then
If Left(CStr(Lines(LineIndex)), 2) <> "U" & vbTab Then _
Expected = Expected & Replace(Lines(LineIndex), vbCr, "") & vbCrLf
End If
Next
Actual = ""
For Index = 0 To Records.Item("components").Count - 1
@@ -858,6 +1070,7 @@ Sub QPRollbackNativeReplacement(ByVal SnapshotPath)
Actual = Actual & QPSnapshotComponent(Candidate)
QPProgress "verify_native_rollback", Index + 1, Records.Item("components").Count
Next
QPVerifyUntouched Records
If Actual <> Expected Then Err.Raise vbObjectError + 842, _
"QuickPartReplace", "native undo does not match the original snapshot"
QPWriteUtf8 SnapshotPath & ".native.rolled-back", _
@@ -874,6 +1087,7 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath)
Dim PartAttr
Dim Snapshot
Dim Index
Dim Selectors, Selector, Uid, ValueAttr, ValueText
If StrComp(CStr(Command("old_part_number")), CStr(Command("new_part_number")), vbTextCompare) = 0 Then _
Err.Raise vbObjectError + 829, "QuickPartReplace", "source and target must differ"
@@ -884,17 +1098,35 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath)
QPLog QP_Root, "INFO", "stage=query_components"
Set Components = QP_App.ActiveView.Query(VDM_COMP, VD_ALL)
QPBuildComponentIndex Components
Set Selectors = QPCommandTargets(Command)
For Each Comp In Components
PartNumber = ""
Set PartAttr = QPFindCurrentAttribute(Comp, "Part Number")
If Not PartAttr Is Nothing Then PartNumber = QPEffectiveAttributeValue(PartAttr)
If StrComp(PartNumber, CStr(Command("old_part_number")), _
vbTextCompare) = 0 Then
Uid = CStr(Comp.UID)
If Selectors Is Nothing Then
If StrComp(PartNumber, CStr(Command("old_part_number")), _
vbTextCompare) = 0 Then Matches.Add CStr(Matches.Count), Comp
ElseIf Selectors.Exists(Uid) Then
Selector = Selectors.Item(Uid)
ValueText = ""
Set ValueAttr = QPFindCurrentAttribute(Comp, "Value")
If Not ValueAttr Is Nothing Then ValueText = QPEffectiveAttributeValue(ValueAttr)
If CStr(Comp.Refdes) <> CStr(Selector(0)) Or _
StrComp(PartNumber, CStr(Command("old_part_number")), vbTextCompare) <> 0 Or _
ValueText <> CStr(Selector(1)) Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "selected component changed since inventory"
Matches.Add CStr(Matches.Count), Comp
End If
QPProgress "find_components", Matches.Count, 0
Next
If Not Selectors Is Nothing Then
If Matches.Count <> Selectors.Count Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "selected component is missing"
End If
If Matches.Count = 0 Then
If Not Selectors Is Nothing Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "target scope is empty"
QPWriteStatus QP_Root, CStr(Command("job_id")), "no_match", "", _
"No components match old Part Number on the current sheet; no replacement was performed. " & _
"Project=" & QPProjectPath() & "; sheet=" & QPSheetIdentity() & "; old_part=" & CStr(Command("old_part_number"))
@@ -911,6 +1143,8 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath)
Snapshot = Snapshot & vbTab & QPEncode(QPValueMode(Command)) & _
vbTab & QPEncode(QPCustomValue(Command)) & vbTab & _
QPEncode(QPBooleanText(QPSyncNc(Command)))
If Not Selectors Is Nothing Then _
Snapshot = Snapshot & vbTab & QPEncode("targets") & vbTab & CStr(Command("target_selectors"))
Snapshot = Snapshot & vbCrLf
For Index = 0 To Matches.Count - 1
Set Comp = Matches.Item(CStr(Index))
@@ -918,6 +1152,12 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath)
Snapshot = Snapshot & QPSnapshotComponent(Comp)
QPProgress "capture", Index + 1, Matches.Count
Next
If Not Selectors Is Nothing Then
For Each Comp In Components
If Not Selectors.Exists(CStr(Comp.UID)) Then _
Snapshot = Snapshot & QPUntouchedComponent(Comp)
Next
End If
QPWriteUtf8 SnapshotPath, Snapshot
For Each Comp In Components
@@ -933,6 +1173,77 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath)
QPLog QP_Root, "INFO", "awaiting_native_replace count=" & Matches.Count
End Sub
Function QPUntouchedComponent(ByRef Comp)
QPUntouchedComponent = "U" & vbTab & QPEncode(CStr(Comp.UID)) & vbTab & _
QPEncode(CStr(Comp.Refdes)) & vbTab & QPEncode(QPEffectiveComponentAttribute(Comp, "Part Number")) & vbTab & _
QPEncode(QPEffectiveComponentAttribute(Comp, "Value")) & vbTab & _
QPEncode(QPEffectiveComponentAttribute(Comp, "Part Name")) & vbTab & _
QPEncode(QPEffectiveComponentAttribute(Comp, "Part Label")) & vbCrLf
End Function
Function QPEffectiveComponentAttribute(ByRef Comp, ByVal Name)
Dim Attr
QPEffectiveComponentAttribute = ""
Set Attr = QPFindCurrentAttribute(Comp, Name)
If Not Attr Is Nothing Then QPEffectiveComponentAttribute = QPEffectiveAttributeValue(Attr)
End Function
Sub QPVerifyUntouched(ByRef Records)
Dim Baseline, Components, Comp, Uid, Actual, Matched, Total, Seen
If Not Records.Item("meta").Exists("target_scope") Then Exit Sub
Set Baseline = Records.Item("untouched")
Set Components = QP_App.ActiveView.Query(VDM_COMP, VD_ALL)
Matched = 0
Total = 0
Set Seen = CreateObject("Scripting.Dictionary")
For Each Comp In Components
Total = Total + 1
Uid = CStr(Comp.UID)
If Seen.Exists(Uid) Then Err.Raise vbObjectError + 874, _
"QuickPartReplace.Target", "duplicate component UID"
Seen.Add Uid, True
If Baseline.Exists(Uid) Then
Matched = Matched + 1
Actual = Replace(QPUntouchedComponent(Comp), vbCrLf, "")
If Actual <> CStr(Baseline.Item(Uid)) Then _
Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "unselected component changed"
End If
Next
If Total <> Baseline.Count + Records.Item("components").Count Then _
Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "component count changed outside selected targets"
If Matched <> Baseline.Count Then Err.Raise vbObjectError + 874, _
"QuickPartReplace.Target", "unselected component is missing"
End Sub
Function QPCommandTargets(ByRef Command)
Dim Scope, Text, Entries, Entry, Fields, Result, Index
Set QPCommandTargets = Nothing
If Not Command.Exists("target_scope") Then Exit Function
Scope = CStr(Command("target_scope"))
If Scope = "all" Then
If Len(CStr(Command("target_selectors"))) <> 0 Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "all-match scope has selectors"
Exit Function
End If
If Scope <> "targets" Then Err.Raise vbObjectError + 873, _
"QuickPartReplace.Target", "target scope is invalid"
Text = QPDecode(CStr(Command("target_selectors")))
If Len(Text) = 0 Then Err.Raise vbObjectError + 873, _
"QuickPartReplace.Target", "target scope is empty"
Set Result = CreateObject("Scripting.Dictionary")
Entries = Split(Text, Chr(30))
For Index = 0 To UBound(Entries)
Fields = Split(Entries(Index), Chr(31))
If UBound(Fields) <> 2 Or Len(CStr(Fields(0))) = 0 Or _
Len(CStr(Fields(1))) = 0 Then Err.Raise vbObjectError + 873, _
"QuickPartReplace.Target", "target selector is malformed"
If Result.Exists(CStr(Fields(0))) Then Err.Raise vbObjectError + 873, _
"QuickPartReplace.Target", "duplicate target UID"
Result.Add CStr(Fields(0)), Array(CStr(Fields(1)), CStr(Fields(2)))
Next
Set QPCommandTargets = Result
End Function
Function QPSnapshotComponent(ByRef Comp)
Dim AttributeCount
Dim Point
@@ -1086,6 +1397,8 @@ Sub QPRestoreAfterOperatorReplace(ByRef Command, ByVal SnapshotPath)
QP_NcSyncSummary = ""
QPProgress "restore_preflight", 0, 0
Set Records = QPReadSnapshot(SnapshotPath)
QPRequireCommandSnapshot Command, SnapshotPath
QPVerifyUntouched Records
Set Meta = Records.Item("meta")
If QPCanonicalPath(CStr(Meta("project_path"))) <> QPCanonicalPath(QPProjectPath()) Or _
CStr(Meta("sheet_name")) <> QPSheetIdentity() Then _
@@ -1232,6 +1545,7 @@ Sub QPRecoverSavedJob(ByRef Command, ByVal SnapshotPath)
Dim OldCount, NewCount, ErrorNumber, ErrorDescription, RecoveryDocuments, RecoveryDocument, RecoveryProjectData
QPRequireCommandSnapshot Command, SnapshotPath
Set Records = QPReadSnapshot(SnapshotPath)
QPVerifyUntouched Records
Set Plans = CreateObject("Scripting.Dictionary")
Set Used = CreateObject("Scripting.Dictionary")
Set ValueStates = CreateObject("Scripting.Dictionary")
@@ -1700,6 +2014,19 @@ Sub QPRequireCommandSnapshot(ByRef Command, ByVal SnapshotPath)
If QPCustomValue(Meta) <> QPCustomValue(Command) Or _
QPSyncNc(Meta) <> QPSyncNc(Command) Then _
Err.Raise vbObjectError + 842, "QuickPartReplace", "snapshot Value or NC option mismatch"
If Command.Exists("target_scope") Then
If CStr(Command("target_scope")) = "targets" Then
If Not Meta.Exists("target_scope") Then Err.Raise vbObjectError + 873, _
"QuickPartReplace.Target", "target selector missing from snapshot"
If CStr(Meta("target_scope")) <> "targets" Or _
CStr(Meta("target_selectors")) <> CStr(Command("target_selectors")) Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "target selector changed since snapshot"
ElseIf Meta.Exists("target_scope") Then
Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "snapshot scope changed"
End If
ElseIf Meta.Exists("target_scope") Then
Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "target scope missing from command"
End If
End Sub
Function QPValueMode(ByRef Record)
@@ -2175,7 +2502,7 @@ Function QPProjectPath()
If Len(Trim(ProjectPath)) = 0 Then
Err.Raise vbObjectError + 827, "QuickPartReplace", "no active project"
End If
QPProjectPath = ProjectPath
QPProjectPath = QPCanonicalPath(ProjectPath)
End Function
Function QPSheetIdentity()
@@ -2362,6 +2689,7 @@ Function QPReadSnapshot(ByVal Path)
Dim Result
Dim Components
Dim Attributes
Dim Untouched
Dim Fields
Dim Index
Dim Record
@@ -2370,13 +2698,14 @@ Function QPReadSnapshot(ByVal Path)
Set Result = CreateObject("Scripting.Dictionary")
Set Components = CreateObject("Scripting.Dictionary")
Set Attributes = CreateObject("Scripting.Dictionary")
Set Untouched = CreateObject("Scripting.Dictionary")
Lines = Split(QPReadUtf8(Path), vbLf)
For Index = 0 To UBound(Lines)
If Len(Replace(Lines(Index), vbCr, "")) > 0 Then
Fields = Split(Replace(Lines(Index), vbCr, ""), vbTab)
Select Case Fields(0)
Case "M"
If UBound(Fields) <> 4 And UBound(Fields) <> 5 And UBound(Fields) <> 7 Then Err.Raise vbObjectError + 812, _
If UBound(Fields) <> 4 And UBound(Fields) <> 5 And UBound(Fields) <> 7 And UBound(Fields) <> 9 Then Err.Raise vbObjectError + 812, _
"QuickPartReplace", "invalid snapshot meta"
Set Meta = CreateObject("Scripting.Dictionary")
Meta.Add "project_path", QPDecode(Fields(1))
@@ -2384,11 +2713,15 @@ Function QPReadSnapshot(ByVal Path)
Meta.Add "new_part_number", QPDecode(Fields(3))
Meta.Add "sheet_name", QPDecode(Fields(4))
If UBound(Fields) = 5 Then Meta.Add "value_mode", QPDecode(Fields(5))
If UBound(Fields) = 7 Then
If UBound(Fields) >= 7 Then
Meta.Add "value_mode", QPDecode(Fields(5))
Meta.Add "custom_value", QPDecode(Fields(6))
Meta.Add "sync_nc", QPDecode(Fields(7))
End If
If UBound(Fields) = 9 Then
Meta.Add "target_scope", QPDecode(Fields(8))
Meta.Add "target_selectors", CStr(Fields(9))
End If
Result.Add "meta", Meta
Case "C"
If UBound(Fields) <> 7 Then Err.Raise vbObjectError + 813, _
@@ -2418,6 +2751,12 @@ Function QPReadSnapshot(ByVal Path)
Record.Add "orientation", QPDecode(Fields(10))
Record.Add "visible", QPDecode(Fields(11))
Attributes.Add CStr(Attributes.Count), Record
Case "U"
If UBound(Fields) <> 6 Then Err.Raise vbObjectError + 874, _
"QuickPartReplace.Target", "invalid unselected component snapshot"
If Untouched.Exists(QPDecode(Fields(1))) Then Err.Raise vbObjectError + 874, _
"QuickPartReplace.Target", "duplicate unselected component UID"
Untouched.Add QPDecode(Fields(1)), Replace(Lines(Index), vbCr, "")
End Select
End If
Next
@@ -2426,6 +2765,7 @@ Function QPReadSnapshot(ByVal Path)
End If
Result.Add "components", Components
Result.Add "attributes", Attributes
Result.Add "untouched", Untouched
Set QPReadSnapshot = Result
End Function
@@ -2514,6 +2854,27 @@ Function QPReadUtf8(ByVal Path)
Stream.Close
End Function
Function QPReadContinuation(ByVal Path)
Dim Attempt, Text, Number, Description
' Atomic Windows replacement and background readers may briefly deny access.
' Only the continuation read retries; token and checkpoint checks remain strict.
For Attempt = 1 To 20
On Error Resume Next
Err.Clear
Text = QPReadUtf8(Path)
Number = Err.Number
Description = Err.Description
Err.Clear
On Error GoTo 0
If Number = 0 Then
QPReadContinuation = Text
Exit Function
End If
WScript.Sleep 50
Next
Err.Raise Number, "QuickPartReplace.ProjectSession", Description
End Function
Sub QPWriteUtf8(ByVal Path, ByVal Text)
Dim Stream
Set Stream = CreateObject("ADODB.Stream")
@@ -2572,8 +2933,49 @@ Function QPDecode(ByVal Value)
End Function
Function QPCanonicalPath(ByVal Value)
QPCanonicalPath = LCase(Replace(QP_Fso.GetAbsolutePathName(CStr(Value)), _
"/", "\"))
Dim Identity
QPEnsureProjectAccess
Identity = LCase(Replace(QP_Fso.GetAbsolutePathName(CStr(Value)), "/", "\"))
If QP_AccessProject.Exists(Identity) Then Identity = QP_AccessProject(Identity)
QPCanonicalPath = Identity
End Function
Sub QPEnsureProjectAccess()
Dim Path, Lines, Fields, Index, Canonical, Access
If IsObject(QP_ProjectAccess) Then Exit Sub
Set QP_ProjectAccess = CreateObject("Scripting.Dictionary")
Set QP_AccessProject = CreateObject("Scripting.Dictionary")
QP_ProjectAccess.CompareMode = 1
QP_AccessProject.CompareMode = 1
Path = QP_Fso.BuildPath(QP_Root, "project-access.tsv")
If Not QP_Fso.FileExists(Path) Then Exit Sub
Lines = Split(QPReadUtf8(Path), vbLf)
If Replace(Lines(0), vbCr, "") <> "project_path" & vbTab & "access_path" Then _
Err.Raise vbObjectError + 874, "QuickPartReplace.ProjectAccess", "invalid project access header"
For Index = 1 To UBound(Lines)
If Len(Replace(Lines(Index), vbCr, "")) > 0 Then
Fields = Split(Replace(Lines(Index), vbCr, ""), vbTab)
If UBound(Fields) <> 1 Then _
Err.Raise vbObjectError + 874, "QuickPartReplace.ProjectAccess", "invalid project access row"
Canonical = LCase(Replace(QP_Fso.GetAbsolutePathName(Fields(0)), "/", "\"))
Access = LCase(Replace(QP_Fso.GetAbsolutePathName(Fields(1)), "/", "\"))
If QP_ProjectAccess.Exists(Canonical) Or QP_AccessProject.Exists(Access) Then _
Err.Raise vbObjectError + 874, "QuickPartReplace.ProjectAccess", "duplicate project access identity"
QP_ProjectAccess.Add Canonical, Fields(1)
QP_AccessProject.Add Access, Canonical
End If
Next
End Sub
Function QPProjectAccessPath(ByVal Value)
Dim Identity
QPEnsureProjectAccess
Identity = LCase(Replace(QP_Fso.GetAbsolutePathName(CStr(Value)), "/", "\"))
If QP_ProjectAccess.Exists(Identity) Then
QPProjectAccessPath = QP_ProjectAccess(Identity)
Else
QPProjectAccessPath = Value
End If
End Function
Sub QPRaiseCaptured(ByVal Number, ByVal Source, ByVal Description, ByVal Fallback)
+3 -1
View File
@@ -69,10 +69,12 @@ try {
Push-Location $repositoryRoot
$locationPushed = $true
& $PythonExecutable -m pytest -q tests\trial_task_center\test_application.py tests\packaging\test_dx_part_replace_build.py
& $PythonExecutable -m pytest -q tests\v1_1 tests\trial_task_center\test_application.py tests\trial_task_center\test_execution_safety.py tests\part_replace\test_verification.py
if ($LASTEXITCODE -ne 0) { throw "Release verification failed; build stopped" }
Remove-VerifiedBuildTarget -RepositoryRoot $repositoryRoot -RelativeTarget "build\DxPartReplace"
Remove-VerifiedBuildTarget -RepositoryRoot $repositoryRoot -RelativeTarget "dist\DxPartReplace"
& $PythonExecutable -m PyInstaller --noconfirm packaging\DxPartReplace.spec
if ($LASTEXITCODE -ne 0) { throw "PyInstaller failed; build stopped" }
$executable = [System.IO.Path]::GetFullPath((Join-Path $repositoryRoot "dist\DxPartReplace\DxPartReplace.exe"))
if (-not (Test-Path -LiteralPath $executable -PathType Leaf)) {
+4 -3
View File
@@ -4,9 +4,9 @@ build-backend = "setuptools.build_meta"
[project]
name = "dx-productivity"
version = "1.0.0"
version = "1.1.2"
requires-python = ">=3.12,<3.13"
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<1"]
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<1", "openpyxl>=3.1,<4"]
[project.scripts]
dx-part-replace = "dx_productivity.part_replace.cli:main"
@@ -19,6 +19,7 @@ dev = ["pytest>=8,<9", "pytest-cov>=5,<7", "coverage>=7,<8", "build>=1.2,<2", "p
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
testpaths = ["tests/v1_1"]
pythonpath = ["src"]
addopts = "-ra"
cache_dir = "build/pytest-cache"
@@ -9,7 +9,7 @@ import platform
import sys
from typing import Sequence
from PySide6.QtCore import QTimer
from PySide6.QtCore import QTimer, QThreadPool
from PySide6.QtWidgets import QApplication
from dx_productivity.trial_task_center.logging_setup import LoggingContext, configure_logging, install_exception_hooks
@@ -35,6 +35,9 @@ def _parse_arguments(argv: Sequence[str] | None) -> argparse.Namespace:
parser.add_argument("--native-helper", action="store_true", help=argparse.SUPPRESS)
parser.add_argument("--snapshot", type=Path, help=argparse.SUPPRESS)
parser.add_argument("--sceneos-cli", action="store_true", help=argparse.SUPPRESS)
parser.add_argument('--private-cad-action', choices=('probe', 'quit'), help=argparse.SUPPRESS)
parser.add_argument('--private-cad-evidence', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--private-cad-pid', type=int, help=argparse.SUPPRESS)
return parser.parse_args(list(argv) if argv is not None else None)
@@ -72,11 +75,15 @@ def resolve_data_root(cli_value: Path | None) -> Path:
def _log_startup(context: LoggingContext, data_root: Path, database_path: Path) -> None:
# platform.platform() queries WMI on Windows; diagnostics must not delay or
# fail CAD startup because the WMI provider is slow or out of resources.
version = sys.getwindowsversion() if os.name == 'nt' else None
os_description = f'Windows {version.major}.{version.minor}.{version.build}' if version else platform.platform()
context.logger.info(
"application_start version=%s executable=%s os=%s data_root=%s database=%s application_log=%s",
VERSION,
sys.executable,
platform.platform(),
os_description,
data_root,
database_path,
context.application_log_path,
@@ -91,6 +98,11 @@ def _flush(context: LoggingContext) -> None:
def main(argv: Sequence[str] | None = None) -> int:
"""Run the Qt shell, returning a conventional process status code."""
arguments = _parse_arguments(argv)
if arguments.private_cad_action:
if arguments.private_cad_evidence is None or arguments.private_cad_pid is None:
return 2
from dx_productivity.trial_task_center.isolated_cad import native_action
return native_action(arguments.private_cad_action, arguments.private_cad_evidence, arguments.private_cad_pid)
if arguments.native_helper:
if arguments.snapshot is None:
return 2
@@ -109,11 +121,6 @@ def main(argv: Sequence[str] | None = None) -> int:
database_path = data_root / "task-center.db"
_log_startup(logging_context, data_root, database_path)
store = TaskStore(database_path)
recovered = store.recover_interrupted_work()
if recovered:
logging_context.logger.warning("recovered_interrupted_projects=%s", ",".join(recovered))
else:
logging_context.logger.info("recovered_interrupted_projects=none")
service = TaskCenterService(store, logging_context)
qt_application = QApplication([sys.executable, *(argv or ())])
window = _load_window()(service)
@@ -129,6 +136,9 @@ def main(argv: Sequence[str] | None = None) -> int:
return 1
finally:
if store is not None:
# The window invalidates queued UI results on close. Finish the
# remaining read before releasing the shared SQLite connection.
QThreadPool.globalInstance().waitForDone()
store.close()
+73 -238
View File
@@ -1,15 +1,11 @@
"""Serial, confirmed queue execution with safe between-item pausing."""
from dataclasses import dataclass
from concurrent.futures import Future, ThreadPoolExecutor
import hashlib
import json
import os
from pathlib import Path
import shutil
from threading import Event
import time
from uuid import uuid4
from .errors import TaskCenterError
from .logging_setup import append_task_event
@@ -17,7 +13,6 @@ from .models import TaskStatus
from .quick_run import (
BATCH_FAILED_STATE,
BATCH_SAVED_UNVERIFIED_STATE,
TERMINAL_STATES,
QuickRunProgress,
QuickRunStepResult,
_path_key,
@@ -25,10 +20,8 @@ from .quick_run import (
)
from .retention import maintain_quick_run_storage
from .schematic_backup import create_schematic_backup
_BACKUP_STATE_NAME = 'batch-backups.json'
_BACKUP_DIRECTORY_NAME = 'batch-backups'
from .execution_metrics import measure_phase
from .batch_backup import BatchBackupCoordinator, _write_backup_state
@dataclass(frozen=True)
@@ -47,9 +40,10 @@ def execute_batch(
expected_item,
stop_event: Event,
continue_after_backup_failure: bool = False,
reuse_project_session: bool = True,
) -> BatchRunResult:
preparer = service._quick_run_preparer
retention = maintain_quick_run_storage(preparer._data_root)
retention = maintain_quick_run_storage(preparer.data_root)
if retention.removed_entries or retention.skipped_entries:
service._logging.logger.info(
'quick_run_retention removed=%s removed_bytes=%s skipped=%s',
@@ -58,7 +52,7 @@ def execute_batch(
)
task = service._store.get_task(task_id)
projects = service._store.list_projects(task_id)
rules = service._store.list_rules(task_id)
rules = service._execution_rules(task_id)
progress = preparer.progress(task_id, projects, rules, copy_part_number_to_value=task.copy_part_number_to_value)
mode = 'part_label' if task.copy_part_number_to_value else 'preserve'
actual = (str(progress.next_project_path), progress.next_old_part_number, progress.next_new_part_number, mode)
@@ -67,118 +61,26 @@ def execute_batch(
return BatchRunResult(progress, False)
if expected_item is None or actual != expected_item:
raise TaskCenterError('quick_run_selection_changed', '队列起点或 Value 选项发生变化,请重新确认。')
if (preparer._data_root / 'quick-run/uncertain.flag').exists():
if (preparer.data_root / 'quick-run/uncertain.flag').exists():
raise TaskCenterError('quick_run_uncertain', '队列存在待核验步骤,不能绕过保护开始批量执行。')
if task.status is TaskStatus.PAUSED and not stop_event.is_set():
service._store.set_task_status(task_id, TaskStatus.RUNNING, summary='automatic queue resumed after confirmation')
session = preparer.begin_batch_session(
task_id,
projects,
rules,
copy_part_number_to_value=task.copy_part_number_to_value,
)
with measure_phase(service._logging, task_id, 'prepare_queue', unit='step') as metric:
session = preparer.begin_batch_session(
task_id,
projects,
rules,
copy_part_number_to_value=task.copy_part_number_to_value,
)
metric['completed_units'] = len(session.commands)
initial_progress = progress
progress = session.progress
backup_root = session.handoff.command_path.parent
backup_state_path = backup_root / _BACKUP_STATE_NAME
backup_state = _read_backup_state(backup_state_path, task_id)
backed_up_roots = {
root_key
for root_key, entry in backup_state.items()
if entry.get('status') == 'backed_up' and _reusable_backup(backup_root, root_key, entry)
}
unbacked_project_paths: list[Path] = [
Path(str(entry['project_path']))
for entry in backup_state.values()
if entry.get('status') == 'unbacked' and entry.get('project_path')
]
backups = BatchBackupCoordinator(service, task_id, session, projects,
continue_after_failure=continue_after_backup_failure,
backup=_backup_project_root, write_state=_write_backup_state)
last_result = None
item_messages: list[str] = []
def backup_destination(root_key: str) -> Path:
return backup_root / _BACKUP_DIRECTORY_NAME / f'project-{_backup_key(root_key)}'
def record_backup_failure(project_path: Path, root_key: str, destination: Path, error: TaskCenterError) -> None:
backup_state[root_key] = {
'status': 'unbacked',
'project_path': str(project_path),
'destination': str(destination.relative_to(backup_root)),
'error_id': error.error_id,
'error': error.message,
}
_write_backup_state(backup_state_path, task_id, backup_state)
if not continue_after_backup_failure:
raise error
if project_path not in unbacked_project_paths:
unbacked_project_paths.append(project_path)
service._batch_feedback = (task_id, progress, f'备份失败已按确认跳过:{project_path.name}')
append_task_event(
service._logging,
level='WARNING',
task_id=task_id,
operation='quick_run_backup_override',
message='操作员明确确认在原理图精简备份失败后继续当前队列。',
error_id=error.error_id,
details={
'state': 'continued_without_backup',
'project_path': str(project_path),
'backup_error': error.message,
'rollback_available': False,
},
)
def record_backup_success(project_path: Path, root_key: str, destination: Path) -> None:
backup_state[root_key] = {
'status': 'backed_up',
'project_path': str(project_path),
'destination': str(destination.relative_to(backup_root)),
}
_write_backup_state(backup_state_path, task_id, backup_state)
backed_up_roots.add(root_key)
def backup_project(project_path: Path) -> None:
root_key = _path_key(project_path.resolve(strict=False).parent)
if root_key in backed_up_roots:
return
previous = backup_state.get(root_key)
if previous is not None and previous.get('status') == 'unbacked':
if not continue_after_backup_failure:
raise TaskCenterError(
'quick_run_backup',
f"工程此前备份失败,尚未建立可用回滚副本:{project_path};请排除原因后重试,或明确确认忽略备份失败。",
error_id=str(previous.get('error_id') or '') or None,
)
if project_path not in unbacked_project_paths:
unbacked_project_paths.append(project_path)
backed_up_roots.add(root_key)
return
service._batch_feedback = (task_id, progress, f'正在备份 {project_path.name}')
destination = backup_destination(root_key)
try:
_backup_project_root(
preparer._data_root,
project_path,
destination,
)
except TaskCenterError as error:
if error.code != 'quick_run_backup':
raise
record_backup_failure(project_path, root_key, destination, error)
else:
record_backup_success(project_path, root_key, destination)
backed_up_roots.add(root_key)
def next_backup_candidate(start_index: int, active_root_key: str) -> tuple[Path, str] | None:
for command in session.commands[start_index:]:
state = session.latest.get(command[1])
if state is not None and state[0] in TERMINAL_STATES:
continue
project_path = Path(command[2])
root_key = _path_key(project_path.resolve(strict=False).parent)
if root_key == active_root_key or root_key in backed_up_roots or root_key in backup_state:
continue
return project_path, root_key
return None
project_ids = {_path_key(project.path): project.project_id for project in projects}
if session.progress.completed_items > initial_progress.completed_items:
discovered_no_match = session.progress.completed_items - initial_progress.completed_items
@@ -206,64 +108,46 @@ def execute_batch(
)
else:
progress = session.progress
prefetched_backup: tuple[Path, str, Path, Future[None]] | None = None
def commit_prefetched_backup() -> None:
nonlocal prefetched_backup
if prefetched_backup is None:
return
project_path, root_key, destination, future = prefetched_backup
try:
future.result()
except TaskCenterError as error:
if error.code != 'quick_run_backup':
raise
record_backup_failure(project_path, root_key, destination, error)
else:
record_backup_success(project_path, root_key, destination)
prefetched_backup = None
with ThreadPoolExecutor(max_workers=1, thread_name_prefix='dxpart-backup') as backup_executor:
with backups, preparer.project_session_scope(enabled=reuse_project_session) as project_session:
while not progress.queue_complete:
if stop_event.is_set():
commit_prefetched_backup()
backups.commit_prefetched(progress)
return BatchRunResult(
progress, True, last_result, tuple(item_messages), tuple(unbacked_project_paths)
progress, True, last_result, tuple(item_messages), tuple(backups.unbacked_project_paths)
)
current = progress.next_project_path
if current is None:
raise TaskCenterError('quick_run_queue_progress', '队列未结束但找不到下一项,已停止。')
root_key = _path_key(current.resolve(strict=False).parent)
if root_key not in backed_up_roots:
if prefetched_backup is not None and prefetched_backup[1] == root_key:
service._batch_feedback = (task_id, progress, f'正在确认预备份 {current.name}')
commit_prefetched_backup()
else:
service._batch_feedback = (task_id, progress, f'正在备份 {current.name}')
backup_project(current)
if prefetched_backup is None:
next_backup = next_backup_candidate(session.next_index + 1, root_key)
if next_backup is not None:
project_path, next_root_key = next_backup
destination = backup_destination(next_root_key)
future = backup_executor.submit(
_backup_project_root,
preparer._data_root,
project_path,
destination,
)
prefetched_backup = (project_path, next_root_key, destination, future)
current_key = _path_key(current)
project_session.prepare(current)
backups.prepare(current, progress)
service._batch_feedback = (task_id, progress, f'正在处理 {current.name}')
if stop_event.is_set():
commit_prefetched_backup()
backups.commit_prefetched(progress)
return BatchRunResult(
progress, True, last_result, tuple(item_messages), tuple(unbacked_project_paths)
progress, True, last_result, tuple(item_messages), tuple(backups.unbacked_project_paths)
)
expected = (str(current), progress.next_old_part_number, progress.next_new_part_number, mode)
sheet = f'{progress.next_schematic_name}:{progress.next_sheet_number}' if progress.next_schematic_name else '当前图页'
service._batch_feedback = (task_id, progress, f'正在执行 {current.name} | {sheet}:{expected[1]} → {expected[2]}')
last_result = preparer.execute_step(task_id, projects, rules, copy_part_number_to_value=task.copy_part_number_to_value,
expected_item=expected, batch_mode=True, batch_session=session)
with measure_phase(service._logging, task_id, 'execute_step', unit='step', persist=False,
project_path=str(current), schematic_name=progress.next_schematic_name,
sheet_number=progress.next_sheet_number, old_part_number=expected[1],
new_part_number=expected[2], job_id=session.commands[session.next_index][1]) as metric:
try:
last_result = preparer.execute_step(task_id, projects, rules, copy_part_number_to_value=task.copy_part_number_to_value,
expected_item=expected, batch_mode=True, batch_session=session,
**({'project_session': project_session} if project_session.enabled else {}))
metric['state'] = last_result.state
metric['completed_units'] = int(last_result.state in {'saved_ok', 'restored_ok', 'no_match'})
finally:
worker_progress = session.handoff.command_path.parent / 'worker-progress.json'
try:
native = json.loads(worker_progress.read_text(encoding='utf-8'))
if isinstance(native, dict) and native.get('job_id') == metric['job_id']:
metric['worker_stage_seconds'] = native.get('stage_seconds', {})
except (OSError, ValueError):
pass
if 'NC synced:' in last_result.message or last_result.state in {
BATCH_FAILED_STATE,
BATCH_SAVED_UNVERIFIED_STATE,
@@ -279,100 +163,51 @@ def execute_batch(
or candidate.queue_complete
or last_result.state in {BATCH_FAILED_STATE, BATCH_SAVED_UNVERIFIED_STATE}
)
updated = service._synchronize_quick_run_progress(task_id, progress=candidate) if synchronize else candidate
if synchronize:
with measure_phase(service._logging, task_id, 'persist_progress', job_id=metric['job_id']) as persistence:
updated = service._synchronize_quick_run_progress(task_id, progress=candidate)
persistence['completed_units'] = 1
else:
updated = candidate
if updated.completed_items <= progress.completed_items or updated.total_items != progress.total_items:
_write_uncertain_flag(preparer._data_root / 'quick-run/uncertain.flag', 'batch_progress_mismatch')
_write_uncertain_flag(preparer.data_root / 'quick-run/uncertain.flag', 'batch_progress_mismatch')
raise TaskCenterError('quick_run_queue_progress', '执行器返回后队列进度异常,已停止,避免重复执行。')
if project_completed or updated.queue_complete or last_result.state in {
# Keep every verified step: one project can contain many sheets and rules.
project_id = project_ids.get(current_key)
event_level = 'WARNING' if last_result.state in {
BATCH_FAILED_STATE,
BATCH_SAVED_UNVERIFIED_STATE,
}:
project_id = next(
(project.project_id for project in projects if _path_key(project.path) == _path_key(current)),
None,
)
event_level = 'WARNING' if last_result.state in {
BATCH_FAILED_STATE,
BATCH_SAVED_UNVERIFIED_STATE,
} else 'INFO'
append_task_event(service._logging, level=event_level,
task_id=task_id, project_id=project_id, operation='quick_run_executed', message=last_result.message,
details={'state': last_result.state, 'continue_queue': not updated.queue_complete,
'completed_items': updated.completed_items, 'total_items': updated.total_items,
'completed_projects': len(updated.completed_project_paths)})
} else 'INFO'
append_task_event(service._logging, level=event_level,
task_id=task_id, project_id=project_id, operation='quick_run_executed', message=last_result.message,
details={'state': last_result.state, 'continue_queue': not updated.queue_complete,
'timing': metric,
'project_path': str(current),
'schematic_name': progress.next_schematic_name,
'sheet_number': progress.next_sheet_number,
'old_part_number': expected[1], 'new_part_number': expected[2],
'completed_items': updated.completed_items, 'total_items': updated.total_items,
'completed_projects': len(updated.completed_project_paths)})
service._logging.logger.info('quick_run_batch_item task_id=%s state=%s completed=%s total=%s',
task_id, last_result.state, updated.completed_items, updated.total_items)
progress = updated
if last_result.state == BATCH_SAVED_UNVERIFIED_STATE:
_write_uncertain_flag(preparer.data_root / 'quick-run/uncertain.flag',
'saved_readback_unverified')
service._batch_feedback = (task_id, progress, '保存后回读未通过,队列已停止,请核验工程。')
return BatchRunResult(progress, True, last_result, tuple(item_messages),
tuple(backups.unbacked_project_paths))
feedback = '未命中已跳过,继续下一项' if last_result.state == 'no_match' else (
'已保存但回读校验失败,已记录,继续下一项'
if last_result.state == BATCH_SAVED_UNVERIFIED_STATE
else '失败已记录,继续下一项'
'失败已记录,继续下一项'
if last_result.state == BATCH_FAILED_STATE
else '已保存并校验,继续下一项'
)
service._batch_feedback = (task_id, progress, feedback)
return BatchRunResult(
progress, False, last_result, tuple(item_messages), tuple(unbacked_project_paths)
progress, False, last_result, tuple(item_messages), tuple(backups.unbacked_project_paths)
)
def _backup_key(root_key: str) -> str:
return hashlib.sha256(root_key.encode('utf-8')).hexdigest()[:16]
def _read_backup_state(path: Path, task_id: str) -> dict[str, dict[str, object]]:
if not path.is_file():
return {}
try:
payload = json.loads(path.read_text(encoding='utf-8'))
if not isinstance(payload, dict) or payload.get('format_version') != 1 or payload.get('task_id') != task_id:
raise ValueError('backup state does not belong to the current queue')
projects = payload.get('projects')
if not isinstance(projects, dict):
raise ValueError('backup state projects are invalid')
return {
str(root_key): dict(entry)
for root_key, entry in projects.items()
if isinstance(entry, dict) and entry.get('status') in {'backed_up', 'unbacked'}
}
except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as error:
raise TaskCenterError('quick_run_backup', '当前队列的备份状态文件无效,已停止以避免重复或错误覆盖。') from error
def _write_backup_state(path: Path, task_id: str, projects: dict[str, dict[str, object]]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(f'.{path.name}.{uuid4().hex}.tmp')
payload = {'format_version': 1, 'task_id': task_id, 'projects': projects}
try:
with temporary.open('w', encoding='utf-8', newline='\n') as stream:
json.dump(payload, stream, ensure_ascii=False, indent=2)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
except OSError as error:
temporary.unlink(missing_ok=True)
raise TaskCenterError('quick_run_backup', '无法保存队列备份状态,已停止以避免重复执行。') from error
def _reusable_backup(backup_root: Path, root_key: str, entry: dict[str, object]) -> bool:
destination = backup_root / str(entry.get('destination') or '')
manifest = destination / '.dxpartreplace-backup.json'
if not manifest.is_file() or str(entry.get('destination') or '').replace('\\', '/') != (
f'{_BACKUP_DIRECTORY_NAME}/project-{_backup_key(root_key)}'
):
return False
try:
payload = json.loads(manifest.read_text(encoding='utf-8'))
return (
isinstance(payload, dict)
and payload.get('format_version') == 1
and payload.get('scope') == 'dxdesigner_schematic_essentials'
and isinstance(payload.get('files'), list)
)
except (OSError, UnicodeError, json.JSONDecodeError):
return False
def _backup_project_root(data_root: Path, project_path: Path, destination: Path) -> None:
last_error: OSError | None = None
for attempt in range(3):
@@ -0,0 +1,222 @@
"""Durable backup coordination and one-project prefetch for serial CAD queues."""
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
import os
from pathlib import Path
from uuid import uuid4
from .errors import TaskCenterError
from .execution_metrics import measure_phase
from .logging_setup import append_task_event
from .quick_run import TERMINAL_STATES, _path_key
_BACKUP_STATE_NAME = 'batch-backups.json'
_BACKUP_DIRECTORY_NAME = 'batch-backups'
class BatchBackupCoordinator:
"""Publish backup outcomes on the queue thread before allowing CAD work.
Only file copying runs in the prefetch thread. Durable state, failure policy
and operator feedback remain on the serial queue thread.
"""
def __init__(self, service, task_id, session, projects, *, continue_after_failure,
backup, write_state):
self.service = service
self.task_id = task_id
self.session = session
self.data_root = service._quick_run_preparer.data_root
self.root = session.handoff.command_path.parent
self.state_path = self.root / _BACKUP_STATE_NAME
self.state = _read_backup_state(self.state_path, task_id)
self.backed_up_roots = {
key for key, entry in self.state.items()
if entry.get('status') == 'backed_up' and _reusable_backup(self.root, key, entry)
}
self.unbacked_project_paths = [Path(str(entry['project_path']))
for entry in self.state.values()
if entry.get('status') == 'unbacked' and entry.get('project_path')]
self.project_root_keys = {_path_key(project.path):
_path_key(project.path.resolve(strict=False).parent) for project in projects}
self.continue_after_failure = continue_after_failure
self._backup = backup
self._write_state = write_state
self._search_exhausted = False
self._prefetched = None
self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix='dxpart-backup')
def __enter__(self):
return self
def __exit__(self, *exc):
# Match the queue's original executor boundary: wait for copying even
# when CAD fails, without publishing an unconsumed speculative result.
self._executor.shutdown(wait=True)
def _destination(self, root_key):
return self.root / _BACKUP_DIRECTORY_NAME / f'project-{_backup_key(root_key)}'
def perform_backup(self, project_path, destination):
with measure_phase(self.service._logging, self.task_id, 'backup_project',
project_path=str(project_path)) as metric:
self._backup(self.data_root, project_path, destination)
metric['completed_units'] = 1
def _failure(self, project_path, root_key, destination, error, progress):
self.state[root_key] = {
'status': 'unbacked', 'project_path': str(project_path),
'destination': str(destination.relative_to(self.root)),
'error_id': error.error_id, 'error': error.message,
}
self._write_state(self.state_path, self.task_id, self.state)
if not self.continue_after_failure:
raise error
if project_path not in self.unbacked_project_paths:
self.unbacked_project_paths.append(project_path)
self.service._batch_feedback = (self.task_id, progress, f'备份失败已按确认跳过:{project_path.name}')
append_task_event(self.service._logging, level='WARNING', task_id=self.task_id,
operation='quick_run_backup_override',
message='操作员明确确认在原理图精简备份失败后继续当前队列。', error_id=error.error_id,
details={'state': 'continued_without_backup', 'project_path': str(project_path),
'backup_error': error.message, 'rollback_available': False})
def _success(self, project_path, root_key, destination):
self.state[root_key] = {
'status': 'backed_up', 'project_path': str(project_path),
'destination': str(destination.relative_to(self.root)),
}
self._write_state(self.state_path, self.task_id, self.state)
self.backed_up_roots.add(root_key)
def _backup_project(self, project_path, progress):
root_key = self.project_root_keys[_path_key(project_path)]
if root_key in self.backed_up_roots:
return
previous = self.state.get(root_key)
if previous is not None and previous.get('status') == 'unbacked':
if not self.continue_after_failure:
raise TaskCenterError('quick_run_backup',
f"工程此前备份失败,尚未建立可用回滚副本:{project_path};请排除原因后重试,或明确确认忽略备份失败。",
error_id=str(previous.get('error_id') or '') or None)
if project_path not in self.unbacked_project_paths:
self.unbacked_project_paths.append(project_path)
self.backed_up_roots.add(root_key)
return
self.service._batch_feedback = (self.task_id, progress, f'正在备份 {project_path.name}')
destination = self._destination(root_key)
try:
self.perform_backup(project_path, destination)
except TaskCenterError as error:
if error.code != 'quick_run_backup':
raise
self._failure(project_path, root_key, destination, error, progress)
else:
self._success(project_path, root_key, destination)
self.backed_up_roots.add(root_key)
def _next_candidate(self, start_index, active_root_key):
if self._search_exhausted:
return None
for command in self.session.commands[start_index:]:
state = self.session.latest.get(command[1])
if state is not None and state[0] in TERMINAL_STATES:
continue
project_path = Path(command[2])
root_key = self.project_root_keys[_path_key(project_path)]
if root_key == active_root_key or root_key in self.backed_up_roots or root_key in self.state:
continue
return project_path, root_key
self._search_exhausted = True
return None
def commit_prefetched(self, progress):
if self._prefetched is None:
return
project_path, root_key, destination, future = self._prefetched
try:
future.result()
except TaskCenterError as error:
if error.code != 'quick_run_backup':
raise
self._failure(project_path, root_key, destination, error, progress)
else:
self._success(project_path, root_key, destination)
self._prefetched = None
def prepare(self, current, progress):
"""Confirm current backup, then prefetch at most one other project root."""
root_key = self.project_root_keys[_path_key(current)]
if root_key not in self.backed_up_roots:
if self._prefetched is not None and self._prefetched[1] == root_key:
self.service._batch_feedback = (self.task_id, progress, f'正在确认预备份 {current.name}')
self.commit_prefetched(progress)
else:
self.service._batch_feedback = (self.task_id, progress, f'正在备份 {current.name}')
self._backup_project(current, progress)
if self._prefetched is None:
candidate = self._next_candidate(self.session.next_index + 1, root_key)
if candidate is not None:
project_path, next_root_key = candidate
destination = self._destination(next_root_key)
future = self._executor.submit(self.perform_backup, project_path, destination)
self._prefetched = (project_path, next_root_key, destination, future)
def _backup_key(root_key: str) -> str:
return hashlib.sha256(root_key.encode('utf-8')).hexdigest()[:16]
def _read_backup_state(path: Path, task_id: str) -> dict[str, dict[str, object]]:
if not path.is_file():
return {}
try:
payload = json.loads(path.read_text(encoding='utf-8'))
if not isinstance(payload, dict) or payload.get('format_version') != 1 or payload.get('task_id') != task_id:
raise ValueError('backup state does not belong to the current queue')
projects = payload.get('projects')
if not isinstance(projects, dict):
raise ValueError('backup state projects are invalid')
return {
str(root_key): dict(entry)
for root_key, entry in projects.items()
if isinstance(entry, dict) and entry.get('status') in {'backed_up', 'unbacked'}
}
except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as error:
raise TaskCenterError('quick_run_backup', '当前队列的备份状态文件无效,已停止以避免重复或错误覆盖。') from error
def _write_backup_state(path: Path, task_id: str, projects: dict[str, dict[str, object]]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(f'.{path.name}.{uuid4().hex}.tmp')
payload = {'format_version': 1, 'task_id': task_id, 'projects': projects}
try:
with temporary.open('w', encoding='utf-8', newline='\n') as stream:
json.dump(payload, stream, ensure_ascii=False, indent=2)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
except OSError as error:
temporary.unlink(missing_ok=True)
raise TaskCenterError('quick_run_backup', '无法保存队列备份状态,已停止以避免重复执行。') from error
def _reusable_backup(backup_root: Path, root_key: str, entry: dict[str, object]) -> bool:
destination = backup_root / str(entry.get('destination') or '')
manifest = destination / '.dxpartreplace-backup.json'
if not manifest.is_file() or str(entry.get('destination') or '').replace('\\', '/') != (
f'{_BACKUP_DIRECTORY_NAME}/project-{_backup_key(root_key)}'
):
return False
try:
payload = json.loads(manifest.read_text(encoding='utf-8'))
return (
isinstance(payload, dict)
and payload.get('format_version') == 1
and payload.get('scope') == 'dxdesigner_schematic_essentials'
and isinstance(payload.get('files'), list)
)
except (OSError, UnicodeError, json.JSONDecodeError):
return False
@@ -0,0 +1,168 @@
"""Transactional batch defaults, kept separate from per-component choices."""
from dataclasses import replace
from .errors import TaskCenterError
from .models import TaskStatus
from .rule_validation import validate_mapping_pairs
def members(store, task_id):
task = store.get_task(task_id)
if not task.group_id:
return (task,)
return tuple(t for t in store.list_project_group(task.group_id) if t.status is not TaskStatus.DELETED)
def _signature(rule):
return (rule.old_part_number.casefold(), rule.new_part_number, rule.enabled,
rule.custom_value_enabled, rule.custom_value, rule.sync_nc)
def batch_rule_view(store, task_id, *, strict=False):
"""Read legacy groups too; expose conflicting rows so users can resolve them."""
with store.transaction():
tasks = members(store, task_id)
task = store.get_task(task_id)
if task.status is TaskStatus.DELETED or not task.group_id:
return store.list_rules(task_id)
local = {r.old_part_number.casefold(): r for r in store.list_rules(task_id)}
return merge_rule_view((rule for item in tasks for rule in store.list_rules(item.task_id)), local, strict=strict)
def merge_rule_view(rules, local, *, strict=False):
"""Merge already captured rows without reading a newer database generation."""
seen, result = {}, []
for rule in rules:
key = rule.old_part_number.casefold()
if key in seen and seen[key] != _signature(rule):
if strict:
raise TaskCenterError('batch_rules_conflict', f'同批料号规则不一致:{rule.old_part_number},请编辑该规则统一默认值')
result.append(rule)
elif key not in seen:
seen[key] = _signature(rule)
preferred = local.get(key)
result.append(preferred if preferred and _signature(preferred) == _signature(rule) else rule)
if strict:
validate_mapping_pairs((r.old_part_number, r.new_part_number) for r in result if r.enabled)
return tuple(result)
def _options(rule):
return dict(old_part_number=rule.old_part_number, new_part_number=rule.new_part_number,
enabled=rule.enabled, custom_value_enabled=rule.custom_value_enabled,
custom_value=rule.custom_value, sync_nc=rule.sync_nc)
def seed_defaults(rows, rules):
"""Fill new inventory rows only; callers retain every existing edited row."""
defaults = {r.old_part_number.casefold(): r for r in rules if r.enabled}
return tuple(replace(row, new_part_number=rule.new_part_number,
custom_value_enabled=rule.custom_value_enabled,
custom_value=rule.custom_value, sync_nc=rule.sync_nc)
if (rule := defaults.get(row.target.old_part_number.casefold())) else row for row in rows)
def _propagate(store, task_id, before, after):
if not store.get_task(task_id).target_plan_mode:
return
rows = store.list_target_plan(task_id)
defaults_before = {r.old_part_number.casefold(): r for r in before}
defaults_after = {r.old_part_number.casefold(): r for r in after}
updated = []
for row in rows:
key = row.target.old_part_number.casefold()
prior, rule = defaults_before.get(key), defaults_after.get(key)
changes = {}
if rule:
# A rule's enabled flag controls discovery, never the user's selection.
if prior:
for field in ('new_part_number', 'sync_nc'):
if getattr(row, field) == getattr(prior, field):
changes[field] = getattr(rule, field)
if (row.custom_value_enabled, row.custom_value) == (prior.custom_value_enabled, prior.custom_value):
changes.update(custom_value_enabled=rule.custom_value_enabled, custom_value=rule.custom_value)
elif not row.new_part_number:
changes['new_part_number'] = rule.new_part_number
if row.sync_nc:
changes['sync_nc'] = rule.sync_nc
if not row.custom_value_enabled and not row.custom_value:
changes.update(custom_value_enabled=rule.custom_value_enabled, custom_value=rule.custom_value)
updated.append(replace(row, **changes))
if tuple(updated) != rows:
store.replace_target_plan(task_id, updated)
def mutate_batch_rules(service, task_id, operation, *, rule_id=None, offset=0, **options):
store = service._store
with store.transaction():
task = store.get_task(task_id)
tasks = members(store, task_id)
if task.status is TaskStatus.DELETED or not tasks:
raise TaskCenterError('rules_locked', '已删除任务不能编辑料号规则')
for member in tasks:
if member.group_id and member.status not in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.FAILED}:
raise TaskCenterError('rules_locked', f'同批任务「{member.name}」已冻结,不能修改本批料号规则')
service._editable_rules(member.task_id, lambda: None)
before = {t.task_id: store.list_rules(t.task_id) for t in tasks}
selected = store.get_rule(rule_id) if rule_id else None
selected_key = selected.old_part_number.casefold() if selected else None
if operation == 'update':
for field in ('custom_value_enabled', 'custom_value', 'sync_nc'):
if options.get(field) is None:
options[field] = getattr(selected, field)
union = {}
# Existing per-project rules are merged when unambiguous. An explicit
# edit/delete may resolve its own old-number conflict, never other keys.
for rules in before.values():
local_keys = set()
for rule in rules:
key = rule.old_part_number.casefold()
if key in local_keys:
raise TaskCenterError('batch_rules_conflict', f'同批旧料号重复:{rule.old_part_number},请先整理重复规则')
local_keys.add(key)
if key in union and _signature(union[key]) != _signature(rule):
if key != selected_key or operation not in {'update', 'delete'}:
raise TaskCenterError('batch_rules_conflict', f'同批料号规则不一致:{rule.old_part_number},请编辑该规则统一默认值')
else:
union.setdefault(key, rule)
for member in tasks:
local = {r.old_part_number.casefold(): r for r in before[member.task_id]}
if selected_key in local and operation in {'update', 'delete'}:
# Resolve a historical chain/conflict before copying other keys.
# Disabling is temporary and remains inside this batch transaction.
prior = local[selected_key]
if operation == 'delete':
store.delete_rule(prior.rule_id)
del local[selected_key]
else:
store.update_rule(prior.rule_id, **(_options(prior) | {'enabled': False}))
for key, rule in union.items():
if key == selected_key and operation == 'delete':
continue
if key not in local:
settings = _options(rule)
if key == selected_key and operation == 'update':
settings['enabled'] = False
local[key] = store.add_rule(member.task_id, **settings)
# Historical per-project additions may have different positions.
# Normalize to the same batch order before applying a relative move.
store._write_rule_positions([local[key] for key in union if key in local])
if operation == 'add':
if options['old_part_number'].strip().casefold() in local:
raise TaskCenterError('batch_rules_conflict', '该旧料号已有本批规则,请编辑已有规则')
result = store.add_rule(member.task_id, **options)
elif operation == 'update':
new_key = options['old_part_number'].strip().casefold()
if new_key != selected_key and new_key in local:
raise TaskCenterError('batch_rules_conflict', '该旧料号已有本批规则,请编辑已有规则')
result = store.update_rule(local[selected_key].rule_id, **options)
elif operation == 'delete':
result = None
elif operation == 'move':
result = store.move_rule(local[selected_key].rule_id, offset)
else:
raise ValueError(operation)
_propagate(store, member.task_id, before[member.task_id], store.list_rules(member.task_id))
if member.task_id == task_id:
chosen = result
return chosen
@@ -0,0 +1,88 @@
"""Project routing, staged previews and atomic confirmation for a batch BOM."""
from dataclasses import dataclass
from pathlib import Path
from .bom_plan import write_bom_template
from .errors import TaskCenterError
from .models import TaskStatus
@dataclass(frozen=True)
class BomProjectPreview:
task_id: str
project_path: Path
baseline: tuple
inventory: tuple
rows: tuple
@dataclass(frozen=True)
class BomBatchPreview:
anchor_task_id: str
scope: tuple
projects: tuple[BomProjectPreview, ...]
def _scope(store, task_id):
task = store.get_task(task_id)
tasks = store.list_project_group(task.group_id) if task.group_id else (task,)
result = []
for item in tasks:
if item.status is TaskStatus.DELETED:
continue
projects = store.list_projects(item.task_id)
if len(projects) != 1:
raise TaskCenterError('project_binding', '批量 BOM 需要一个工程对应一个任务')
result.append((item, projects[0]))
return tuple(result)
def _identity(scope):
# BOM ownership depends on membership, not the order of later execution.
return tuple(sorted((task.task_id, str(project.path.resolve()).casefold()) for task, project in scope))
def export_template(store, task_id, path):
records = () if task_id is None else tuple({'project_name': task.name, 'project_path': str(project.path),
'enabled': True, 'sync_nc': True} for task, project in _scope(store, task_id))
return write_bom_template(path, records)
def _assert_editable(service, task_id):
context = service.task_context(task_id)
if (context.task.status not in {TaskStatus.DRAFT, TaskStatus.READY} or context.has_evidence
or context.interrupted or not context.project or not context.project.available):
raise TaskCenterError('target_plan_locked', f'工程任务当前不能修改 BOM 计划:{context.task.name}')
def preview_batch(service, task_id, path, *, stop_event=None, on_progress=None):
"""Strict adapter to the same validation engine used by the import report."""
from .bom_import_report import inspect_batch
report = inspect_batch(service, task_id, path, stop_event=stop_event, on_progress=on_progress)
if report.preview is not None:
return report.preview
failed = next((row for row in report.rows if row.status == 'failed'), None)
message = (f'工程「{failed.project_name}」({failed.project_path}) · '
f'Excel 第 {failed.excel_row} 行:{failed.reason}' if failed else
'\n'.join(report.errors) or 'BOM 校验未通过')
raise TaskCenterError('bom_import', message)
def save_batch(service, preview, rows_by_task):
store = service._store
expected = {project.task_id for project in preview.projects}
if not expected or set(rows_by_task) != expected:
raise TaskCenterError('bom_import', '本批 BOM 预览的工程范围已改变')
result = {}
with store.transaction():
if _identity(_scope(store, preview.anchor_task_id)) != preview.scope:
raise TaskCenterError('project_binding', '本批工程范围已改变,请重新导入 BOM')
for project in preview.projects:
_assert_editable(service, project.task_id)
if tuple(store.list_target_plan(project.task_id)) != project.baseline:
raise TaskCenterError('target_identity', '工程位号计划在 BOM 预览后已改变,请重新导入')
for project in preview.projects:
store.record_target_inventory(project.task_id, project.inventory)
result[project.task_id] = store.replace_target_plan(project.task_id, rows_by_task[project.task_id])
return result
@@ -0,0 +1,231 @@
"""Read-only, exhaustive BOM validation with an all-or-nothing preview."""
from dataclasses import dataclass, replace
from pathlib import Path
from zipfile import BadZipFile
from openpyxl import load_workbook
from .bom_batch import BomBatchPreview, BomProjectPreview, _assert_editable, _identity, _scope
from .bom_plan import BomMatcher, _normal_headers, _text, parse_bom_row
from .errors import TaskCenterError
from .store_target_plan import merge_target_inventory
from .target_plan import ProjectIdentityResolver, compile_target_rules
@dataclass(frozen=True)
class BomRowResult:
excel_row: int
project_path: str
project_name: str
status: str # passed, failed, unchecked
reason: str = ''
@dataclass(frozen=True)
class BomProjectResult:
project_path: str
project_name: str
status: str
excel_rows: tuple[int, ...]
@dataclass(frozen=True)
class BomImportReport:
rows: tuple[BomRowResult, ...]
projects: tuple[BomProjectResult, ...]
preview: BomBatchPreview | None = None
errors: tuple[str, ...] = ()
@property
def total_rows(self):
return len(self.rows)
@property
def passed_rows(self):
return sum(row.status == 'passed' for row in self.rows)
@property
def failed_rows(self):
return sum(row.status == 'failed' for row in self.rows)
@property
def unchecked_rows(self):
return sum(row.status == 'unchecked' for row in self.rows)
@property
def total_projects(self):
return len(self.projects)
@property
def passed_projects(self):
return sum(project.status == 'passed' for project in self.projects)
@property
def failed_projects(self):
return sum(project.status == 'failed' for project in self.projects)
@property
def unchecked_projects(self):
return sum(project.status == 'unchecked' for project in self.projects)
def _report(rows, preview=None, errors=()):
grouped = {}
for row in rows:
grouped.setdefault((row.project_path, row.project_name), []).append(row)
projects = tuple(BomProjectResult(path, name,
'failed' if any(row.status == 'failed' for row in items) else
'unchecked' if any(row.status == 'unchecked' for row in items) else 'passed',
tuple(row.excel_row for row in items)) for (path, name), items in grouped.items())
return BomImportReport(tuple(rows), projects, preview, tuple(errors))
def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None):
"""Validate all independent rows; never persist inventory or return partial plans.
Operational failures (including cancellation and native cleanup) propagate so
callers cannot accidentally continue opening CAD after an unsafe failure.
"""
def check_cancelled():
if stop_event is not None and stop_event.is_set():
raise TaskCenterError('operation_cancelled', 'BOM 导入已取消')
check_cancelled()
scope = _scope(service._store, task_id)
routing = ProjectIdentityResolver()
owners = {routing.project(project.path): (task, project) for task, project in scope}
if len(owners) != len(scope):
raise TaskCenterError('project_binding', '同批任务存在重复工程')
rows, records, grouped = [], {}, {}
workbook = None
try:
workbook = load_workbook(Path(path), read_only=True, data_only=False)
sheet = workbook.active
cells = list(sheet.iter_rows())
header_error = ''
if len(workbook.worksheets) != 1:
header_error = 'BOM 工作簿只能包含一个工作表'
elif not cells:
header_error = 'BOM 工作表为空'
headers = _normal_headers(tuple(cell.value for cell in cells[0])) if cells else ()
names = tuple(name for name in headers if name)
if not header_error and len(set(names)) != len(names):
header_error = 'BOM 列名重复'
if not header_error and not {'old_part_number', 'new_part_number', 'refdes'} <= set(headers):
header_error = 'BOM 必须包含旧料号、新料号和位号列'
if cells and any(cell.data_type == 'f' for cell in cells[0]):
header_error = 'BOM 表头不接受公式'
positions = {name: index for index, name in enumerate(headers) if name}
for number, row_cells in enumerate(cells[1:], 2):
check_cancelled()
values = tuple(cell.value for cell in row_cells)
if not any(value not in (None, '') for value in values):
continue
project_path = _text(values, positions, 'project_path')
project_name = _text(values, positions, 'project_name')
if project_path:
owner = owners.get(routing.project(project_path))
if owner is not None:
project_path, project_name = str(owner[1].path), owner[0].name
elif len(scope) == 1:
project_path, project_name = str(scope[0][1].path), scope[0][0].name
reason = header_error
record = None
if not reason:
try:
record = parse_bom_row(row_cells, positions)
if record is None:
continue
except (ValueError, TypeError, TaskCenterError) as error:
reason = str(error)
key = ''
if not reason:
if not record.project_path and len(scope) != 1:
reason = '多工程 BOM 必须填写工程路径列,不能按位号猜测工程'
else:
key = routing.project(record.project_path) if record.project_path else next(iter(owners))
if key not in owners:
reason = f'BOM 工程不属于当前批次:{record.project_path}'
else:
task, project = owners[key]
project_path, project_name = str(project.path), task.name
records[len(rows)] = record
grouped.setdefault(key, []).append(len(rows))
rows.append(BomRowResult(number, project_path, project_name,
'failed' if reason else 'unchecked', reason or '尚未匹配工程位号'))
if header_error:
return _report(rows, errors=(f'Excel 第 1 行:{header_error}',))
except TaskCenterError:
raise
except (OSError, ValueError, TypeError, KeyError, BadZipFile) as error:
return _report(rows, errors=(str(error),))
finally:
if workbook is not None:
workbook.close()
if not rows:
return _report(rows, errors=('BOM 尚未填写替换行,请填写旧料号、新料号和位号',))
# Do not start any reader until all spreadsheet/routing/editability checks pass.
for key, indices in grouped.items():
try:
_assert_editable(service, owners[key][0].task_id)
except TaskCenterError as error:
for index in indices:
rows[index] = replace(rows[index], status='failed', reason=error.message)
if any(row.status == 'failed' for row in rows):
return _report(rows)
previews = []
for position, (key, indices) in enumerate(grouped.items(), 1):
check_cancelled()
task, project = owners[key]
def progress(message):
if on_progress is not None:
on_progress(f'工程 {position}/{len(grouped)} · {message}')
progress(f'正在读取工程「{task.name}」({project.path})')
baseline = tuple(service._store.list_target_plan(task.task_id))
requested = tuple(dict.fromkeys(records[index].old for index in indices))
known = tuple(dict.fromkeys(row.target.old_part_number for row in baseline))
if baseline and {part.casefold() for part in requested} <= {part.casefold() for part in known}:
inventory = tuple(row.target for row in baseline)
else:
controls = {}
if stop_event is not None:
controls['stop_event'] = stop_event
if on_progress is not None:
controls['on_progress'] = progress
inventory = tuple(service.for_project_task(task.task_id)._quick_run_preparer.collect_inventory(
project.path, tuple(dict.fromkeys((*known, *requested))), **controls))
check_cancelled()
merged = merge_target_inventory(baseline, inventory)
matched_rows, touched = {}, {}
matcher = BomMatcher(merged) if merged else None
for index in indices:
try:
# A per-record match reports independent row errors without hiding later rows.
if matcher is None:
raise TaskCenterError('target_inventory', '未采集到可匹配的工程位号')
matched = matcher.match_record(records[index])
compile_target_rules(tuple(matched.values()))
for target_key, row in matched.items():
touched.setdefault(target_key, []).append(index)
matched_rows[target_key] = row
rows[index] = replace(rows[index], status='passed', reason='校验通过')
except TaskCenterError as error:
rows[index] = replace(rows[index], status='failed', reason=error.message)
for target, indices_for_target in touched.items():
if len(indices_for_target) > 1:
for index in indices_for_target:
rows[index] = replace(rows[index], status='failed', reason='位号在 BOM 中重复(Excel 行 ' +
', '.join(str(rows[item].excel_row) for item in indices_for_target) + ')')
combined = tuple(matched_rows.get(key, row) for key, row in matcher.by_key.items()) if matcher else ()
try:
compile_target_rules(combined)
except TaskCenterError as error:
for index in indices:
if rows[index].status == 'passed':
rows[index] = replace(rows[index], status='failed', reason=error.message)
previews.append(BomProjectPreview(task.task_id, project.path, baseline, inventory, combined))
progress(f'「{task.name}」校验完成')
check_cancelled()
preview = None if any(row.status != 'passed' for row in rows) else BomBatchPreview(
task_id, _identity(scope), tuple(previews))
return _report(rows, preview)
@@ -0,0 +1,240 @@
"""Safe BOM-template import for one-to-many RefDes replacement plans."""
from __future__ import annotations
import re
from dataclasses import dataclass
from pathlib import Path
from openpyxl import Workbook, load_workbook
from openpyxl.comments import Comment
from openpyxl.styles import Alignment, Font, PatternFill
from openpyxl.worksheet.datavalidation import DataValidation
from .errors import TaskCenterError
from .target_plan import ProjectIdentityResolver, TargetPlanRow, compile_target_rules
BOM_HEADERS = ('project_name', 'project_path', 'old_part_number', 'new_part_number', 'refdes', 'schematic_name',
'sheet_number', 'uid', 'enabled', 'custom_value', 'sync_nc')
_HEADER_HELP = (
'工程名称:自动填写,便于查看;导入时按工程路径分配任务。',
'工程路径:自动填写,用于区分同批工程,请保持原样;需要更多规则时复制该工程行。',
'旧料号,必填。按文本填写,保留前导零。',
'新料号,必填。按文本填写,保留前导零。',
'位号,必填。一行可填 R1,R2,R3,支持逗号、分号、空格或顿号分隔。',
'原理图名称,可选。位号重复时用于精确匹配。',
'图页,可选。位号跨页重复时应填写图页或 UID。',
'器件 UID,可选;填写时必须与采集结果一致。',
'是否替换:TRUE/FALSE 或 是/否;留空默认替换。未列出的位号保留。',
'自定义 Value,可选;留空沿用工具原有 Value 策略。',
'同步 NC:TRUE/FALSE 或 是/否;留空默认开启。',
)
_REFDES_SPLIT = re.compile(r'[,,;;、\s]+')
_ALIASES = {
'工程名称': 'project_name', '项目名称': 'project_name',
'工程': 'project_path', '工程路径': 'project_path', '项目路径': 'project_path',
'旧料号': 'old_part_number', '旧物料编码': 'old_part_number', 'old_part': 'old_part_number',
'新料号': 'new_part_number', '新物料编码': 'new_part_number', 'new_part': 'new_part_number',
'位号': 'refdes', '参考标号': 'refdes', 'refdes': 'refdes', 'reference_designator': 'refdes',
'原理图': 'schematic_name', 'schematic': 'schematic_name', '图页': 'sheet_number', 'sheet': 'sheet_number',
'uid': 'uid', '替换': 'enabled', '是否替换': 'enabled', 'enabled': 'enabled',
'新value': 'custom_value', '自定义value': 'custom_value', 'custom_value': 'custom_value',
'同步nc': 'sync_nc', '同步_nc': 'sync_nc', 'sync_nc': 'sync_nc',
}
def write_bom_template(path: Path, records=()) -> Path:
workbook = Workbook()
sheet = workbook.active
sheet.title = 'BOM Replacement'
sheet.append(BOM_HEADERS)
for record in records:
sheet.append(tuple(record.get(header, '') for header in BOM_HEADERS))
wrapped = Alignment(wrap_text=True, vertical='top')
for row in sheet.iter_rows():
for cell in row:
cell.alignment = wrapped
# Leave row heights automatic so Excel can fit wrapped text after editing.
for cell, help_text in zip(sheet[1], _HEADER_HELP):
cell.font = Font(bold=True, color='FFFFFF')
cell.fill = PatternFill('solid', fgColor='1D3557')
cell.comment = Comment(help_text, 'DxPartReplace')
sheet.freeze_panes = 'C2'
sheet.auto_filter.ref = sheet.dimensions
for column in ('I', 'K'):
validation = DataValidation(type='list', formula1='"TRUE,FALSE"', allow_blank=False)
sheet.add_data_validation(validation)
validation.add(f'{column}2:{column}{max(2, sheet.max_row + 500)}')
for column, width in {'A': 30, 'B': 64, 'C': 22, 'D': 22, 'E': 28, 'F': 18, 'G': 14,
'H': 28, 'I': 12, 'J': 24, 'K': 12}.items():
sheet.column_dimensions[column].width = width
sheet.column_dimensions[column].alignment = wrapped
for column in ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J'):
sheet.column_dimensions[column].number_format = '@'
path = Path(path)
workbook.save(path)
return path
@dataclass(frozen=True)
class BomRecord:
project_path: str
old: str
new: str
refs: tuple[str, ...]
schematic: str
sheet: str
uid: str
enabled: bool
custom: str
sync_nc: bool
def read_bom_records(path: Path) -> tuple[BomRecord, ...]:
workbook = None
try:
workbook = load_workbook(Path(path), read_only=True, data_only=False)
if len(workbook.worksheets) != 1:
raise ValueError('BOM 工作簿只能包含一个工作表')
sheet = workbook.active
records = list(sheet.iter_rows(values_only=False))
if not records:
raise ValueError('BOM 工作表为空')
headers = _normal_headers(tuple(cell.value for cell in records[0]))
names = tuple(name for name in headers if name)
if len(set(names)) != len(names):
raise ValueError('BOM 列名重复')
required = {'old_part_number', 'new_part_number', 'refdes'}
if not required <= set(headers):
raise ValueError('BOM 必须包含旧料号、新料号和位号列')
positions = {name: index for index, name in enumerate(headers) if name}
result = []
for cells in records[1:]:
record = parse_bom_row(cells, positions)
if record is not None:
result.append(record)
return tuple(result)
except (OSError, ValueError, TypeError, KeyError) as error:
if isinstance(error, TaskCenterError):
raise
raise TaskCenterError('bom_import', str(error)) from error
finally:
if workbook is not None:
workbook.close()
def parse_bom_row(cells, positions):
values = tuple(cell.value for cell in cells)
if not any(value not in (None, '') for value in values):
return None
if any(cell.data_type == 'f' for cell in cells):
raise ValueError('BOM 不接受公式,请填写实际值')
old = _text(values, positions, 'old_part_number')
new = _text(values, positions, 'new_part_number')
refs = _split_refdes(_text(values, positions, 'refdes'))
if not old and not new and not refs and not _text(values, positions, 'custom_value'):
return None # An untouched project row is a scaffold, not a rule.
if not old or not new or not refs:
raise ValueError('BOM 行的旧料号、新料号和位号不能为空')
enabled = _bool(_value(values, positions, 'enabled', True))
sync_nc = _bool(_value(values, positions, 'sync_nc', True))
custom = _text(values, positions, 'custom_value')
schematic = _text(values, positions, 'schematic_name')
sheet_number = _text(values, positions, 'sheet_number')
uid = _text(values, positions, 'uid')
project = _text(values, positions, 'project_path')
if project and not Path(project).is_absolute():
raise ValueError('工程路径必须使用模板中的完整路径')
return BomRecord(project, old, new, refs, schematic, sheet_number, uid, enabled, custom, sync_nc)
class BomMatcher:
"""Index one immutable inventory once, then match independent Excel rows."""
def __init__(self, baseline):
if not baseline:
raise TaskCenterError('target_inventory', '未采集到可匹配的工程位号')
self.by_key = {}
self.projects = set()
self.by_identity = {}
self.identities = ProjectIdentityResolver()
for row in baseline:
target = row.target
key = self.identities.target(target)
if key in self.by_key:
raise TaskCenterError('target_overlap', '采集清单存在重复位号身份')
self.by_key[key] = row
self.projects.add(key[0])
self.by_identity.setdefault((target.old_part_number.casefold(), target.refdes.casefold()), []).append((key, target))
def match_record(self, record):
if record.project_path and self.identities.project(record.project_path) not in self.projects:
raise TaskCenterError('bom_import', 'BOM 工程与当前任务不一致')
matched = {}
for refdes in record.refs:
candidates = [(key, target) for key, target in self.by_identity.get((record.old.casefold(), refdes.casefold()), ())
if (not record.schematic or target.schematic_name.casefold() == record.schematic.casefold())
and (not record.sheet or target.sheet_number.casefold() == record.sheet.casefold())
and (not record.uid or target.uid == record.uid)]
if len(candidates) != 1:
raise TaskCenterError('bom_import', f'位号 {refdes} 无法唯一匹配当前采集清单')
key, target = candidates[0]
if key in matched:
raise TaskCenterError('bom_import', f'位号 {refdes} 在 BOM 中重复')
matched[key] = TargetPlanRow(target, record.enabled, record.new,
bool(record.custom), record.custom, record.sync_nc)
return matched
def match_bom_records(baseline, records) -> tuple[TargetPlanRow, ...]:
matcher = BomMatcher(baseline)
matched = {}
for record in records:
incoming = matcher.match_record(record)
if matched.keys() & incoming.keys():
raise TaskCenterError('bom_import', '位号在 BOM 中重复')
matched.update(incoming)
result = tuple(matched.get(key, TargetPlanRow(row.target)) for key, row in matcher.by_key.items())
compile_target_rules(result)
return result
def read_bom_plan(store, task_id: str, path: Path) -> tuple[TargetPlanRow, ...]:
return match_bom_records(store.list_target_plan(task_id), read_bom_records(path))
def _normal_headers(values):
result = []
for value in values:
raw = str(value or '').strip().casefold().replace(' ', '').replace('-', '_')
result.append(raw if raw in BOM_HEADERS else _ALIASES.get(raw, ''))
return tuple(result)
def _value(values, positions, name, default=''):
index = positions.get(name)
if index is None or index >= len(values) or values[index] in (None, ''):
return default
return values[index]
def _text(values, positions, name):
value = _value(values, positions, name, '')
return '' if value is None else str(value).strip()
def _split_refdes(value):
return tuple(item for item in _REFDES_SPLIT.split(value.strip()) if item)
def _bool(value):
if type(value) is bool:
return value
if isinstance(value, (int, float)) and value in (0, 1):
return bool(value)
if isinstance(value, str) and value.strip().casefold() in {'true', '是', '1', 'yes', 'y'}:
return True
if isinstance(value, str) and value.strip().casefold() in {'false', '否', '0', 'no', 'n', ''}:
return False
raise ValueError('BOM 布尔字段只能填写 TRUE/FALSE 或 是/否')
@@ -0,0 +1,77 @@
"""Identity certificate shared by the private desktop worker and native helper."""
from dataclasses import dataclass
import ctypes
from ctypes import wintypes
import os
import re
def current_desktop_name():
user = ctypes.WinDLL('user32', use_last_error=True)
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
user.GetThreadDesktop.argtypes = [wintypes.DWORD]
user.GetThreadDesktop.restype = wintypes.HANDLE
user.GetUserObjectInformationW.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p,
wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)]
desktop = user.GetThreadDesktop(kernel.GetCurrentThreadId())
value, required = ctypes.create_unicode_buffer(256), wintypes.DWORD()
if not user.GetUserObjectInformationW(desktop, 2, value, ctypes.sizeof(value), ctypes.byref(required)):
raise ctypes.WinError(ctypes.get_last_error())
return value.value
def window_pid(handle):
import win32process
return win32process.GetWindowThreadProcessId(handle)[1]
@dataclass(frozen=True, slots=True)
class CadBinding:
desktop: str
pid: int
guid: str
token: str
@classmethod
def from_environment(cls, environment=None):
environment = os.environ if environment is None else environment
fields = ('DXPART_DESKTOP', 'DXPART_CAD_PID', 'DXPART_CAD_GUID', 'DXPART_SESSION_TOKEN')
values = [environment.get(field, '') for field in fields]
if not any(values):
return None
if not all(values):
raise ValueError('incomplete private CAD identity')
desktop, pid, guid, token = values
if not re.fullmatch(r'dx-[A-Za-z0-9-]{1,80}', desktop) or int(pid) <= 0:
raise ValueError('invalid private CAD desktop or PID')
if not re.fullmatch(r'[0-9a-f]{32}', token):
raise ValueError('invalid private CAD session token')
return cls(desktop, int(pid), guid, token)
def environment(self):
return dict(os.environ, DXPART_DESKTOP=self.desktop, DXPART_CAD_PID=str(self.pid),
DXPART_CAD_GUID=self.guid, DXPART_SESSION_TOKEN=self.token)
def verify_application(app, binding=None, *, require_view=True):
binding = CadBinding.from_environment() if binding is None else binding
if binding is None:
return None
if current_desktop_name() != binding.desktop:
raise ValueError('CAD helper is not running on its owned desktop')
if str(app.Guid()).casefold() != binding.guid.casefold():
raise ValueError('CAD COM GUID does not match its owned session')
if require_view:
handle = int(app.ActiveViewHandle)
if not handle or window_pid(handle) != binding.pid:
raise ValueError('CAD view PID does not match its owned session')
return binding
def project_file_path(app):
"""COM type libraries expose this getter as either a property or a method."""
value = app.GetProjectData().GetProjectFilePath
value = value() if callable(value) else value
if not isinstance(value, str):
raise ValueError('CAD returned an invalid project path')
return value
@@ -7,7 +7,6 @@ from dataclasses import dataclass
import json
import math
from types import MappingProxyType
from typing import Any
from dx_productivity.part_replace.models import MappingRule
@@ -0,0 +1,205 @@
"""Conservative, bounded process-local reuse of read-only CAD discovery.
Content and metadata fingerprints cover every project-tree file except generated
logs and explicit tool data. Links, unreadable paths and changing discovery are misses.
This is an optimization, never a replacement for execution identity checks.
"""
from __future__ import annotations
from collections import OrderedDict
from copy import deepcopy
import hashlib
import os
from pathlib import Path
import stat
from threading import RLock
from .errors import TaskCenterError
from .operation_control import check_cancelled
def project_fingerprint(project: Path, excluded_root: Path, *, stop_event=None) -> tuple | None:
try:
project = Path(project).absolute()
root = project.parent
excluded = excluded_root.resolve()
if _unsafe(root.lstat()):
return None
# A project inside the evidence directory cannot be safely excluded.
if project.resolve().is_relative_to(excluded):
return None
rows = []
def fail(error):
raise error
for current, dirs, files in os.walk(root, onerror=fail, followlinks=False):
check_cancelled(stop_event)
current = Path(current)
kept = []
for name in sorted(dirs):
path = current / name
relative = tuple(part.casefold() for part in path.relative_to(root).parts)
audit_directory = (len(relative) == 3 and relative[:2] == ('database', 'cdbsvr')
and relative[2] in {'log', 'plog', 'events'})
backup_directory = relative == ('projectbackup', 'backups')
if path.resolve() == excluded or name.casefold() == '.git' or audit_directory or backup_directory:
continue
info = path.lstat()
if _unsafe(info):
return None
kept.append(name)
dirs[:] = kept
for name in sorted(files):
check_cancelled(stop_event)
path = current / name
relative = tuple(part.casefold() for part in path.relative_to(root).parts)
if path.suffix.casefold() == '.log' or relative == ('log files', 'projectbackuplog.txt'):
continue
info = path.lstat()
if _unsafe(info) or not stat.S_ISREG(info.st_mode):
return None
before = _file_stamp(info)
with path.open('rb') as stream:
handle_before = _file_stamp(os.fstat(stream.fileno()))
# Windows path stat and handle stat expose different ctime
# semantics. Compare their identity/size/mtime, then compare
# each source's full stamp against itself after hashing.
if handle_before[:4] != before[:4]:
return None
if stop_event is None:
digest = hashlib.file_digest(stream, 'sha256').digest()
else:
digestor = hashlib.sha256()
while chunk := stream.read(1024 * 1024):
check_cancelled(stop_event)
digestor.update(chunk)
digest = digestor.digest()
if _file_stamp(os.fstat(stream.fileno())) != handle_before:
return None
# Check the path as well as the handle: atomic replacement can
# leave a readable handle referring to the obsolete file.
after = path.lstat()
if _unsafe(after) or _file_stamp(after) != before:
return None
rows.append((str(path.relative_to(root)), *before, digest))
if not project.is_file():
return None
return (str(project.resolve()), tuple(sorted(rows)))
except (OSError, ValueError, RuntimeError):
return None
def _file_stamp(info):
return (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns)
def _unsafe(info):
return stat.S_ISLNK(info.st_mode) or bool(
getattr(info, 'st_file_attributes', 0) & getattr(stat, 'FILE_ATTRIBUTE_REPARSE_POINT', 0x400))
def _without_runtime_database(stamp):
if stamp is None or len(stamp) != 2:
return None
return (stamp[0], tuple(row for row in stamp[1]
if row[0].replace('\\', '/').casefold() != 'database/icdb.dat'))
def _only_database_changed(before, after):
design = _without_runtime_database(before)
return design is not None and before != after and design == _without_runtime_database(after)
def _discovery_identity(discovery):
sheets = discovery.sheets
components = getattr(discovery, 'components', ())
if len(set(sheets)) != len(sheets) or len({row.key for row in components}) != len(components):
raise TaskCenterError('target_identity', '原生采集返回重复图页或位号身份,请核对工程')
return (tuple(sorted(sheets)),
tuple(sorted((sheet, tuple(sorted(parts))) for sheet, parts in discovery.matched_old_parts.items())),
tuple(sorted((row.key, row.refdes, row.old_part_number, row.old_value) for row in components)))
class DiscoveryCache:
"""One preparer owns one cache; the lock also serializes cache discovery."""
def __init__(self, data_root: Path, capacity: int = 32):
self.data_root = data_root
self.capacity = capacity
self.lock = RLock()
self._entries = OrderedDict()
def invalidate(self, project: Path):
with self.lock:
self._entries.pop(_key(project), None)
def discover(self, project, parts, collect_components, loader, *, stop_event=None):
with self.lock:
check_cancelled(stop_event)
def fingerprint():
check_cancelled(stop_event)
return project_fingerprint(project, self.data_root, **({'stop_event': stop_event} if stop_event is not None else {}))
key = _key(project)
requested = frozenset(part.casefold() for part in parts)
before = fingerprint()
entry = self._entries.pop(key, None)
if entry is not None:
stamp, covered, has_components, discovery = entry
if (before is not None and before == stamp and requested <= covered
and (not collect_components or has_components)):
self._entries[key] = entry
check_cancelled(stop_event)
return deepcopy(discovery)
# Fingerprinting is an optimization: an initially unverifiable
# project still gets fresh native discovery, with no cache reuse.
if before is None:
discovery = loader()
check_cancelled(stop_event)
_discovery_identity(discovery)
return discovery
# Native opens may update database session metadata on every read.
# Accept that case only after two equal native results while every
# other design file stays stable across both passes. The complete
# final database hash still invalidates later cache reuse.
previous = None
previous_design = None
attempt, limit = 0, 2
while attempt < limit:
if attempt:
before = fingerprint()
check_cancelled(stop_event)
discovery = loader()
check_cancelled(stop_event)
identity = _discovery_identity(discovery)
after = fingerprint()
if before is not None and before == after:
break
if _only_database_changed(before, after):
design = _without_runtime_database(after)
if previous is not None and previous == identity and previous_design == design:
break
# First-open normalization can precede the two stable
# inventory reads. Allow one extra pass only in that case.
if attempt == 1 and previous is None:
limit = 3
previous, previous_design = identity, design
else:
previous = previous_design = None
attempt += 1
else:
raise TaskCenterError("quick_run_sheet_discovery",
"project contents changed or could not be verified during discovery; retry read-only discovery")
# Refuse incomplete inventories and bound both projects and row count.
sheets = getattr(discovery, 'sheets', ())
matches = getattr(discovery, 'matched_old_parts', {})
check_cancelled(stop_event)
if (after is not None and sheets
and set(sheets) == set(matches)
and (len(getattr(discovery, 'components', ())) + len(sheets)
+ sum(len(parts) for parts in matches.values())) <= 100000):
self._entries[key] = (after, requested, collect_components, deepcopy(discovery))
while len(self._entries) > self.capacity:
self._entries.popitem(last=False)
return discovery
def _key(project):
return os.path.normcase(os.path.abspath(str(project)))
@@ -0,0 +1,41 @@
"""Read-only execution feedback shared by the service and UI."""
from dataclasses import dataclass
import json
from pathlib import Path
import time
@dataclass(frozen=True, slots=True)
class ExecutionFeedback:
task_id: str | None
position: int = 1
total: int = 1
message: str = '正在准备执行'
stage: str = ''
stage_seconds: float = 0.0
def read_feedback(task_id, position, total, message, root: Path, started_after: float):
private = root / 'quick-run' / 'private-desktop.json'
try:
modified = private.stat().st_mtime
if modified >= started_after:
state = json.loads(private.read_text(encoding='utf-8')).get('state')
if state in {'starting', 'closing'}:
return ExecutionFeedback(task_id, position, total, message,
'private_startup' if state == 'starting' else 'private_shutdown', max(0, time.time() - modified))
except (OSError, ValueError, TypeError, AttributeError):
pass
path = root / 'quick-run' / 'worker-progress.json'
stage, seconds = '', 0.0
try:
modified = path.stat().st_mtime
if modified >= started_after:
record = json.loads(path.read_text(encoding='utf-8'))
candidate = record.get('stage', '')
if candidate and candidate != 'finished':
seconds = float(record.get('stage_seconds', {}).get(candidate, 0)) + max(0, time.time() - modified)
stage = candidate
except (OSError, ValueError, TypeError, AttributeError):
pass # Display feedback is optional; it never changes execution state.
return ExecutionFeedback(task_id, position, total, message, stage, seconds)
@@ -0,0 +1,24 @@
"""Monotonic phase measurements persisted beside task execution evidence."""
from contextlib import contextmanager
import time
from .logging_setup import append_task_event
@contextmanager
def measure_phase(logging, task_id: str, phase: str, *, unit: str = 'operation', persist: bool = True, **details):
metric = {'phase': phase, 'unit': unit, 'completed_units': 0, 'state': 'completed', **details}
started = time.perf_counter()
try:
yield metric
except Exception as error:
metric.update(state='error', completed_units=0, error_code=getattr(error, 'code', type(error).__name__))
raise
finally:
elapsed = max(0.0, time.perf_counter() - started)
metric['elapsed_seconds'] = elapsed
metric['units_per_minute'] = metric['completed_units'] * 60 / elapsed if elapsed > 0 else None
if persist or metric['state'] == 'error':
append_task_event(logging, level='WARNING' if metric['state'] == 'error' else 'INFO',
task_id=task_id, operation='execution_timing', details=metric)
@@ -0,0 +1,51 @@
"""Validate read-only component inventory produced by sheet discovery."""
from __future__ import annotations
from pathlib import Path
from .errors import TaskCenterError
from .target_plan import ComponentTarget
HEADER = ("project_path", "schematic_name", "sheet_number", "uid", "refdes",
"old_part", "old_value")
def read_component_inventory(path: Path, project_path: Path,
sheets: tuple[tuple[str, str], ...]) -> tuple[ComponentTarget, ...]:
from .quick_run import _decode_vbs_field, _path_key
try:
lines = Path(path).read_text(encoding="utf-8-sig").splitlines()
if not lines or tuple(lines[0].split("\t")) != HEADER:
raise ValueError("component inventory header changed")
result: list[ComponentTarget] = []
seen: set[tuple[str, str, str]] = set()
for line in lines[1:]:
if not line:
continue
fields = tuple(_decode_vbs_field(field) for field in line.split("\t"))
if len(fields) != len(HEADER):
raise ValueError("component inventory row is malformed")
project, schematic, sheet, uid, refdes, old_part, old_value = fields
if (_path_key(project) != _path_key(project_path) or (schematic, sheet) not in sheets or
not all((uid, refdes, old_part)) or (schematic, sheet, uid) in seen):
raise ValueError("component inventory identity is invalid")
seen.add((schematic, sheet, uid))
result.append(ComponentTarget(Path(project_path), schematic, sheet, uid, refdes,
old_part, old_value))
return tuple(result)
except (OSError, UnicodeError, ValueError) as error:
raise TaskCenterError("target_inventory", str(error)) from error
def collect_target_inventory(preparer, project_path: Path,
old_part_numbers: tuple[str, ...], *, stop_event=None, on_progress=None) -> tuple[ComponentTarget, ...]:
if not old_part_numbers:
raise TaskCenterError("target_inventory", "at least one old Part Number is required")
from .operation_control import check_cancelled, control_options
check_cancelled(stop_event)
rows = preparer.collect_inventory(project_path, old_part_numbers, **control_options(stop_event, on_progress))
check_cancelled(stop_event)
return rows
@@ -0,0 +1,255 @@
"""Start the real CAD and its automation on one owned Windows desktop."""
from dataclasses import asdict
import json
import os
from pathlib import Path
import subprocess
import sys
import time
from uuid import uuid4
from .cad_identity import CadBinding, current_desktop_name, verify_application, project_file_path
from .isolated_desktop import PrivateDesktop
from .worker_monitor import WorkerMonitorError
class PrivateCadStartupError(WorkerMonitorError):
"""The owned desktop was released before any project worker was launched."""
def _helper_command(action, evidence, pid):
if getattr(sys, 'frozen', False):
return (sys.executable, '--private-cad-action', action, '--private-cad-evidence', str(evidence),
'--private-cad-pid', str(pid))
return (sys.executable, '-m', __name__, action, str(evidence), str(pid))
def _child_environment(environment):
environment = dict(environment)
if not getattr(sys, 'frozen', False):
environment['PYTHONPATH'] = str(Path(__file__).resolve().parents[2]) + os.pathsep + environment.get('PYTHONPATH', '')
return environment
def _replace_record(temporary, target):
# Windows readers can temporarily deny delete access to the old JSON.
# Keep the complete old record until replacement succeeds, with a finite
# retry budget so persistent permissions failures still reach the caller.
deadline = time.monotonic() + 1.0
while True:
try:
temporary.replace(target)
return
except PermissionError:
if time.monotonic() >= deadline:
raise
time.sleep(0.02)
def _designer_executable():
import winreg
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'Viewdraw.Application\CLSID') as key:
clsid = winreg.QueryValue(key, None)
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, rf'CLSID\{clsid}\LocalServer32',
0, winreg.KEY_READ | winreg.KEY_WOW64_32KEY) as key:
command = winreg.QueryValue(key, None)
# Mentor registers an absolute LocalServer32 path, sometimes quoted.
command = command.strip()
executable = command.split('"', 2)[1] if command.startswith('"') else command[:command.lower().index('.exe') + 4]
path = Path(executable)
if path.name.casefold() != 'viewdraw.exe' or not path.is_file():
raise WorkerMonitorError('registered DxDesigner executable is unavailable')
return path
class IsolatedCadSession:
"""The supervisor never attaches to COM on the user's input desktop."""
def __init__(self, root, *, abort_event=None):
self.root = Path(root).resolve()
self.token = uuid4().hex
self.desktop = PrivateDesktop('dx-' + self.token, enabled=True)
self.cad = None
self.binding = None
self.started = time.monotonic()
self.abort_event = abort_event
self.record = {'desktop': self.desktop.name, 'token': self.token, 'state': 'starting'}
def _record(self, **values):
self.record.update(values)
self.root.mkdir(parents=True, exist_ok=True)
target = self.root / 'private-desktop.json'
temporary = target.with_suffix('.tmp')
temporary.write_text(json.dumps(self.record, ensure_ascii=False, indent=2), encoding='utf-8')
_replace_record(temporary, target)
history = self.root / 'private-desktop-sessions'
history.mkdir(exist_ok=True)
archived = history / (self.token + '.json')
pending = archived.with_suffix('.tmp')
pending.write_text(json.dumps(self.record, ensure_ascii=False, indent=2), encoding='utf-8')
_replace_record(pending, archived)
def __enter__(self):
try:
self._check_abort()
self.desktop.__enter__()
self.cad = self.desktop.start_process((str(_designer_executable()),))
self._record(cad_pid=self.cad.pid)
bootstrap = self.root / ('cad-binding-' + self.token + '.json')
environment = dict(os.environ, DXPART_DESKTOP=self.desktop.name,
DXPART_CAD_PID=str(self.cad.pid), DXPART_SESSION_TOKEN=self.token)
environment.pop('DXPART_CAD_GUID', None)
probe = self.desktop.start_process(_helper_command('probe', bootstrap, self.cad.pid), env=_child_environment(environment),
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
deadline = time.monotonic() + 120
while probe.poll() is None:
self._check_abort()
if time.monotonic() >= deadline:
raise WorkerMonitorError('private CAD bootstrap timed out')
time.sleep(0.05)
code = probe.poll()
if code:
raise WorkerMonitorError('private CAD startup identity failed: ' + probe.stderr.read().decode('utf-8', errors='replace'))
finally:
probe.close()
result = json.loads(bootstrap.read_text(encoding='utf-8'))
self.binding = CadBinding(**result)
if (self.binding.pid, self.binding.desktop, self.binding.token) != (self.cad.pid, self.desktop.name, self.token):
raise WorkerMonitorError('private CAD bootstrap returned a foreign identity')
self._record(state='ready', guid=self.binding.guid, startup_seconds=time.monotonic() - self.started)
return self
except Exception as error:
try:
self.desktop.close()
except Exception as failure:
self._uncertain('startup cleanup failed: ' + str(failure))
raise WorkerMonitorError('private CAD startup cleanup requires reconciliation: ' + str(failure)) from error
self._record(state='released', clean=False, startup_error=str(error))
raise PrivateCadStartupError(str(error)) from error
def _check_abort(self):
if self.abort_event is not None and self.abort_event.is_set():
raise WorkerMonitorError('private CAD startup was cancelled before execution')
def start_worker(self, command, **options):
if self.binding is None or self.cad.poll() is not None:
raise WorkerMonitorError('owned private CAD is unavailable')
return self.desktop.start_process(command, env=_child_environment(self.binding.environment()), **options)
def __exit__(self, error_type, error, traceback):
closing_started = time.monotonic()
cleanup_error = None
try:
self._record(state='closing')
if error is not None:
self._uncertain(str(error))
if self.cad is not None and self.cad.poll() is not None:
raise WorkerMonitorError('owned CAD exited before the authorized quit request')
if self.cad is not None and self.binding is not None:
closing = self.desktop.start_process(_helper_command('quit', self.root / 'private-desktop.json', self.cad.pid),
env=_child_environment(self.binding.environment()), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
if closing.wait(timeout=20):
raise WorkerMonitorError('owned CAD refused orderly exit: ' + closing.stderr.read().decode('utf-8', errors='replace'))
if self.cad.wait(timeout=15) != 0:
raise WorkerMonitorError('owned CAD returned a nonzero exit code after quit')
finally:
closing.close()
except Exception as failure:
cleanup_error = failure
self._uncertain(str(failure))
finally:
try:
self.desktop.close()
self._record(state='released', clean=error is None and cleanup_error is None,
shutdown_seconds=time.monotonic() - closing_started)
except Exception as failure:
self._uncertain(str(failure))
cleanup_error = failure
if cleanup_error is not None:
raise WorkerMonitorError('private CAD cleanup requires reconciliation: ' + str(cleanup_error)) from cleanup_error
def _uncertain(self, message):
from .quick_run import _write_uncertain_flag
_write_uncertain_flag(self.root / 'uncertain.flag', 'private_desktop: ' + message)
self._record(state='uncertain', error=message)
def run_isolated_process(command, timeout, *, abort_event=None, cooperative_abort=False):
from .worker_monitor import run_monitored_process
try:
with IsolatedCadSession(Path(command[3]), abort_event=abort_event) as session:
return run_monitored_process(command, timeout, abort_event=abort_event, process_factory=session.start_worker,
**({'cooperative_abort': True} if cooperative_abort else {}))
except PrivateCadStartupError as error:
# The existing handoff recognizes exit=2 with unchanged status as a
# retryable pre-mutation startup failure, without an uncertainty lock.
return subprocess.CompletedProcess(command, 2, '', str(error))
def native_action(action, evidence, expected_pid):
"""Runs in a child created with lpDesktop, never in a Python thread switch."""
if action != 'probe':
return _native_action(action, evidence, expected_pid)
# COM startup can block inside a native call, so keep diagnostics outside
# the redirected pipes and retain them when the supervisor ends the child.
import faulthandler
with Path(str(evidence) + '.fault.txt').open('a', encoding='utf-8') as trace:
faulthandler.dump_traceback_later(20, repeat=True, file=trace)
try:
return _native_action(action, evidence, expected_pid)
finally:
faulthandler.cancel_dump_traceback_later()
def _native_action(action, evidence, expected_pid):
import pythoncom
import win32com.client
import win32gui
import win32process
pythoncom.CoInitialize()
try:
desktop = os.environ.get('DXPART_DESKTOP', '')
token = os.environ.get('DXPART_SESSION_TOKEN', '')
if not desktop.startswith('dx-') or current_desktop_name() != desktop:
raise ValueError('CAD bootstrap is not on the requested private desktop')
expected_pid = int(expected_pid)
if expected_pid <= 0 or str(expected_pid) != os.environ.get('DXPART_CAD_PID'):
raise ValueError('invalid CAD bootstrap PID')
deadline = time.monotonic() + 60
while True:
try:
app = win32com.client.GetActiveObject('Viewdraw.Application')
break
except pythoncom.com_error:
if action != 'probe' or time.monotonic() >= deadline:
raise
time.sleep(0.2)
if action == 'probe':
cad_windows = []
win32gui.EnumWindows(lambda handle, _: cad_windows.append(handle)
if win32process.GetWindowThreadProcessId(handle)[1] == expected_pid else None, None)
if not cad_windows:
raise ValueError('owned CAD has no windows on its private desktop')
# ROT is scoped to this desktop. Certify the freshly launched instance
# here; every subsequent VBS/helper attachment checks its GUID.
binding = CadBinding(desktop, expected_pid, str(app.Guid()), token)
verify_application(app, binding, require_view=False)
Path(evidence).write_text(json.dumps(asdict(binding)), encoding='utf-8')
elif action == 'quit':
binding = CadBinding.from_environment()
# ActiveViewHandle can retain a destroyed/reused HWND after closing
# the last project. The private ROT/GUID binds this empty instance.
verify_application(app, binding, require_view=False)
if project_file_path(app):
raise ValueError('owned CAD still has a project open; no implicit save or discard')
app.Quit()
else:
raise ValueError('unknown private CAD action')
finally:
pythoncom.CoUninitialize()
return 0
if __name__ == '__main__':
raise SystemExit(native_action(sys.argv[1], Path(sys.argv[2]), int(sys.argv[3])))
@@ -0,0 +1,449 @@
"""Owned Windows private-desktop process boundary for CAD and research workers.
This module deliberately contains no CAD automation. It only creates a
desktop, starts a process on that desktop, and closes resources it owns.
"""
from __future__ import annotations
from dataclasses import dataclass
from contextlib import ExitStack
import ctypes
from ctypes import wintypes
import math
import os
from pathlib import Path
import subprocess
import time
from typing import Mapping, Sequence
from .errors import TaskCenterError
@dataclass(frozen=True, slots=True)
class StartupInfo:
lpDesktop: str
def build_startup_info(desktop_name: str) -> StartupInfo:
if not desktop_name or "\\" in desktop_name or "\x00" in desktop_name:
raise TaskCenterError("private_desktop", "invalid private desktop name")
return StartupInfo(lpDesktop=f"winsta0\\{desktop_name}")
class _Win32Api:
def __init__(self) -> None:
try:
import win32api, win32con, win32event, win32job, win32process, win32service
except ImportError as error:
raise TaskCenterError("private_desktop", "pywin32 is required for private desktop supervision") from error
self.con, self.job, self.process, self.service = win32con, win32job, win32process, win32service
self.event = win32event
self.open_process = win32api.OpenProcess
self._pending_cleanup = []
def create_desktop(self, name: str):
return self.service.CreateDesktop(name, 0, self.con.GENERIC_ALL, None)
def confirm_desktop_released(self, name: str):
deadline = time.monotonic() + 2.0
while True:
# EnumDesktops avoids reopening/closing a handle which Windows may
# share with another desktop handle held by this process.
names = self.service.GetProcessWindowStation().EnumDesktops()
if name.casefold() not in {value.casefold() for value in names}:
return
if time.monotonic() >= deadline:
raise TaskCenterError('private_desktop_cleanup', 'owned private desktop still exists after cleanup')
time.sleep(0.05)
def create_process(self, command: Sequence[str], desktop: str, cwd: Path | None, env: Mapping[str, str] | None,
*, stdout=None, stderr=None):
startup = self.process.STARTUPINFO()
startup.lpDesktop = desktop
flags = self.con.CREATE_NO_WINDOW | self.con.CREATE_SUSPENDED
job = self.job.CreateJobObject(None, "")
process = None
try:
info = self.job.QueryInformationJobObject(job, self.job.JobObjectExtendedLimitInformation)
info["BasicLimitInformation"]["LimitFlags"] |= self.job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
self.job.SetInformationJobObject(job, self.job.JobObjectExtendedLimitInformation, info)
streams = (None, None)
if stdout is not None or stderr is not None:
(handle, thread, pid, _), streams = _create_redirected_process(command, desktop, cwd, env, flags, stdout, stderr)
else:
handle, thread, pid, _ = self.process.CreateProcess(
str(command[0]), subprocess.list2cmdline([str(item) for item in command]),
None, None, False, flags, env, str(cwd) if cwd else None, startup,
)
process = _Win32Process(self.process, self.job, self.event, handle, job, int(pid), command,
open_process=getattr(self, 'open_process', None))
process.stdout, process.stderr = streams
process.thread = thread
self.job.AssignProcessToJobObject(job, handle)
process.job_assigned = True
self.process.ResumeThread(thread)
thread.Close()
process.thread = None
except Exception as error:
try:
if process is not None:
# Assignment can fail before the job owns this suspended process.
process.close()
else:
job.Close()
except Exception as cleanup_error:
pending = getattr(self, '_pending_cleanup', None)
if pending is None:
self._pending_cleanup = pending = []
pending.append(process if process is not None else job)
raise TaskCenterError('private_desktop', f'launch failed: {error}; cleanup failed: {cleanup_error}') from error
raise
return process
def close_pending(self):
errors, remaining = [], []
for resource in getattr(self, '_pending_cleanup', []):
try:
resource.close() if isinstance(resource, _Win32Process) else resource.Close()
except Exception as error:
errors.append(error)
remaining.append(resource)
self._pending_cleanup = remaining
_raise_cleanup_errors(errors)
def _raise_cleanup_errors(errors):
if errors:
raise TaskCenterError('private_desktop_cleanup', '; '.join(str(error) for error in errors))
def _stop_and_wait(process):
errors = []
running = True
try:
running = process.poll() is None
except Exception as error:
errors.append(error)
if running:
try:
process.terminate()
except Exception as error:
errors.append(error)
try:
process.wait(timeout=5.0)
except Exception as error:
errors.append(error)
return errors
def _create_redirected_process(command, desktop, cwd, env, flags, stdout, stderr):
"""Use an explicit inheritance list; never inherit unrelated parent handles."""
import msvcrt
import pywintypes
class NativeStartup(ctypes.Structure):
_fields_ = [
('cb', wintypes.DWORD), ('lpReserved', wintypes.LPWSTR),
('lpDesktop', wintypes.LPWSTR), ('lpTitle', wintypes.LPWSTR),
('dwX', wintypes.DWORD), ('dwY', wintypes.DWORD),
('dwXSize', wintypes.DWORD), ('dwYSize', wintypes.DWORD),
('dwXCountChars', wintypes.DWORD), ('dwYCountChars', wintypes.DWORD),
('dwFillAttribute', wintypes.DWORD), ('dwFlags', wintypes.DWORD),
('wShowWindow', wintypes.WORD), ('cbReserved2', wintypes.WORD),
('lpReserved2', ctypes.POINTER(ctypes.c_byte)),
('hStdInput', wintypes.HANDLE), ('hStdOutput', wintypes.HANDLE), ('hStdError', wintypes.HANDLE),
]
class ExtendedStartup(ctypes.Structure):
_fields_ = [('StartupInfo', NativeStartup), ('lpAttributeList', ctypes.c_void_p)]
class ProcessInformation(ctypes.Structure):
_fields_ = [('hProcess', wintypes.HANDLE), ('hThread', wintypes.HANDLE),
('dwProcessId', wintypes.DWORD), ('dwThreadId', wintypes.DWORD)]
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
initialize = kernel.InitializeProcThreadAttributeList
initialize.argtypes = [ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD, ctypes.POINTER(ctypes.c_size_t)]
initialize.restype = wintypes.BOOL
update = kernel.UpdateProcThreadAttribute
update.argtypes = [ctypes.c_void_p, wintypes.DWORD, ctypes.c_size_t, ctypes.c_void_p,
ctypes.c_size_t, ctypes.c_void_p, ctypes.c_void_p]
update.restype = wintypes.BOOL
delete = kernel.DeleteProcThreadAttributeList
delete.argtypes = [ctypes.c_void_p]
delete.restype = None
create = kernel.CreateProcessW
create.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, ctypes.c_void_p, ctypes.c_void_p,
wintypes.BOOL, wintypes.DWORD, ctypes.c_void_p, wintypes.LPCWSTR,
ctypes.POINTER(ExtendedStartup), ctypes.POINTER(ProcessInformation)]
create.restype = wintypes.BOOL
readers = [None, None]
try:
with ExitStack() as children:
def output_handle(target, channel):
if target == subprocess.PIPE:
read_fd, write_fd = os.pipe()
readers[channel] = os.fdopen(read_fd, 'rb')
writer = children.enter_context(os.fdopen(write_fd, 'wb'))
elif target is None or target == subprocess.DEVNULL:
writer = children.enter_context(open(os.devnull, 'wb'))
else:
writer = children.enter_context(os.fdopen(os.dup(target.fileno()), 'wb'))
handle = msvcrt.get_osfhandle(writer.fileno())
os.set_handle_inheritable(handle, True)
return handle
stdin_file = children.enter_context(open(os.devnull, 'rb'))
stdin_handle = msvcrt.get_osfhandle(stdin_file.fileno())
os.set_handle_inheritable(stdin_handle, True)
stdout_handle = output_handle(stdout, 0)
stderr_handle = stdout_handle if stderr == subprocess.STDOUT else output_handle(stderr, 1)
handles = list(dict.fromkeys((stdin_handle, stdout_handle, stderr_handle)))
inherited = (wintypes.HANDLE * len(handles))(*handles)
size = ctypes.c_size_t()
initialize(None, 1, 0, ctypes.byref(size))
attributes = ctypes.create_string_buffer(size.value)
if not initialize(attributes, 1, 0, ctypes.byref(size)):
raise ctypes.WinError(ctypes.get_last_error())
try:
if not update(attributes, 0, 0x20002, inherited, ctypes.sizeof(inherited), None, None):
raise ctypes.WinError(ctypes.get_last_error())
startup = ExtendedStartup()
startup.StartupInfo.cb = ctypes.sizeof(startup)
startup.StartupInfo.lpDesktop = desktop
startup.StartupInfo.dwFlags = 0x100 # STARTF_USESTDHANDLES
startup.StartupInfo.hStdInput = stdin_handle
startup.StartupInfo.hStdOutput = stdout_handle
startup.StartupInfo.hStdError = stderr_handle
startup.lpAttributeList = ctypes.addressof(attributes)
information = ProcessInformation()
environment = None if env is None else ctypes.create_unicode_buffer(
'\0'.join(f'{key}={value}' for key, value in sorted(env.items(), key=lambda item: item[0].upper())) + '\0\0')
command_line = ctypes.create_unicode_buffer(subprocess.list2cmdline([str(item) for item in command]))
if not create(str(command[0]), command_line, None, None, True,
flags | 0x80000 | 0x400, environment, str(cwd) if cwd else None,
ctypes.byref(startup), ctypes.byref(information)):
raise ctypes.WinError(ctypes.get_last_error())
result = (pywintypes.HANDLE(information.hProcess), pywintypes.HANDLE(information.hThread),
information.dwProcessId, information.dwThreadId)
finally:
delete(attributes)
return result, readers
except BaseException:
for reader in readers:
if reader is not None:
reader.close()
raise
class _Win32Process:
def __init__(self, process_api, job_api, event_api, handle, job, pid: int, args, *, open_process=None):
self._process_api, self._job_api = process_api, job_api
self._event_api = event_api
self._open_process = open_process
self._descendant_handles = []
self._descendant_pids = set()
self.handle, self.job, self.pid = handle, job, pid
self.args = args
self.thread = None
self.job_assigned = False
self.returncode = None
self.stdout = self.stderr = None
def poll(self):
if self.returncode is not None or self.handle is None:
return self.returncode
status = self._event_api.WaitForSingleObject(self.handle, 0)
if status == 258: # WAIT_TIMEOUT: 259 is also a valid *completed* exit code.
return None
if status != 0:
raise OSError(f'process wait failed with status {status}')
self.returncode = self._process_api.GetExitCodeProcess(self.handle)
return self.returncode
def wait(self, timeout=None):
if self.returncode is not None:
return self.returncode
if self.handle is None:
raise OSError('owned process handle is closed before exit was confirmed')
milliseconds = 0xFFFFFFFF if timeout is None else min(max(math.ceil(timeout * 1000), 0), 0xFFFFFFFE)
status = self._event_api.WaitForSingleObject(self.handle, milliseconds)
if status == 258:
raise subprocess.TimeoutExpired(self.args, timeout)
if status != 0:
raise OSError(f'process wait failed with status {status}')
self.returncode = self._process_api.GetExitCodeProcess(self.handle)
return self.returncode
def terminate(self):
if self.handle is None:
return
if not self.job_assigned:
self._process_api.TerminateProcess(self.handle, 1)
return
errors = []
try:
self._remember_descendants()
except Exception as error:
errors.append(error)
try:
self._job_api.TerminateJobObject(self.job, 1)
except Exception:
self._process_api.TerminateProcess(self.handle, 1)
_raise_cleanup_errors(errors)
kill = terminate
def _remember_descendants(self):
if self._open_process is None or self.job is None:
return
for pid in self._job_api.QueryInformationJobObject(self.job, self._job_api.JobObjectBasicProcessIdList):
if pid == self.pid or pid in self._descendant_pids:
continue
try:
self._descendant_handles.append(self._open_process(0x100000, False, pid))
self._descendant_pids.add(pid)
except Exception as error:
# pywintypes.error is not an OSError. A child that exited
# between the job snapshot and OpenProcess reports error 87.
code = getattr(error, 'winerror', None)
if code is None and error.args:
code = error.args[0]
if code != 87:
raise
def close(self):
errors = []
if self.handle is not None:
errors.extend(_stop_and_wait(self))
deadline = time.monotonic() + 5.0
if self.job is not None and self.job_assigned:
try:
# A completed root can leave grandchildren holding the desktop.
self._remember_descendants()
self._job_api.TerminateJobObject(self.job, 1)
while self._job_api.QueryInformationJobObject(
self.job, self._job_api.JobObjectBasicAccountingInformation,
)['ActiveProcesses']:
if time.monotonic() >= deadline:
raise TimeoutError('owned job descendants did not exit within 5 seconds')
time.sleep(0.01)
except Exception as error:
errors.append(error)
retained = []
for descendant in self._descendant_handles:
try:
# Job accounting can reach zero before a terminated process is signaled.
remaining = max(0, math.ceil((deadline - time.monotonic()) * 1000))
if self._event_api.WaitForSingleObject(descendant, remaining) != 0:
raise TimeoutError('owned job descendant exit was not confirmed within 5 seconds')
except Exception as error:
errors.append(error)
retained.append(descendant)
continue
try:
descendant.Close()
except Exception as error:
errors.append(error)
retained.append(descendant)
self._descendant_handles = retained
for name in ('job', 'thread', 'handle'):
handle = getattr(self, name)
if name == 'handle' and self.returncode is None:
# Keep the only termination/wait capability until cleanup can retry.
continue
if handle is not None:
try:
handle.Close()
setattr(self, name, None)
except Exception as error:
errors.append(error)
for stream in (self.stdout, self.stderr):
if stream is not None:
try:
stream.close()
except Exception as error:
errors.append(error)
_raise_cleanup_errors(errors)
class PrivateDesktop:
"""Own a private Windows desktop and processes started on it."""
def __init__(self, name: str, *, enabled: bool = False, api=None) -> None:
self.name = name
self.enabled = enabled
self._handle = None
self._processes: list[subprocess.Popen[str]] = []
self._api = api
def __enter__(self) -> "PrivateDesktop":
if not self.enabled:
raise TaskCenterError("private_desktop_opt_in", "private desktop backend requires explicit opt-in")
self._create()
if self._handle is None:
raise TaskCenterError("private_desktop", "private desktop could not be created")
return self
def __exit__(self, *_exc: object) -> None:
self.close()
def _create(self) -> None:
if os.name != "nt" and self._api is None:
return
self._api = self._api or _Win32Api()
self._handle = self._api.create_desktop(self.name)
def start_process(
self,
command: Sequence[str],
*,
cwd: Path | None = None,
env: Mapping[str, str] | None = None,
stdout=None,
stderr=None,
) -> subprocess.Popen[str]:
if not self.enabled or self._handle is None:
raise TaskCenterError("private_desktop", "process launch requires an owned private desktop")
if not command:
raise TaskCenterError("private_desktop", "private desktop command is empty")
if self._api is None:
raise TaskCenterError("private_desktop", "private desktop process API is unavailable")
options = {} if stdout is None and stderr is None else {'stdout': stdout, 'stderr': stderr}
process = self._api.create_process(command, build_startup_info(self.name).lpDesktop, cwd, env, **options)
self._processes.append(process)
return process
def close(self) -> None:
errors, remaining = [], []
for process in reversed(self._processes):
process_errors = _stop_and_wait(process)
errors.extend(process_errors)
failed = bool(process_errors)
try:
process.close()
except Exception as error:
errors.append(error)
failed = True
if failed:
remaining.append(process)
self._processes = list(reversed(remaining))
close_pending = getattr(self._api, 'close_pending', None)
if close_pending:
try:
close_pending()
except Exception as error:
errors.append(error)
close_desktop = getattr(self._handle, "CloseDesktop", None)
if close_desktop:
try:
close_desktop()
self._handle = None
except Exception as error:
errors.append(error)
confirm = getattr(self._api, 'confirm_desktop_released', None)
if confirm and self._handle is None:
try:
confirm(self.name)
except Exception as error:
errors.append(error)
_raise_cleanup_errors(errors)
@@ -0,0 +1,137 @@
"""Legacy research-only request protocol; production uses isolated_cad.
The worker writes versioned request/evidence files and delegates process
launching to an injected callback. It never attaches to an existing CAD
process and does not perform CAD writes itself.
"""
from __future__ import annotations
from dataclasses import dataclass, asdict
import hashlib
import json
from pathlib import Path
from typing import Callable
from .errors import TaskCenterError
from .isolated_desktop import PrivateDesktop
@dataclass(frozen=True, slots=True)
class IsolatedWorkerRequest:
protocol_version: str
task_id: str
project_path: Path
target_uids: tuple[str, ...]
plan_hash: str
allow_writes: bool = False
@dataclass(frozen=True, slots=True)
class IsolatedWorkerEvidence:
protocol_version: str
task_id: str
state: str
request_hash: str
cad_pid: int | None = None
project_path: str | None = None
message: str = ""
@dataclass(frozen=True, slots=True)
class CadIdentity:
pid: int
project_path: Path
class IsolatedDesktopWorker:
"""An explicit opt-in supervision boundary; disabled by default."""
protocol_version = "1"
def __init__(
self,
*,
enabled: bool = False,
desktop_factory: Callable[[str], PrivateDesktop] | None = None,
existing_cad_validator: Callable[[Path], bool] | None = None,
) -> None:
self.enabled = enabled
self._desktop_factory = desktop_factory or (lambda name: PrivateDesktop(name, enabled=True))
self._existing_cad_validator = existing_cad_validator or (lambda _path: False)
@staticmethod
def request_hash(request: IsolatedWorkerRequest) -> str:
payload = json.dumps(_json_request(request), sort_keys=True, separators=(",", ":")).encode()
return hashlib.sha256(payload).hexdigest()
def run(self, request: IsolatedWorkerRequest, *, evidence_root: Path | None = None) -> IsolatedWorkerEvidence:
if not self.enabled:
raise TaskCenterError("private_desktop_opt_in", "isolated worker is research-only and requires explicit opt-in")
self._validate_request(request)
if self._existing_cad_validator(request.project_path):
raise TaskCenterError("isolated_cad_attachment", "an unrelated CAD process is already associated with this project")
digest = self.request_hash(request)
root = Path(evidence_root) if evidence_root is not None else None
if root is not None:
root.mkdir(parents=True, exist_ok=True)
(root / "request.json").write_text(json.dumps(_json_request(request), indent=2), encoding="utf-8")
evidence = IsolatedWorkerEvidence(self.protocol_version, request.task_id, "prepared", digest, project_path=str(request.project_path))
if root is not None:
(root / "evidence.json").write_text(json.dumps(asdict(evidence), indent=2), encoding="utf-8")
return evidence
def read_only_probe(
self,
request: IsolatedWorkerRequest,
cad_probe: Callable[[Path], CadIdentity],
*,
evidence_root: Path | None = None,
) -> IsolatedWorkerEvidence:
"""Validate an injected callback result; this does not move CAD desktops.
The callback is the only native integration point and must return the
PID and project identity it observed. Tests inject it; production can
later provide a COM reader without changing the request contract.
"""
prepared = self.run(request, evidence_root=evidence_root)
desktop = self._desktop_factory(f"dx-{request.task_id[:12]}")
try:
with desktop:
identity = cad_probe(request.project_path)
except TaskCenterError:
raise
except Exception as error:
raise TaskCenterError("isolated_probe", "private desktop read-only probe failed") from error
if identity.pid <= 0 or Path(identity.project_path).resolve(strict=False) != request.project_path.resolve(strict=False):
raise TaskCenterError("isolated_cad_identity", "read-only probe did not validate CAD PID/project identity")
evidence = IsolatedWorkerEvidence(
self.protocol_version, request.task_id, "read_only_verified", prepared.request_hash,
cad_pid=identity.pid, project_path=str(identity.project_path),
message="read-only CAD identity verified",
)
if evidence_root is not None:
root = Path(evidence_root)
(root / "evidence.json").write_text(json.dumps(asdict(evidence), indent=2), encoding="utf-8")
return evidence
def _validate_request(self, request: IsolatedWorkerRequest) -> None:
if request.protocol_version != self.protocol_version:
raise TaskCenterError("isolated_protocol", "unsupported isolated worker protocol")
if not request.task_id or not request.project_path:
raise TaskCenterError("isolated_request", "task and project are required")
if any(not uid or "\x00" in uid for uid in request.target_uids):
raise TaskCenterError("isolated_request", "target UID is invalid")
if request.allow_writes:
raise TaskCenterError("isolated_write_boundary", "research worker cannot enable CAD writes")
def _json_request(request: IsolatedWorkerRequest) -> dict[str, object]:
return {
"protocol_version": request.protocol_version,
"task_id": request.task_id,
"project_path": str(request.project_path),
"target_uids": list(request.target_uids),
"plan_hash": request.plan_hash,
"allow_writes": request.allow_writes,
}
@@ -0,0 +1,156 @@
"""Short access paths for legacy WSH without relocating task evidence."""
from __future__ import annotations
import atexit
import ctypes
import csv
import hashlib
import os
from pathlib import Path
import tempfile
from threading import RLock
from .errors import TaskCenterError
def _short_path(path: Path) -> str | None:
function = ctypes.WinDLL('kernel32', use_last_error=True).GetShortPathNameW
function.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint]
function.restype = ctypes.c_uint
buffer = ctypes.create_unicode_buffer(32768)
count = function(str(path), buffer, len(buffer))
return buffer.value if count and count < len(buffer) else None
def _fits(root) -> bool:
# Leave room for snapshot/job suffixes and monitor handshakes.
return len(str(root)) + 100 < 260
class _AliasPool:
def __init__(self):
self.directory = None
self.links = {}
self.lock = RLock()
def alias(self, root: Path) -> Path:
import _winapi
with self.lock:
if self.directory is None:
local = Path(os.environ.get('LOCALAPPDATA') or tempfile.gettempdir())
parent = local / 'DxProductivity' / 'path-links'
parent.mkdir(parents=True, exist_ok=True)
self.directory = Path(tempfile.mkdtemp(prefix='dxp-', dir=parent))
key = hashlib.sha256(os.path.normcase(str(root)).encode('utf-8')).hexdigest()[:20]
link = self.directory / key
if not _fits(link):
raise OSError('the per-user compatibility directory is also too long')
if link not in self.links:
# Junction creation needs no symbolic-link privilege. The
# junction contains no copies and never changes the target.
_winapi.CreateJunction(str(root), str(link))
self.links[link] = root
if not link.is_junction() or link.resolve(strict=True) != root:
raise OSError('compatibility directory no longer points to the confirmed evidence')
return link
def close(self):
errors = []
with self.lock:
for link, target in tuple(self.links.items()):
try:
if link.is_junction():
if link.resolve() != target:
raise OSError('refusing to remove a redirected compatibility directory')
link.rmdir() # Remove only the link, never the target tree.
elif link.exists():
raise OSError('refusing to remove a non-junction compatibility directory')
del self.links[link]
except OSError as error:
errors.append(error)
if self.directory is not None and not self.links:
try:
self.directory.rmdir()
self.directory = None
except OSError as error:
errors.append(error)
return errors
_aliases = _AliasPool()
def cleanup_worker_aliases():
return _aliases.close()
atexit.register(cleanup_worker_aliases)
def worker_paths(script: Path, root: Path) -> tuple[str, str]:
if os.name == 'nt':
_prepare_project_access(root)
if os.name != 'nt' or _fits(root):
return str(script), str(root)
canonical = root.resolve(strict=True)
short = _short_path(canonical)
if short and _fits(short):
return str(Path(short) / script.name), short
try:
alias = _aliases.alias(canonical)
except OSError as error:
raise TaskCenterError('quick_run_path_length',
f'无法建立长路径兼容入口:{error};尚未启动 CAD 操作。') from error
return str(alias / script.name), str(alias)
def _prepare_project_access(root: Path):
"""Keep command identities canonical while giving legacy CAD short entry paths."""
command = root / 'command.tsv'
if not command.is_file():
return
rows = []
with command.open(encoding='utf-8-sig', newline='') as stream:
for row in csv.DictReader(stream, delimiter='\t'):
value = row.get('project_path')
if not value:
continue
project = Path(value).resolve(strict=False)
if (_fits(project.parent) and len(str(project)) < 260) or not project.is_file():
continue
short = _short_path(project)
if short and _fits(Path(short).parent) and len(short) < 260:
access = Path(short)
else:
access = _aliases.alias(project.parent) / project.name
if not _fits(access.parent) or len(str(access)) >= 260 or access.resolve(strict=True) != project:
raise TaskCenterError('quick_run_path_length', '工程短路径入口不能与原工程身份对应,未启动 CAD 操作。')
pair = (str(project), str(access))
if pair not in rows:
rows.append(pair)
target = root / 'project-access.tsv'
if rows or target.exists():
temporary = target.with_suffix('.tmp')
with temporary.open('w', encoding='utf-8', newline='') as stream:
writer = csv.writer(stream, delimiter='\t', lineterminator='\n')
writer.writerow(('project_path', 'access_path'))
writer.writerows(rows)
temporary.replace(target)
def validate_project_access(root: Path):
"""Reject disappeared/redirected entry paths before and after a native worker."""
target = Path(root) / 'project-access.tsv'
if not target.is_file():
return
with target.open(encoding='utf-8-sig', newline='') as stream:
reader = csv.DictReader(stream, delimiter='\t')
if reader.fieldnames != ['project_path', 'access_path']:
raise TaskCenterError('target_identity', '工程路径入口清单格式已改变')
for row in reader:
try:
same = Path(row['access_path']).resolve(strict=True) == Path(row['project_path']).resolve(strict=True)
except (OSError, ValueError, KeyError):
same = False
if not same:
raise TaskCenterError('target_identity', '工程短路径入口已失效或指向其他工程,拒绝使用采集或替换结果')
@@ -3,6 +3,7 @@
from __future__ import annotations
from dataclasses import dataclass, field
from collections import OrderedDict
from datetime import datetime, timezone
import hashlib
import json
@@ -47,6 +48,7 @@ class LoggingContext:
application_log_path: Path
logger: logging.Logger
_event_lock: threading.RLock = field(default_factory=threading.RLock, repr=False)
_event_sequences: OrderedDict = field(default_factory=OrderedDict, repr=False)
def report_exception(
self,
@@ -128,7 +130,11 @@ def append_task_event(
raise TaskCenterError("event_details", "task event details must be JSON-compatible") from error
path = task_directory / "events.jsonl"
with context._event_lock:
sequence = _next_event_sequence(path)
# Reuse only a sequence belonging to this exact, unchanged file. External
# appends, rotation, truncation and replacement fall back to the disk tail.
cached = context._event_sequences.pop(path, None)
stamp = _event_file_stamp(path)
sequence = cached[1] if cached is not None and stamp is not None and cached[0] == stamp else _next_event_sequence(path)
event = {
"sequence": sequence,
"timestamp_utc": _utc_now_text(),
@@ -153,6 +159,14 @@ def append_task_event(
handle.write(encoded)
handle.flush()
os.fsync(handle.fileno())
written = os.fstat(handle.fileno())
final = _event_file_stamp(path)
# Windows fstat/Path.stat differ in ctime semantics; retain the full
# Path stamp only after handle identity, size and mtime agree.
if final is not None and final[:4] == (written.st_dev, written.st_ino, written.st_size, written.st_mtime_ns):
context._event_sequences[path] = (final, sequence + 1)
while len(context._event_sequences) > 64:
context._event_sequences.popitem(last=False)
except OSError as error:
raise TaskCenterError("event_write_failed", "cannot append task event") from error
context.logger.log(
@@ -167,6 +181,14 @@ def append_task_event(
return event
def _event_file_stamp(path):
try:
info = path.stat()
return info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns
except OSError:
return None
def capture_subprocess_output(
context: LoggingContext,
*,
@@ -45,6 +45,10 @@ class TaskRecord:
error_id: str | None = None
summary: str = ""
copy_part_number_to_value: bool = False
group_id: str | None = None
group_position: int = 0
primary_project_id: str | None = None
target_plan_mode: bool = False
@dataclass(frozen=True, slots=True)
@@ -1,5 +1,6 @@
"""Native current-sheet replacement adapter for the existing QuickPartReplace runner."""
import argparse
import faulthandler
import ctypes
import hashlib
import json
@@ -34,11 +35,11 @@ def read_snapshot(path):
for line in Path(path).read_text(encoding="utf-8-sig").splitlines() if line]
metadata = [row for row in rows if row[0] == "M"]
components = [row for row in rows if row[0] == "C"]
if len(metadata) != 1 or len(metadata[0]) not in {5, 6, 8} or not components:
if len(metadata) != 1 or len(metadata[0]) not in {5, 6, 8, 10} or not components:
raise ValueError("Incomplete snapshot")
if len(metadata[0]) >= 6 and metadata[0][5] not in {"preserve", "part_label", "part_number", "custom"}:
raise ValueError("Invalid snapshot Value policy")
if len(metadata[0]) == 8:
if len(metadata[0]) >= 8:
if metadata[0][7] not in {"0", "1"} or (metadata[0][5] == "custom") != bool(metadata[0][6]):
raise ValueError("Invalid snapshot Value or NC option")
if any(len(row) != 8 for row in components):
@@ -47,6 +48,8 @@ def read_snapshot(path):
raise ValueError("Duplicate snapshot UID")
if metadata[0][2].casefold() == metadata[0][3].casefold():
raise ValueError("Source and target must differ")
if len(metadata[0]) == 10 and (metadata[0][8] != "targets" or not metadata[0][9]):
raise ValueError("Target snapshot has no selector")
return metadata[0], components
@@ -71,6 +74,7 @@ def transaction_binding(snapshot, metadata, records, library_row, symbol, slot_c
"old_part_number": metadata[2],
"new_part_number": metadata[3],
"source_uids": sorted(row[1] for row in records),
"target_selectors": metadata[9] if len(metadata) == 10 else None,
"library_row": [str(value) for value in library_row],
"target_symbol": str(symbol),
"slot_count": slots,
@@ -93,6 +97,7 @@ def require_resumable_transaction(snapshot, report, metadata, records):
"old_part_number": metadata[2],
"new_part_number": metadata[3],
"source_uids": sorted(row[1] for row in records),
"target_selectors": metadata[9] if len(metadata) == 10 else None,
}
if not isinstance(binding, dict) or any(binding.get(key) != value for key, value in expected.items()):
raise ValueError("Native replacement evidence does not match this snapshot")
@@ -201,6 +206,8 @@ def attach():
api = win32com.client.gencache.EnsureModule(
"{4ADEF4E1-690A-11CE-9261-0020C5E26659}", 0, 1, 0)
app = api.IVdApp(win32com.client.GetActiveObject("Viewdraw.Application")._oleobj_)
from .cad_identity import verify_application, project_file_path
verify_application(app)
return app, api
@@ -222,7 +229,9 @@ def components_on_sheet(app, api):
def check_active_context(app, metadata):
if os.path.normcase(os.path.abspath(app.GetProjectData().GetProjectFilePath())) != os.path.normcase(os.path.abspath(metadata[1])):
from .cad_identity import verify_application, project_file_path
verify_application(app)
if Path(project_file_path(app)).resolve() != Path(metadata[1]).resolve():
raise ValueError("Active project changed")
if f"{app.ActiveView.GetName(0)}:{app.ActiveView.Block.SheetNum}" != metadata[4]:
raise ValueError("Active sheet changed")
@@ -232,15 +241,63 @@ def check_context(app, api, metadata, records, require_selection=True):
check_active_context(app, metadata)
components = components_on_sheet(app, api)
wanted = {row[1] for row in records}
actual = {str(component.UID) for component in components if attribute_value(component, "Part Number").casefold() == metadata[2].casefold()}
if actual != wanted:
raise ValueError(f"Source batch changed since snapshot: expected={sorted(wanted)!r} actual={sorted(actual)!r}")
by_uid = {str(component.UID): component for component in components}
if len(by_uid) != len(components):
raise ValueError("Duplicate component UID on sheet")
if len(metadata) == 10:
selectors = _target_selectors(metadata[9])
if set(selectors) != wanted:
raise ValueError("Target selector differs from snapshot components")
for uid, (refdes, old_value) in selectors.items():
component = by_uid.get(uid)
if (component is None or str(component.Refdes) != refdes or
attribute_value(component, "Part Number").casefold() != metadata[2].casefold() or
attribute_value(component, "Value") != old_value):
raise ValueError("Selected target changed since inventory")
else:
actual = {str(component.UID) for component in components if attribute_value(component, "Part Number").casefold() == metadata[2].casefold()}
if actual != wanted:
raise ValueError(f"Source batch changed since snapshot: expected={sorted(wanted)!r} actual={sorted(actual)!r}")
selected = {str(api.IVdComp(component._oleobj_).UID) for component in app.ActiveView.Query(128, 1)}
if require_selection and selected != wanted:
raise ValueError(f"Selected component set differs from snapshot: expected={sorted(wanted)!r} actual={sorted(selected)!r}")
return components
def _target_selectors(value):
result = {}
for item in value.split("\x1e"):
fields = item.split("\x1f")
if len(fields) != 3 or not fields[0] or not fields[1] or fields[0] in result:
raise ValueError("Target selector is malformed")
result[fields[0]] = (fields[1], fields[2])
if not result:
raise ValueError("Target selector is empty")
return result
def verify_unselected_snapshot(snapshot, components, selected_uids):
"""Compare the full identity/value baseline for components outside target scope."""
selected_uids = {str(uid) for uid in selected_uids}
rows = [line.split("\t") for line in Path(snapshot).read_text(encoding="utf-8-sig").splitlines()
if line.startswith("U\t")]
if any(len(row) != 7 for row in rows):
raise ValueError("Unselected component baseline is malformed")
baseline = {decode(row[1]): tuple(decode(value) for value in row[2:]) for row in rows}
if len(baseline) != len(rows):
raise ValueError("Duplicate unselected component UID")
current = {}
for component in components:
uid = str(component.UID)
if uid in selected_uids:
continue
current[uid] = (str(component.Refdes), *(attribute_value(component, name)
for name in ("Part Number", "Value", "Part Name", "Part Label")))
if baseline != current:
raise ValueError("An unselected component was changed")
return True
def select_snapshot_batch(app, api, metadata, records):
components = check_context(app, api, metadata, records, require_selection=False)
wanted = {row[1] for row in records}
@@ -277,14 +334,21 @@ def existing_replacement_uids(components, records, target, binding, require_part
return matches
def promote_pin_numbers(app, api, replacement_uids, slot_count=1):
def promote_pin_numbers(app, api, replacement_uids, slot_count=1, on_progress=None):
def progress(phase):
if on_progress:
on_progress(phase)
progress('query_components')
components = components_on_sheet(app, api)
replacement_uids = set(replacement_uids)
try:
progress('select_replacements')
for component in components:
selection(component, str(component.UID) in replacement_uids)
for slot in range(1, int(slot_count) + 1):
progress(f'promote_slot_{slot}')
app.ActiveView.Block.PromoteSymbolNumbers(1, slot)
progress('query_promoted_pins')
promoted = []
for item in app.ActiveView.Query(4096, 0):
pin = api.IVdCmpPin(item._oleobj_)
@@ -296,8 +360,15 @@ def promote_pin_numbers(app, api, replacement_uids, slot_count=1):
raise ValueError("Replacement produced no pins")
return promoted
finally:
progress('deselect_components')
for component in components:
selection(component, False)
progress('promotion_complete')
def _promotion_phase(snapshot, report, phase):
report['pin_promotion_phase'] = phase
save_report(snapshot, report)
def replacement_matches(components, records, target, require_part_label):
@@ -344,10 +415,12 @@ def run_native(snapshot, report):
check_active_context(app, metadata)
components = components_on_sheet(app, api)
wanted = {row[1] for row in records}
if len(metadata) == 10:
verify_unselected_snapshot(snapshot, components, wanted)
source_uids = {
str(component.UID)
for component in components
if attribute_value(component, "Part Number").casefold() == metadata[2].casefold()
if str(component.UID) in wanted and attribute_value(component, "Part Number").casefold() == metadata[2].casefold()
}
if source_uids != wanted:
binding = require_resumable_transaction(snapshot, report, metadata, records)
@@ -362,13 +435,17 @@ def run_native(snapshot, report):
slot_count = int(binding.get("slot_count", report.get("slot_count", 1)))
if slot_count < 1:
raise ValueError("Recorded replacement has no valid slots")
report["promoted_pins"] = promote_pin_numbers(app, api, report["replaced_uids"], slot_count)
report["promoted_pins"] = promote_pin_numbers(app, api, report["replaced_uids"], slot_count,
lambda phase: _promotion_phase(snapshot, report, phase))
report["already_replaced"] = True
report["stage"] = "native_replace_verified"
return
components = select_snapshot_batch(app, api, metadata, records)
before_uids = {str(component.UID) for component in components}
untouched = {str(component.UID): attribute_value(component, "Part Number") for component in components if str(component.UID) not in wanted}
untouched = {str(component.UID): (
str(component.Refdes),
*(attribute_value(component, name) for name in ("Part Number", "Value", "Part Name", "Part Label"))
) for component in components if str(component.UID) not in wanted}
view_handle = int(app.ActiveViewHandle)
process_id = win32process.GetWindowThreadProcessId(view_handle)[1]
main_handle = win32gui.GetAncestor(view_handle, 2)
@@ -536,11 +613,18 @@ def run_native(snapshot, report):
selected_replaced, "Native replacement did not complete", timeout=30
)
current = components_on_sheet(app, api)
if len(metadata) == 10:
verify_unselected_snapshot(snapshot, current, wanted)
if len(current) != len(before_uids):
raise ValueError("Component count changed during replacement")
current_by_uid = {str(component.UID): component for component in current}
for uid, number in untouched.items():
if uid not in current_by_uid or attribute_value(current_by_uid[uid], "Part Number") != number:
for uid, identity in untouched.items():
component = current_by_uid.get(uid)
current_identity = None if component is None else (
str(component.Refdes),
*(attribute_value(component, name) for name in ("Part Number", "Value", "Part Name", "Part Label"))
)
if current_identity != identity:
raise ValueError("An unselected component was changed")
verified_uids = replacement_matches(current, records, metadata[3], require_part_label)
if verified_uids is None or set(verified_uids) != set(report["replaced_uids"]):
@@ -549,7 +633,8 @@ def run_native(snapshot, report):
save_report(snapshot, report)
report["stage"] = "pin_promotion_started"
save_report(snapshot, report)
report["promoted_pins"] = promote_pin_numbers(app, api, report["replaced_uids"], slot_count)
report["promoted_pins"] = promote_pin_numbers(app, api, report["replaced_uids"], slot_count,
lambda phase: _promotion_phase(snapshot, report, phase))
report["stage"] = "native_replace_verified"
finally:
if dialog and win32gui.IsWindow(dialog):
@@ -576,13 +661,23 @@ def atomic_text(path, text):
handle.write(text)
handle.flush()
os.fsync(handle.fileno())
os.replace(temporary, path)
deadline = time.monotonic() + 1.0
while True:
try:
os.replace(temporary, path)
break
except PermissionError:
if time.monotonic() >= deadline:
raise
time.sleep(.02)
finally:
temporary.unlink(missing_ok=True)
def run(snapshot):
snapshot = Path(snapshot)
fault_stream = Path(str(snapshot) + '.native.fault.txt').open('a', encoding='utf-8')
faulthandler.enable(file=fault_stream, all_threads=True)
report_path = Path(str(snapshot) + ".native.json")
report = {}
if report_path.is_file():
@@ -613,7 +708,15 @@ def run(snapshot):
return 1
finally:
watchdog.cancel()
save_report(snapshot, report)
try:
save_report(snapshot, report)
except Exception:
traceback.print_exc(file=fault_stream)
fault_stream.flush()
raise
finally:
faulthandler.disable()
fault_stream.close()
def main(argv=None):
@@ -0,0 +1,130 @@
"""Explicit completed-round archival; previous handoffs never become resumable."""
from dataclasses import asdict
import json
import os
from pathlib import Path
from uuid import uuid4
from .errors import TaskCenterError
from .models import ProjectStatus, TaskStatus
from .target_plan import compile_target_rules
def _write(path, value):
temporary = path.with_name(f'.{path.name}.{uuid4().hex}.tmp')
try:
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, default=str), encoding='utf-8')
with temporary.open('r+b') as stream:
os.fsync(stream.fileno())
temporary.replace(path)
finally:
temporary.unlink(missing_ok=True)
def recover_archives(service):
"""Recover a process exit between atomic directory moves and the DB commit."""
for journal in (service._logging.root / 'round-transitions').glob('*/journal.json'):
if (journal.parent / 'committed').exists() or (journal.parent / 'rolled-back').exists():
continue
value = json.loads(journal.read_text(encoding='utf-8'))
committed = service._store.round_committed(journal.parent.name)
if committed:
(journal.parent / 'committed').touch()
continue
# The database transaction is atomic, so an uncommitted journal restores
# the original current handoff. Never merge or overwrite newer files.
for source, destination in reversed(value['moves']):
source, destination = Path(source), Path(destination)
if destination.exists():
if source.exists():
raise TaskCenterError('round_recovery', '新一轮归档恢复发生目录冲突,请保留证据并检查归档日志。')
destination.rename(source)
(journal.parent / 'rolled-back').touch()
def start_new_round(service, task_id):
recover_archives(service)
transition = {}
try:
# Include the actual COMMIT boundary, not only the SQL/reset body.
with service._store.transaction():
tasks, journal_root = _stage_new_round(service, task_id, transition)
except BaseException:
if transition:
_restore_moves(transition['moves'])
(transition['journal_root'] / 'rolled-back').touch()
raise
(journal_root / 'committed').touch()
return tasks
def _restore_moves(moves):
for source, destination in reversed(moves):
source, destination = Path(source), Path(destination)
if destination.exists():
if source.exists():
raise TaskCenterError('round_recovery', '归档回滚目录冲突,请保留证据并检查日志。')
destination.rename(source)
def _stage_new_round(service, task_id, transition):
store = service._store
with store.transaction():
task = store.get_task(task_id)
if task.status is not TaskStatus.COMPLETED:
raise TaskCenterError('new_round_state', '只有已完成任务可以开始新一轮;当前轮次不会重复重置。')
if store.has_active_project():
raise TaskCenterError('active_project_exists', '请先完成当前活动工程。')
members = (tuple(t for t in store.list_project_group(task.group_id) if t.status is not TaskStatus.DELETED)
if task.group_id else (task,))
completed = tuple(t for t in members if t.status is TaskStatus.COMPLETED)
for member in members:
facade = service._project_task_service(member.task_id)
root = facade._quick_run_preparer.data_root / 'quick-run'
rules = (compile_target_rules(store.list_target_plan(member.task_id))
if member.target_plan_mode else store.list_rules(member.task_id))
snapshot = facade._quick_run_preparer.read_snapshot(member.task_id,
store.list_projects(member.task_id), rules,
copy_part_number_to_value=member.copy_part_number_to_value)
if snapshot.interrupted or (root / 'uncertain.flag').exists():
raise TaskCenterError('new_round_interrupted', '同批任务有中断或不确定结果,请先核验恢复。')
if member.status is not TaskStatus.COMPLETED:
if member.status not in {TaskStatus.DRAFT, TaskStatus.READY} or snapshot.has_evidence:
raise TaskCenterError('new_round_batch_active', '同批任务仍有执行记录,请先完成或核验;未执行的草稿可以保留。')
continue
selected = tuple(p for p in store.list_projects(member.task_id) if p.selected)
if not selected or any(p.status is not ProjectStatus.COMPLETED for p in selected):
raise TaskCenterError('new_round_unverified', '工程尚未全部校验完成,不能开始新一轮。')
if snapshot.has_evidence and (not snapshot.progress.queue_complete or snapshot.progress.failed_items):
raise TaskCenterError('new_round_unverified', '替换队列尚未校验完成,不能开始新一轮。')
round_id = uuid4().hex
summary = f'new round {round_id}: collect current inventory before execution'
journal_root = service._logging.root / 'round-transitions' / round_id
journal_root.mkdir(parents=True)
moves, archives = [], []
for member in completed:
root = service._project_task_service(member.task_id)._quick_run_preparer.data_root
archive = root / 'rounds' / round_id
archive.mkdir(parents=True)
archives.append(archive)
_write(archive / 'plan.json', dict(task=asdict(member),
projects=[asdict(p) for p in store.list_projects(member.task_id)],
rules=[asdict(r) for r in store.list_rules(member.task_id)],
targets=[asdict(r) for r in store.list_target_plan(member.task_id)]))
for name in ('quick-run', 'quick-run-history'):
if (root / name).exists():
moves.append((str(root / name), str(archive / name)))
_write(journal_root / 'journal.json', dict(task_ids=[t.task_id for t in completed],
summary=summary, moves=moves, archives=[str(path) for path in archives]))
transition.update(moves=moves, journal_root=journal_root)
for source, destination in moves:
Path(source).rename(destination)
for member in completed:
store.reset_completed_round(member.task_id, summary)
store.record_round_commit(round_id)
return tuple(store.get_task(t.task_id) for t in completed), journal_root
def latest_archive(preparer):
plans = tuple((preparer.data_root / 'rounds').glob('*/plan.json'))
return max(plans, key=lambda path: path.stat().st_mtime_ns).parent if plans else None
@@ -0,0 +1,16 @@
"""Cooperative read-only operation control, independent of Qt and CAD."""
from .errors import TaskCenterError
def check_cancelled(stop_event):
if stop_event is not None and stop_event.is_set():
raise TaskCenterError('operation_cancelled', '已取消采集;当前私有 CAD 会话已安全收尾,未保存部分计划。')
def control_options(stop_event=None, on_progress=None):
return {key: value for key, value in (('stop_event', stop_event), ('on_progress', on_progress)) if value is not None}
def report_progress(on_progress, message):
if on_progress is not None:
on_progress(message)
@@ -0,0 +1,29 @@
"""Frozen, read-only data presented by the single-project task UI."""
from __future__ import annotations
from dataclasses import dataclass
from .models import ProjectRecord, RuleRecord, TaskRecord
from .quick_run import QuickRunProgress
from .target_plan import TargetPlanRow
@dataclass(frozen=True, slots=True)
class ProjectTaskContext:
"""One refreshable snapshot of a task and its bound project.
``project`` is ``None`` for historical tasks that do not have exactly one
immutable project binding. Such contexts are intentionally read-only.
"""
task: TaskRecord
project: ProjectRecord | None
rules: tuple[RuleRecord, ...]
targets: tuple[TargetPlanRow, ...]
progress: QuickRunProgress
phase: str
has_evidence: bool
interrupted: bool
legacy: bool
@@ -0,0 +1,112 @@
"""Read-only project discovery worker orchestration, independent of execution queues."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
import shutil
import subprocess
from uuid import uuid4
from .errors import TaskCenterError
from .quick_run_protocol import ProjectDiscovery, _encode_vbs_field
from .operation_control import check_cancelled, report_progress
@dataclass(frozen=True, slots=True)
class DiscoveryRuntime:
"""Worker and evidence adapters shared with the execution entry point."""
process_runner: Callable[[tuple[str, ...], int], subprocess.CompletedProcess[str]]
cscript_resolver: Callable[[], Path]
worker_paths: Callable[[Path, Path], tuple[str, str]]
helper_launch_arguments: Callable[[], tuple[str, ...]]
failure_message: Callable[[str], str]
read_sheets: Callable[[Path, Path], tuple[tuple[str, str], ...]]
read_matches: Callable[[Path, Path, tuple[tuple[str, str], ...]], dict[tuple[str, str], frozenset[str]]]
timeout: int
def discover_project(
project_path: Path,
old_part_numbers: tuple[str, ...],
*,
data_root: Path,
script_source: Path,
runtime: DiscoveryRuntime,
collect_components: bool = False,
stop_event=None,
on_progress=None,
) -> ProjectDiscovery:
"""Enumerate sheets and requested source parts while the owned project is open."""
check_cancelled(stop_event)
project = project_path.resolve(strict=True)
token = uuid4().hex
job_id = "discover_" + token
root = data_root / "quick-run-history" / ("sheet-discovery-" + token)
root.mkdir(parents=True, exist_ok=False)
script = root / "QuickPartReplace.vbs"
shutil.copyfile(script_source, script)
(root / "command.tsv").write_text(
"task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\r\n"
f"sheet_discovery\t{job_id}\t{project}\tDISCOVERY_OLD\tDISCOVERY_NEW\tpreserve\r\n",
encoding="utf-8",
newline="",
)
(root / "status.tsv").write_text("job_id\tstate\tcode\tmessage\r\n", encoding="utf-8", newline="")
(root / "batch.request").write_text(job_id, encoding="ascii")
(root / "sheet-discovery.request").write_text(job_id, encoding="ascii")
requested: dict[str, str] = {}
for old_part_number in old_part_numbers:
requested.setdefault(old_part_number.casefold(), old_part_number)
(root / "inventory-request.tsv").write_text(
"old_part\r\n" + "".join(
f"{_encode_vbs_field(old_part_number)}\r\n"
for old_part_number in requested.values()
),
encoding="utf-8",
newline="",
)
if collect_components:
(root / "component-inventory.request").write_text(job_id, encoding="ascii")
script_argument, root_argument = runtime.worker_paths(script, root)
command = (
str(runtime.cscript_resolver()),
"//nologo",
script_argument,
root_argument,
*runtime.helper_launch_arguments(),
job_id,
)
try:
report_progress(on_progress, f'正在启动工程读取会话:{project.name}')
check_cancelled(stop_event)
completed = runtime.process_runner(command, runtime.timeout)
except (OSError, subprocess.SubprocessError) as error:
_require_released_reader(root)
check_cancelled(stop_event)
raise TaskCenterError(
"quick_run_sheet_discovery",
f"枚举工程图页时执行器未能安全结束:{project};{error}",
) from error
_require_released_reader(root)
check_cancelled(stop_event)
report_progress(on_progress, f'读取会话已结束,正在核对位号清单:{project.name}')
(root / "worker-output.txt").write_text(completed.stdout + "\n" + completed.stderr, encoding="utf-8")
if completed.returncode != 0:
detail = completed.stderr.strip() or completed.stdout.strip() or "sheet discovery failed"
raise TaskCenterError("quick_run_sheet_discovery", runtime.failure_message(detail))
sheets = runtime.read_sheets(root / "sheets.tsv", project)
matches = runtime.read_matches(root / "inventory.tsv", project, sheets)
if collect_components:
from .inventory import read_component_inventory
components = read_component_inventory(root / "components.tsv", project, sheets)
else:
components = ()
check_cancelled(stop_event)
return ProjectDiscovery(sheets, matches, components)
def _require_released_reader(root):
if (root / 'uncertain.flag').exists():
raise TaskCenterError('inventory_cleanup', f'采集会话未能正常收尾,请检查诊断记录后重试:{root}')
@@ -0,0 +1,149 @@
"""A supervised worker retained between verified steps of one owned project."""
from __future__ import annotations
from pathlib import Path
import subprocess
from threading import Event, Thread
from uuid import uuid4
from .worker_monitor import WorkerMonitorError, run_monitored_process
def _write_control(path: Path, value: str):
temporary = path.with_name(path.name + '.' + uuid4().hex + '.tmp')
temporary.write_text(value, encoding='utf-8')
temporary.replace(path)
class ProjectSessionWorker:
"""Only a saved-and-reopened checkpoint releases the caller for its next step.
The VBS worker owns CAD. This driver never attaches to COM or terminates CAD.
A separate monitor thread retains the existing idle watchdog and worker job.
"""
def __init__(self, project: Path, root: Path, *, private_desktop=False):
self.project, self.root = Path(project), Path(root).resolve()
self.token = uuid4().hex
self._done, self._abort = Event(), Event()
self._thread = None
self._command = None
self._result = self._error = None
self._waiting = False
self._closed = False
self._failure_delivered = False
self._timeout = 150
self.starts = 0
self.private_desktop = private_desktop
def _monitor(self, command, timeout):
try:
if self.private_desktop:
from .isolated_cad import run_isolated_process
self._result = run_isolated_process(command, timeout, abort_event=self._abort)
else:
self._result = run_monitored_process(command, timeout, abort_event=self._abort)
except Exception as error:
self._error = error
finally:
self._done.set()
def run_step(self, command: tuple[str, ...], timeout: float):
if self._closed:
raise WorkerMonitorError('project session is already closed')
if Path(command[3]).resolve() != self.root.resolve():
raise WorkerMonitorError('project session evidence root changed')
if self._command is not None and command[:-1] != self._command[:-1]:
raise WorkerMonitorError('project session worker configuration changed')
job = command[-1]
if self._thread is None:
self.root.mkdir(parents=True, exist_ok=True)
_write_control(self.root / 'project-session.request', f'{self.token}\t{self.project}\t{job}')
(self.root / 'project-session-next.tsv').unlink(missing_ok=True)
(self.root / 'project-session-result.tsv').unlink(missing_ok=True)
self._command, self._timeout = command, timeout
self._thread = Thread(target=self._monitor, args=(command, timeout), daemon=True,
name='dxpart-project-session')
self.starts += 1
self._thread.start()
else:
if not self._waiting:
raise WorkerMonitorError('project session has no verified checkpoint')
self._waiting = False
_write_control(self.root / 'project-session-next.tsv', f'{self.token}\t{job}')
while True:
if self._done.is_set():
if self._error is not None:
raise self._error
if self._result.returncode == 0:
raise WorkerMonitorError('project session exited before authorized closing')
self._failure_delivered = True
return self._result
try:
fields = (self.root / 'project-session-result.tsv').read_text(encoding='utf-8-sig').strip().split('\t')
except (FileNotFoundError, PermissionError):
fields = ()
if len(fields) == 4 and fields[:2] == [self.token, job]:
if fields[2] not in {'saved_ok', 'no_match'} or fields[3] != 'session_verified':
raise WorkerMonitorError('project session returned an invalid checkpoint')
self._waiting = True
return subprocess.CompletedProcess(command, 0, '', '')
self._done.wait(0.025)
def close(self):
if self._closed:
return
try:
if self._thread is None:
self._closed = True
return
if not self._done.is_set():
_write_control(self.root / 'project-session-next.tsv', f'{self.token}\tclose')
close_grace = 60 if self.private_desktop else min(30, max(10, self._timeout))
if not self._done.wait(close_grace):
self._abort.set()
if not self._done.wait(30):
raise WorkerMonitorError('owned project cleanup is still pending; retry closing before another task')
self._closed = True
raise WorkerMonitorError('owned project did not acknowledge session closing')
self._closed = True
if self._error is not None:
raise self._error
if self._result.returncode != 0 and not self._failure_delivered:
raise WorkerMonitorError('owned project session did not close cleanly: ' + self._result.stderr)
finally:
if self._done.is_set():
for name in ('project-session.request', 'project-session-next.tsv', 'project-session-result.tsv'):
(self.root / name).unlink(missing_ok=True)
class ProjectSessionScope:
"""One serial task can visit projects, but can hold only one worker at a time."""
def __init__(self, fallback, *, enabled, private_desktop=False):
self.fallback, self.enabled = fallback, enabled
self.worker = None
self.private_desktop = private_desktop
def __enter__(self):
return self
def run_step(self, project, command, timeout):
if not self.enabled:
return self.fallback(command, timeout)
self.prepare(project)
if self.worker is None:
self.worker = ProjectSessionWorker(Path(project), Path(command[3]), private_desktop=self.private_desktop)
return self.worker.run_step(command, timeout)
def prepare(self, project):
if self.worker is not None and (self.worker.project.resolve() != Path(project).resolve()
or self.worker._done.is_set()):
self.worker.close()
self.worker = None
def __exit__(self, error_type, error, traceback):
if self.worker is not None:
try:
self.worker.close()
except Exception:
self.worker._abort.set()
raise
@@ -0,0 +1,143 @@
"""Create one task for each discovered schematic project."""
from __future__ import annotations
from collections.abc import Callable
from threading import Event
import os
from pathlib import Path
import stat
from uuid import uuid4
from .errors import TaskCenterError
from .models import TaskRecord, TaskStatus
from .scanner import _is_schematic_project, _reject_reparse
from .store import TaskStore
def _validated_root(root: Path, excluded_roots: tuple[Path, ...]) -> tuple[Path, tuple[Path, ...]]:
root = Path(os.path.abspath(root))
for ancestor in (*reversed(root.parents), root):
_reject_reparse(ancestor.lstat(), ancestor)
root = root.resolve(strict=True)
if not root.is_dir():
raise TaskCenterError("discovery_root", "project root is not a directory")
excluded = tuple(Path(path).resolve(strict=False) for path in excluded_roots)
if any(root.is_relative_to(blocked) for blocked in excluded):
raise TaskCenterError("discovery_root", "project root is inside an excluded directory")
return root, excluded
def scan_project_directory(root: Path, *, excluded_roots: tuple[Path, ...] = (),
stop_event: Event | None = None,
on_progress: Callable[[Path, int, int], None] | None = None) -> tuple[Path, ...]:
"""Scan cooperatively; cancellation raises rather than returning partial results.
Progress reports (current directory, visited directories, discovered projects).
The callback runs on the scanning thread.
"""
def check_cancelled():
if stop_event is not None and stop_event.is_set():
raise TaskCenterError("discovery_cancelled", "directory scan cancelled")
check_cancelled()
root, excluded = _validated_root(root, excluded_roots)
found: list[Path] = []
pending = [root]
visited = 0
while pending:
check_cancelled()
directory = pending.pop()
_reject_reparse(directory.lstat(), directory)
children = []
with os.scandir(directory) as entries:
for entry in entries:
check_cancelled()
children.append(entry)
projects: list[Path] = []
folders: list[Path] = []
for entry in sorted(children, key=lambda item: item.name.casefold()):
check_cancelled()
path = Path(entry.path)
if any(path.is_relative_to(blocked) for blocked in excluded):
continue
details = entry.stat(follow_symlinks=False)
_reject_reparse(details, path)
if stat.S_ISDIR(details.st_mode):
folders.append(path)
elif stat.S_ISREG(details.st_mode) and path.suffix.casefold() == ".prj" and _is_schematic_project(path):
projects.append(path.resolve(strict=True))
found.extend(projects)
visited += 1
if on_progress is not None:
on_progress(directory, visited, len(found))
check_cancelled()
if not projects:
pending.extend(reversed(folders))
return tuple(found)
def _validate_selected(root: Path, selected_paths: tuple[Path, ...], excluded: tuple[Path, ...]) -> tuple[Path, ...]:
selected: set[Path] = set()
ancestor_projects: dict[Path, bool] = {}
for candidate in selected_paths:
path = Path(os.path.abspath(candidate))
if not path.is_relative_to(root) or any(path.is_relative_to(blocked) for blocked in excluded):
raise TaskCenterError("project_selection", "selected project is outside discovery results")
relative = path.relative_to(root)
cursor = root
for part in relative.parts:
cursor /= part
_reject_reparse(cursor.lstat(), cursor)
if not path.is_file() or path.suffix.casefold() != ".prj" or not _is_schematic_project(path):
raise TaskCenterError("project_selection", "selected file is not a schematic project")
# A project in any ancestor directory stops discovery below that directory.
directory = path.parent
while directory != root:
directory = directory.parent
if directory not in ancestor_projects:
has_project = False
with os.scandir(directory) as entries:
for entry in entries:
sibling = Path(entry.path)
if sibling.suffix.casefold() != ".prj" or any(sibling.is_relative_to(b) for b in excluded):
continue
details = entry.stat(follow_symlinks=False)
_reject_reparse(details, sibling)
if stat.S_ISREG(details.st_mode) and _is_schematic_project(sibling):
has_project = True
break
ancestor_projects[directory] = has_project
if ancestor_projects[directory]:
raise TaskCenterError("project_selection", "selected project is hidden by an ancestor project")
selected.add(path.resolve(strict=True))
return tuple(sorted(selected, key=lambda path: str(path).casefold()))
def create_project_tasks(store: TaskStore, root: Path, *, selected_paths: tuple[Path, ...] | None = None,
excluded_roots: tuple[Path, ...] = ()) -> tuple[TaskRecord, ...]:
root, excluded = _validated_root(root, excluded_roots)
discovered = (scan_project_directory(root, excluded_roots=excluded) if selected_paths is None
else _validate_selected(root, selected_paths, excluded))
active_paths = {project.path.resolve(strict=False) for task in store.list_tasks()
if task.status not in {TaskStatus.DELETED, TaskStatus.COMPLETED}
for project in store.list_projects(task.task_id)}
pending = [path for path in discovered if path not in active_paths]
group_id = uuid4().hex
created: list[TaskRecord] = []
with store.transaction():
names = {task.name.casefold() for task in store.list_tasks()}
for position, path in enumerate(pending):
base_name = path.relative_to(root).as_posix()
name = base_name
suffix = 2
while name.casefold() in names:
name = f"{base_name} ({suffix})"
suffix += 1
names.add(name.casefold())
task = store.create_task(name)
project = store.sync_projects(task.task_id, root, (path,))[0]
store.set_project_selected(project.project_id, True)
created.append(store.bind_project_task(task.task_id, project.project_id, group_id, position))
return tuple(created)
+280 -287
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
from collections.abc import Callable
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, timezone
from functools import lru_cache
@@ -13,6 +14,7 @@ import re
import shutil
import subprocess
import sys
import time
from typing import Protocol
from uuid import uuid4
@@ -31,60 +33,9 @@ _BATCH_LOG_ROTATION_INTERVAL = 16
_MISSING_PROJECT_SHEET = ("__missing_project__", "0")
@dataclass(frozen=True, slots=True)
class QuickRunResult:
"""The files an operator needs to run and diagnose one quick replacement pass."""
script_path: Path
command_path: Path
status_path: Path
log_path: Path
vbs_root_compatible: bool
@dataclass(frozen=True, slots=True)
class QuickRunStepResult:
"""The correlated result produced by one automatic replacement pass."""
script_path: Path
command_path: Path
status_path: Path
log_path: Path
state: str
message: str
next_project_path: Path | None = None
next_old_part_number: str | None = None
next_new_part_number: str | None = None
next_schematic_name: str | None = None
next_sheet_number: str | None = None
progress: QuickRunProgress | None = None
@dataclass(frozen=True, slots=True)
class QuickRunProgress:
"""Durable progress reconstructed from the correlated handoff files."""
completed_items: int
total_items: int
next_project_path: Path | None
next_old_part_number: str | None
next_new_part_number: str | None
completed_project_paths: tuple[Path, ...]
queue_complete: bool
no_match_items: int = 0
project_summaries: tuple[tuple[Path, str], ...] = ()
saved_items: int = 0
next_schematic_name: str | None = None
next_sheet_number: str | None = None
page_addressed: bool = False
failed_items: int = 0
failed_project_summaries: tuple[tuple[Path, str], ...] = ()
@dataclass(frozen=True, slots=True)
class _ProjectDiscovery:
sheets: tuple[tuple[str, str], ...]
matched_old_parts: dict[tuple[str, str], frozenset[str]]
from .quick_run_protocol import (QuickRunResult, QuickRunStepResult, QuickRunProgress,
ProjectDiscovery, _ProjectDiscovery, _encode_vbs_field, _decode_vbs_field)
from .quick_run_snapshot import QuickRunSnapshot, read_snapshot
@dataclass(slots=True)
@@ -106,6 +57,10 @@ class QuickRunBatchSession:
command_stamp: tuple[int, int, int, int, int]
manifest_stamp: tuple[int, int, int, int, int] | None
completed_project_keys: set[str]
status_stamp: tuple[int, int, int, int, int]
command_header: str
target_command_rows: dict[str, str]
worker_paths: tuple[str, str]
class _ProcessRunner(Protocol):
@@ -131,6 +86,8 @@ class QuickRunPreparer:
self._process_runner = process_runner or _run_process
self._cscript_resolver = cscript_resolver or _resolve_cscript
self._sheet_discoverer = sheet_discoverer
from .discovery_cache import DiscoveryCache
self._discovery_cache = DiscoveryCache(self._data_root)
def prepare(
self,
@@ -151,6 +108,7 @@ class QuickRunPreparer:
raise TaskCenterError("enabled_rule_required", "at least one replacement rule must be enabled")
source = self._required_script_source()
self._validate_fields(selected_projects, enabled_rules)
_validate_target_scope(selected_projects, enabled_rules, sheet_targets)
run_token = _safe_run_token(self._run_token_factory())
maintain_quick_run_storage(self._data_root)
@@ -240,7 +198,7 @@ class QuickRunPreparer:
if before_sheet_discovery is not None:
before_sheet_discovery(project.path)
if self._sheet_discoverer is None:
discovery = self._discover_project_sheets(project.path, old_part_numbers)
discovery = self.discover_project(project.path, old_part_numbers)
targets = discovery.sheets
assert discovery_matches is not None
discovery_matches[_path_key(project.path)] = discovery.matched_old_parts
@@ -308,6 +266,10 @@ class QuickRunPreparer:
project_keys_by_index = tuple(_path_key(command[2]) for command in commands)
status_stat = _required_stat(handoff.status_path, "quick_run_status", "cannot inspect quick-run status")
manifest_path = handoff.command_path.with_name("sheets.tsv")
command_lines = handoff.command_path.read_text(encoding='utf-8-sig').splitlines()
job_column = command_lines[0].split('\t').index('job_id')
target_command_rows = ({line.split('\t')[job_column]: line for line in command_lines[1:] if line}
if 'target_scope' in command_lines[0].split('\t') else {})
return QuickRunBatchSession(
task_id,
_value_mode(copy_part_number_to_value),
@@ -326,8 +288,26 @@ class QuickRunPreparer:
_file_stamp(handoff.command_path),
_file_stamp(manifest_path) if sheets is not None else None,
{_path_key(path) for path in progress.completed_project_paths},
_stat_stamp(status_stat),
command_lines[0],
target_command_rows,
_vbs_worker_paths(handoff.script_path, handoff.script_path.parent),
)
@contextmanager
def project_session_scope(self, *, enabled=True):
"""Retain only the built-in supervised worker; injected workers stay compatible."""
from .project_session import ProjectSessionScope
from .worker_monitor import WorkerMonitorError
try:
with ProjectSessionScope(self._process_runner,
enabled=enabled and self._process_runner is _run_process, private_desktop=True) as scope:
yield scope
except (WorkerMonitorError, subprocess.TimeoutExpired) as error:
_write_uncertain_flag(self._data_root / 'quick-run/uncertain.flag', 'project_session_cleanup')
raise TaskCenterError('quick_run_uncertain',
'工程会话未能确认安全关闭,队列已停止;请保留工程和执行证据后核验恢复。') from error
def execute_step(
self,
task_id: str,
@@ -338,11 +318,26 @@ class QuickRunPreparer:
expected_item: tuple[str, str, str, str] | None = None,
batch_mode: bool = False,
batch_session: QuickRunBatchSession | None = None,
project_session=None,
) -> QuickRunStepResult:
"""Prepare or resume a queue, then execute one replacement rule end to end."""
uncertain_path = self._data_root / "quick-run" / "uncertain.flag"
if uncertain_path.exists():
raise TaskCenterError("quick_run_uncertain", "a previous quick-run worker timed out or returned an uncorrelated status; reconcile the project before retrying")
if self._process_runner is _run_process and not batch_mode:
from .single_step import prepare_private_single_step
prepare_private_single_step(self, task_id, projects, rules, copy_part_number_to_value)
batch_mode = True
current_root = self._data_root / "quick-run"
if batch_session is None and self.evidence_path(task_id) == current_root and (current_root / "status.tsv").is_file():
recorded = _read_status_details(current_root / "status.tsv")
latest_states = {job_id: state for job_id, state, _, _ in recorded}
if any(state == BATCH_SAVED_UNVERIFIED_STATE for state in latest_states.values()):
_write_uncertain_flag(uncertain_path, "saved_readback_unverified")
raise TaskCenterError("quick_run_uncertain", "saved readback was not verified; reconcile before continuing")
if batch_session is not None and any(state == BATCH_SAVED_UNVERIFIED_STATE for state, _ in batch_session.latest.values()):
_write_uncertain_flag(uncertain_path, 'saved_readback_unverified')
raise TaskCenterError('quick_run_uncertain', 'saved readback was not verified; reconcile before continuing')
value_mode = _value_mode(copy_part_number_to_value)
if batch_session is not None:
if not batch_mode or batch_session.task_id != task_id or batch_session.value_mode != value_mode:
@@ -364,7 +359,12 @@ class QuickRunPreparer:
self._validate_fields(selected_projects, enabled_rules)
handoff = self._resumable_handoff(task_id, selected_projects, enabled_rules, value_mode)
if handoff is None:
handoff = self.prepare(task_id, projects, rules, copy_part_number_to_value=copy_part_number_to_value)
if any(getattr(rule, "scope", "all") == "targets" for rule in enabled_rules):
handoff = self.ensure_batch_handoff(task_id, projects, rules,
copy_part_number_to_value=copy_part_number_to_value)
else:
handoff = self.prepare(task_id, projects, rules,
copy_part_number_to_value=copy_part_number_to_value)
else:
source = self._required_script_source()
if source.resolve() != handoff.script_path.resolve():
@@ -377,11 +377,13 @@ class QuickRunPreparer:
actual_item = (*selected_command[2:], value_mode)
if expected_item is not None and actual_item != expected_item:
raise TaskCenterError("quick_run_selection_changed", "confirmed queue item or Value policy changed; confirm again")
script_argument, root_argument = (batch_session.worker_paths if batch_session is not None
else _vbs_worker_paths(handoff.script_path, handoff.script_path.parent))
command = (
str(self._cscript_resolver()),
"//nologo",
str(handoff.script_path),
str(handoff.script_path.parent),
script_argument,
root_argument,
*_native_helper_launch_arguments(),
selected_command[1],
)
@@ -395,8 +397,12 @@ class QuickRunPreparer:
batch_request.unlink(missing_ok=True)
from .worker_monitor import WorkerMonitorError
self.invalidate_discovery(Path(selected_command[2]))
try:
completed = self._process_runner(command, IDLE_PROGRESS_TIMEOUT_SECONDS)
if project_session is not None:
completed = project_session.run_step(Path(selected_command[2]), command, IDLE_PROGRESS_TIMEOUT_SECONDS)
else:
completed = self._process_runner(command, IDLE_PROGRESS_TIMEOUT_SECONDS)
except subprocess.TimeoutExpired as error:
_write_uncertain_flag(uncertain_path, "worker_timeout")
_append_log(handoff.log_path, "quick_run_uncertain worker_timeout")
@@ -433,7 +439,7 @@ class QuickRunPreparer:
status_offset = 0
status_identity = (0, 0)
else:
appended, status_offset, status_identity = _read_appended_status_details(batch_session)
appended, status_offset, status_identity, status_stamp = _read_appended_status_details(batch_session)
after = before + appended
except TaskCenterError as error:
_write_uncertain_flag(uncertain_path, "malformed_status_after_worker")
@@ -457,7 +463,9 @@ class QuickRunPreparer:
_append_log(handoff.log_path, f"quick_run_uncertain uncorrelated_status exit_code={completed.returncode}")
raise TaskCenterError("quick_run_uncertain", "quick-run worker returned an uncorrelated status; reconcile the project before retrying")
_, state, code, message = changed
if batch_mode and completed.returncode == 0 and state in DONE_STATES and code != "batch_closed":
verified_session = bool(project_session is not None and project_session.enabled
and code == 'session_verified')
if batch_mode and completed.returncode == 0 and state in DONE_STATES and code != "batch_closed" and not verified_session:
_write_uncertain_flag(uncertain_path, "batch_save_close_unverified")
raise TaskCenterError("quick_run_uncertain", "批量步骤未确认保存关闭完成,队列已停止,不会继续下一工程。")
check_log_rotation = (
@@ -482,6 +490,14 @@ class QuickRunPreparer:
_write_uncertain_flag(uncertain_path, "worker_exited_before_native_completion")
_append_log(handoff.log_path, "quick_run_uncertain worker_exited_before_native_completion")
raise TaskCenterError("quick_run_uncertain", "执行器已退出,但未返回替换收尾结果;请核验恢复,不要重复替换。")
from .quick_run_snapshot import failed_native_result_uncertain
if state == BATCH_FAILED_STATE and failed_native_result_uncertain(
handoff.command_path.parent, commands, after):
_write_uncertain_flag(uncertain_path, "native_batch_failed_after_mutation")
_append_log(handoff.log_path, "quick_run_uncertain native_batch_failed_after_mutation")
raise TaskCenterError("quick_run_uncertain", "原生修改后未完成核验,队列已停止;请先核验恢复,不要直接重试。")
if state == BATCH_SAVED_UNVERIFIED_STATE:
_write_uncertain_flag(uncertain_path, "saved_readback_unverified")
if state in {BATCH_FAILED_STATE, BATCH_SAVED_UNVERIFIED_STATE} and (not batch_mode or batch_session is None):
raise TaskCenterError("quick_run_execution", message or "batch project failed")
if (completed.returncode != 0 or state == "hard_failure") and state not in {
@@ -523,6 +539,7 @@ class QuickRunPreparer:
batch_session.statuses = after
batch_session.status_offset = status_offset
batch_session.status_identity = status_identity
batch_session.status_stamp = status_stamp
_advance_batch_session(batch_session, changed)
progress = batch_session.progress
next_command = commands[batch_session.next_index] if batch_session.next_index < len(commands) else None
@@ -546,142 +563,28 @@ class QuickRunPreparer:
progress,
)
def read_snapshot(self, task_id, projects, rules, *, copy_part_number_to_value=False,
read_control=None) -> QuickRunSnapshot:
"""Read one consistent set of handoff evidence without changing it."""
return read_snapshot(self, task_id, projects, rules,
copy_part_number_to_value=copy_part_number_to_value, read_control=read_control)
def has_interrupted(self, task_id: str) -> bool:
root = self._data_root / "quick-run"
if self.evidence_path(task_id) != root:
return False
if (root / "uncertain.flag").is_file():
return True
try:
commands = _read_commands(root / "command.tsv")
statuses = _read_status_details(root / "status.tsv")
current = _next_unfinished_command(commands, statuses)
if current is None:
return False
final_state = next((entry[1] for entry in reversed(statuses) if entry[0] == current[1]), None)
if final_state == "awaiting_native_replace":
return True
return final_state == "hard_failure" and _recover_pre_mutation_hard_failures(root, commands, statuses) == statuses
except TaskCenterError:
return False
return self.read_snapshot(task_id, (), ()).interrupted
def current_phase(
self,
task_id: str,
projects: tuple[ProjectRecord, ...],
rules: tuple[RuleRecord, ...],
*,
copy_part_number_to_value: bool = False,
) -> str:
"""Read the matching local handoff queue without starting DxDesigner."""
selected_projects = _selected_projects(projects)
enabled_rules = tuple(rule for rule in rules if rule.enabled)
if not selected_projects or not enabled_rules:
return "selection"
try:
self._validate_fields(selected_projects, enabled_rules)
root = self.evidence_path(task_id) or self._data_root / "quick-run"
command_path = root / "command.tsv"
status_path = root / "status.tsv"
if not command_path.is_file() or not status_path.is_file():
return "selection"
commands = _read_commands(command_path)
command_project_keys = {_path_key(command[2]) for command in commands}
queued_projects = tuple(
project for project in selected_projects
if _path_key(project.path) in command_project_keys
)
if not _value_mode_matches_option(_queue_value_mode(command_path), copy_part_number_to_value):
return "selection"
command_task_ids = {command_task_id for command_task_id, *_ in commands}
if command_task_ids != {task_id} or not _queue_matches_inputs(
command_path, commands, queued_projects, enabled_rules
):
return "selection"
statuses = {job_id: state for job_id, state, _, _ in _read_status_details(status_path)}
except TaskCenterError:
return "selection"
relevant_states = tuple(statuses.get(job_id, "") for _, job_id, *_ in commands)
if any(state == "hard_failure" for state in relevant_states):
return "selection"
if relevant_states and all(state in TERMINAL_STATES for state in relevant_states):
return "complete"
return "selection"
def current_phase(self, task_id, projects, rules, *, copy_part_number_to_value=False,
read_control=None) -> str:
snapshot = self.read_snapshot(task_id, projects, rules,
copy_part_number_to_value=copy_part_number_to_value, read_control=read_control)
return "complete" if snapshot.phase == "retry" else snapshot.phase
def progress(
self,
task_id: str,
projects: tuple[ProjectRecord, ...],
rules: tuple[RuleRecord, ...],
*,
copy_part_number_to_value: bool = False,
) -> QuickRunProgress:
"""Reconstruct task progress without executing or modifying DxDesigner."""
all_selected_projects = _selected_projects(projects)
selected_projects = _queue_projects(projects)
enabled_rules = tuple(rule for rule in rules if rule.enabled)
expected = tuple(
(str(project.path), rule.old_part_number, rule.new_part_number)
for project in selected_projects
for rule in enabled_rules
)
fallback = expected[0] if expected else (None, None, None)
empty = QuickRunProgress(
completed_items=0,
total_items=len(expected),
next_project_path=_optional_path(fallback[0]),
next_old_part_number=fallback[1],
next_new_part_number=fallback[2],
completed_project_paths=(),
queue_complete=False,
)
root = self.evidence_path(task_id) or self._data_root / "quick-run"
command_path = root / "command.tsv"
status_path = root / "status.tsv"
if not command_path.is_file() or not status_path.is_file():
return empty
try:
commands = _read_commands(command_path)
details = _read_status_details(status_path)
if not _value_mode_matches_option(_queue_value_mode(command_path), copy_part_number_to_value):
return empty
command_project_paths = {command[2] for command in commands}
queued_projects = tuple(
project for project in all_selected_projects
if str(project.path) in command_project_paths
)
if {command_task_id for command_task_id, *_ in commands} != {task_id} or not _queue_matches_inputs(
command_path, commands, queued_projects, enabled_rules
):
return empty
sheets = _read_command_sheet_targets(command_path)
except TaskCenterError:
return empty
return _progress_from_queue(queued_projects, commands, details, sheets)
def progress(self, task_id, projects, rules, *, copy_part_number_to_value=False,
read_control=None) -> QuickRunProgress:
return self.read_snapshot(task_id, projects, rules,
copy_part_number_to_value=copy_part_number_to_value, read_control=read_control).progress
def evidence_path(self, task_id: str, project_path: Path | None = None) -> Path | None:
"""Return the current or archived handoff directory bound to the task."""
current = self._data_root / "quick-run"
history = self._data_root / "quick-run-history"
archived = tuple(sorted((path for path in history.glob("obsolete-*") if path.is_dir()), reverse=True))
for root in (current, *archived):
command_path = root / "command.tsv"
status_path = root / "status.tsv"
if not command_path.is_file() or not status_path.is_file():
continue
try:
commands = _read_commands(command_path)
except TaskCenterError:
continue
matching = tuple(command for command in commands if command[0] == task_id)
if not matching or len(matching) != len(commands):
continue
if project_path is not None and not any(
_path_key(command[2]) == _path_key(project_path) for command in matching
):
continue
return root
return None
return read_snapshot(self, task_id, (), (), project_path=project_path).evidence_path
def _resumable_handoff(
self,
@@ -756,61 +659,78 @@ class QuickRunPreparer:
self.vbs_root_compatible,
)
@property
def data_root(self) -> Path:
"""Task evidence root, exposed without private configuration coupling."""
return self._data_root
def for_data_root(self, data_root: Path) -> QuickRunPreparer:
"""Clone executor configuration with an independent task-local cache."""
return type(self)(data_root, script_source=self._script_source,
run_token_factory=self._run_token_factory, process_runner=self._process_runner,
cscript_resolver=self._cscript_resolver, sheet_discoverer=self._sheet_discoverer)
def invalidate_discovery(self, project_path: Path) -> None:
"""Discard read-only evidence before any potentially mutating worker."""
self._discovery_cache.invalidate(project_path)
def discover_project(self, project_path: Path, old_part_numbers: tuple[str, ...], *,
collect_components: bool = False, stop_event=None, on_progress=None) -> ProjectDiscovery:
from .operation_control import check_cancelled, control_options, report_progress
check_cancelled(stop_event)
controls = control_options(stop_event, on_progress)
attempt = 0
def load():
nonlocal attempt
attempt += 1
check_cancelled(stop_event)
report_progress(on_progress, f'正在读取工程 {project_path.name}(第 {attempt} 次核对),请等待当前会话安全收尾…')
check_cancelled(stop_event)
if collect_components:
return self._discover_project_sheets(project_path, old_part_numbers,
collect_components=True, **controls)
return self._discover_project_sheets(project_path, old_part_numbers, **controls)
return self._discovery_cache.discover(
Path(project_path), old_part_numbers, collect_components, load,
**({'stop_event': stop_event} if stop_event is not None else {}))
def collect_inventory(self, project_path: Path, old_part_numbers: tuple[str, ...], *, stop_event=None, on_progress=None) -> tuple:
"""Collect validated component targets, retaining reusable sheet evidence."""
if not old_part_numbers:
raise TaskCenterError("target_inventory", "at least one old Part Number is required")
requested = {part.casefold() for part in old_part_numbers}
from .operation_control import control_options
return tuple(component for component in self.discover_project(
project_path, old_part_numbers, collect_components=True, **control_options(stop_event, on_progress)).components
if component.old_part_number.casefold() in requested)
def _discover_project_sheets(
self,
project_path: Path,
old_part_numbers: tuple[str, ...],
*,
collect_components: bool = False,
stop_event=None,
on_progress=None,
) -> _ProjectDiscovery:
"""Enumerate sheets and requested source parts while the owned project is open."""
project = project_path.resolve(strict=True)
token = uuid4().hex
job_id = _safe_run_token("discover_" + token)
root = self._data_root / "quick-run-history" / ("sheet-discovery-" + token)
root.mkdir(parents=True, exist_ok=False)
script = root / "QuickPartReplace.vbs"
shutil.copyfile(self._required_script_source(), script)
(root / "command.tsv").write_text(
"task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\r\n"
f"sheet_discovery\t{job_id}\t{project}\tDISCOVERY_OLD\tDISCOVERY_NEW\tpreserve\r\n",
encoding="utf-8",
newline="",
)
(root / "status.tsv").write_text("job_id\tstate\tcode\tmessage\r\n", encoding="utf-8", newline="")
(root / "batch.request").write_text(job_id, encoding="ascii")
(root / "sheet-discovery.request").write_text(job_id, encoding="ascii")
requested: dict[str, str] = {}
for old_part_number in old_part_numbers:
requested.setdefault(old_part_number.casefold(), old_part_number)
(root / "inventory-request.tsv").write_text(
"old_part\r\n" + "".join(
f"{_encode_vbs_field(old_part_number)}\r\n"
for old_part_number in requested.values()
),
encoding="utf-8",
newline="",
)
command = (
str(self._cscript_resolver()),
"//nologo",
str(script),
str(root),
*_native_helper_launch_arguments(),
job_id,
)
try:
completed = self._process_runner(command, IDLE_PROGRESS_TIMEOUT_SECONDS)
except (OSError, subprocess.SubprocessError) as error:
raise TaskCenterError(
"quick_run_sheet_discovery",
f"枚举工程图页时执行器未能安全结束:{project};{error}",
) from error
(root / "worker-output.txt").write_text(completed.stdout + "\n" + completed.stderr, encoding="utf-8")
if completed.returncode != 0:
detail = completed.stderr.strip() or completed.stdout.strip() or "sheet discovery failed"
raise TaskCenterError("quick_run_sheet_discovery", _session_failure_message(detail))
sheets = _read_discovered_sheets(root / "sheets.tsv", project)
matches = _read_discovery_inventory(root / "inventory.tsv", project, sheets)
return _ProjectDiscovery(sheets, matches)
from .project_discovery import DiscoveryRuntime, discover_project
from .operation_control import control_options
process_runner = self._process_runner
if stop_event is not None and process_runner is _run_process:
def process_runner(command, timeout):
return _run_process(command, timeout, abort_event=stop_event)
return discover_project(project_path, old_part_numbers,
data_root=self._data_root, script_source=self._required_script_source(),
collect_components=collect_components,
**control_options(stop_event, on_progress),
runtime=DiscoveryRuntime(
process_runner, self._cscript_resolver, _vbs_worker_paths,
_native_helper_launch_arguments, _session_failure_message,
_read_discovered_sheets, _read_discovery_inventory,
IDLE_PROGRESS_TIMEOUT_SECONDS))
@property
def vbs_root_compatible(self) -> bool:
@@ -1021,7 +941,7 @@ def _advance_batch_session(
def _is_saved_result(state: str, code: str) -> bool:
return state == "saved_ok" or (state == "restored_ok" and code == "recovery_verified")
return state == "saved_ok" or (state == "restored_ok" and code in {"recovery_verified", "recovery_saved_verified"})
def _failure_details(
@@ -1177,7 +1097,7 @@ def _queue_has_mutation_evidence(root: Path) -> bool:
report = json.loads(report_path.read_text(encoding="utf-8"))
except (OSError, UnicodeError, json.JSONDecodeError):
return True
if report.get("ok") is True or report.get("stage") in {"native_replace_started", "native_replace_verified"}:
if report.get("ok") is True or report.get("stage") in {"native_replace_started", "native_replace_applied", "pin_promotion_started", "native_replace_verified"}:
return True
return False
@@ -1436,6 +1356,7 @@ def _initial_discovery_status(
return rows[0] + "\r\n"
commands = _read_commands(command_path)
sheets = _read_command_sheet_targets(command_path)
targeted = "target_scope" in command_path.read_text(encoding="utf-8-sig").splitlines()[0].split("\t")
if sheets is None:
raise TaskCenterError("quick_run_sheet_discovery", "discovery inventory requires page-addressed commands")
possible_by_sheet: dict[tuple[str, str, str], set[str]] = {}
@@ -1454,7 +1375,7 @@ def _initial_discovery_status(
raise TaskCenterError("quick_run_sheet_discovery", "discovery inventory does not match the command queue")
possible_key = project_key, sheet[0], sheet[1]
possible = possible_by_sheet.setdefault(possible_key, set(project_matches[sheet]))
if old_part.casefold() not in possible:
if old_part.casefold() not in possible and not targeted:
message = (
"Read-only discovery found no components matching the old Part Number; "
f"the project was closed without replacement. Project={project_path}; "
@@ -1476,6 +1397,15 @@ def _queue_matches_inputs(
rules: tuple[RuleRecord, ...],
) -> bool:
base_mode = _queue_value_mode(command_path)
if "target_scope" in command_path.read_text(encoding="utf-8-sig").splitlines()[0].split("\t"):
sheets = _read_command_sheet_targets(command_path)
manifest = _read_sheet_manifest(command_path.with_name("sheets.tsv"), projects) if sheets is not None else None
expected = _command_text("expected", "expected", projects, rules, base_mode,
sheet_targets=manifest).splitlines()
actual = command_path.read_text(encoding="utf-8-sig").splitlines()
return (expected[0] == actual[0] and len(expected) == len(actual) and
all(expected_row.split("\t")[2:] == actual_row.split("\t")[2:]
for expected_row, actual_row in zip(expected[1:], actual[1:])))
options = _read_command_options(command_path)
sheets = _read_command_sheet_targets(command_path)
if sheets is None:
@@ -1530,12 +1460,23 @@ def _read_status_details(path: Path) -> tuple[tuple[str, str, str, str], ...]:
return tuple(entries)
def _open_status_for_read(path: Path):
deadline = time.monotonic() + 1.0
while True:
try:
return path.open('rb')
except PermissionError:
if time.monotonic() >= deadline:
raise
time.sleep(.02)
def _read_appended_status_details(
session: QuickRunBatchSession,
) -> tuple[tuple[tuple[str, str, str, str], ...], int, tuple[int, int]]:
) -> tuple[tuple[tuple[str, str, str, str], ...], int, tuple[int, int], tuple[int, int, int, int, int]]:
path = session.handoff.status_path
try:
with path.open("rb") as handle:
with _open_status_for_read(path) as handle:
current = os.fstat(handle.fileno())
identity = _file_identity(current)
if identity != session.status_identity or current.st_size < session.status_offset:
@@ -1543,7 +1484,7 @@ def _read_appended_status_details(
handle.seek(session.status_offset)
payload = handle.read()
final = os.fstat(handle.fileno())
if _file_identity(final) != identity or final.st_size != current.st_size:
if _stat_stamp(final)[:4] != _stat_stamp(current)[:4]:
raise ValueError("status file changed while it was being read")
if len(payload) != final.st_size - session.status_offset:
raise ValueError("status tail length is inconsistent")
@@ -1558,7 +1499,7 @@ def _read_appended_status_details(
if len(fields) != 4 or not fields[0] or not fields[1]:
raise ValueError("status tail is malformed")
entries.append(tuple(_decode_vbs_field(field) for field in fields))
return tuple(entries), final.st_size, identity
return tuple(entries), final.st_size, identity, _stat_stamp(final)
except (OSError, UnicodeError, ValueError) as error:
raise TaskCenterError("quick_run_status", "cannot incrementally read quick-run status") from error
@@ -1576,10 +1517,22 @@ def _file_identity(stat: os.stat_result) -> tuple[int, int]:
def _file_stamp(path: Path) -> tuple[int, int, int, int, int]:
stat = _required_stat(path, "quick_run_command", "cannot inspect quick-run queue")
return _stat_stamp(stat)
def _stat_stamp(stat: os.stat_result) -> tuple[int, int, int, int, int]:
return stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns
def _assert_batch_files_unchanged(session: QuickRunBatchSession) -> None:
try:
# On Windows, stat() and fstat() report different ctime semantics.
changed_status = _file_stamp(session.handoff.status_path)[:4] != session.status_stamp[:4]
except TaskCenterError:
changed_status = True
if changed_status:
_write_uncertain_flag(session.handoff.command_path.with_name('uncertain.flag'), 'status_changed_between_workers')
raise TaskCenterError('quick_run_uncertain', '执行状态文件在步骤间发生变化,尚未启动下一项,请先核验。')
if _file_stamp(session.handoff.command_path) != session.command_stamp:
raise TaskCenterError("quick_run_selection_changed", "batch command queue changed during execution")
manifest_path = session.handoff.command_path.with_name("sheets.tsv")
@@ -1592,6 +1545,23 @@ def _write_current_command(
command: tuple[str, str, str, str, str],
) -> tuple[int, int, int, int, int]:
task_id, job_id, project_path, old_part, new_part = command
if session.target_command_rows:
matching = session.target_command_rows.get(job_id)
if matching is None:
raise TaskCenterError("quick_run_command", "target command is missing or duplicated")
path = session.handoff.command_path.with_name("current-command.tsv")
_write_atomic_queue_text(path, session.command_header + "\r\n" + matching + "\r\n",
"quick_run_command", "cannot publish the current target command")
state = session.latest.get(job_id)
state_path = path.with_name("current-state.tsv")
if state is None:
state_path.unlink(missing_ok=True)
else:
_write_atomic_queue_text(state_path,
"job_id\tstate\tcode\tmessage\r\n" + "\t".join(
_encode_vbs_field(field) for field in (job_id, state[0], state[1], "")) + "\r\n",
"quick_run_status", "cannot publish the current target state")
return _file_stamp(path)
value_mode, custom_value, sync_nc, base_value_mode = session.command_options[job_id]
if session.sheets is None:
header = "task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode"
@@ -1653,45 +1623,20 @@ def _write_atomic_queue_text(path: Path, text: str, code: str, message: str) ->
handle.write(text)
handle.flush()
os.fsync(handle.fileno())
os.replace(temporary, path)
deadline = time.monotonic() + 1.0
while True:
try:
os.replace(temporary, path)
break
except PermissionError:
if time.monotonic() >= deadline:
raise
time.sleep(.02)
except OSError as error:
temporary.unlink(missing_ok=True)
raise TaskCenterError(code, message) from error
def _encode_vbs_field(value: str) -> str:
encoded: list[str] = []
for character in str(value):
code = ord(character)
if character != "%" and 32 <= code <= 126:
encoded.append(character)
continue
units = character.encode("utf-16-le")
encoded.extend(
f"%{int.from_bytes(units[index:index + 2], 'little'):04X}"
for index in range(0, len(units), 2)
)
return "".join(encoded)
def _decode_vbs_field(value: str) -> str:
characters: list[str] = []
index = 0
while index < len(value):
if value[index] == "%" and index + 4 < len(value):
token = value[index + 1:index + 5]
if all(character in "0123456789abcdefABCDEF" for character in token):
characters.append(chr(int(token, 16)))
index += 5
continue
characters.append(value[index])
index += 1
try:
return "".join(characters).encode("utf-16-le", errors="surrogatepass").decode("utf-16-le")
except UnicodeError as error:
raise ValueError("VBS field contains malformed UTF-16") from error
def _path_key(path: str | Path) -> str:
return os.path.normcase(os.path.abspath(str(path)))
@@ -1758,6 +1703,12 @@ def _next_unfinished_command(
return next((command for command in commands if final_states.get(command[1]) not in TERMINAL_STATES), None)
def _vbs_worker_paths(script: Path, root: Path) -> tuple[str, str]:
"""FSO cannot see some paths beyond MAX_PATH, including monitor handshakes."""
from .legacy_paths import worker_paths
return worker_paths(script, root)
def _resolve_cscript(windows_root: Path | None = None, is_64_bit: bool | None = None) -> Path:
windows = Path(windows_root) if windows_root is not None else Path(os.environ.get("WINDIR", r"C:\Windows"))
if is_64_bit is None:
@@ -1780,10 +1731,15 @@ def _cached_native_helper_launch_arguments(frozen: bool, executable: str) -> tup
return (resolved_executable, str(Path(__file__).with_name("application.py")))
def _run_process(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
from .worker_monitor import run_monitored_process
def _run_process(command: tuple[str, ...], timeout: int, *, abort_event=None) -> subprocess.CompletedProcess[str]:
from .isolated_cad import run_isolated_process
from .legacy_paths import validate_project_access
return run_monitored_process(command, timeout)
validate_project_access(Path(command[3]))
result = run_isolated_process(command, timeout,
**({'abort_event': abort_event, 'cooperative_abort': True} if abort_event is not None else {}))
validate_project_access(Path(command[3]))
return result
def _log_text(value: str) -> str:
@@ -1897,15 +1853,32 @@ def _command_text(
*,
sheet_targets: dict[str, tuple[tuple[str, str], ...]] | None = None,
) -> str:
_validate_target_scope(projects, rules, sheet_targets)
targeted = any(getattr(rule, "scope", "all") == "targets" for rule in rules)
if targeted and sheet_targets is None:
raise TaskCenterError("target_scope", "target execution requires sheet-addressed commands")
suffix = "\ttarget_scope\ttarget_selectors" if targeted else ""
if sheet_targets is None:
rows = ["task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode"]
rows = ["task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode" + suffix]
else:
rows = ["task_id\tjob_id\tproject_path\tschematic_name\tsheet_number\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode"]
rows = ["task_id\tjob_id\tproject_path\tschematic_name\tsheet_number\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode" + suffix]
job_index = 0
for project in projects:
targets = ((None, None),) if sheet_targets is None else sheet_targets[_path_key(project.path)]
for schematic_name, sheet_number in targets:
for rule in rules:
scope = getattr(rule, "scope", "all")
if scope == "targets":
targets_for_sheet = tuple(target for target in rule.targets
if _path_key(target.project_path) == _path_key(project.path)
and (target.schematic_name, target.sheet_number) == (schematic_name, sheet_number))
if not targets_for_sheet:
continue
selectors = _encode_vbs_field("\x1e".join(
"\x1f".join((target.uid, target.refdes, target.old_value))
for target in targets_for_sheet))
else:
selectors = ""
job_id = f"{run_token}_{job_index}"
sheet_fields = "" if schematic_name is None else f"\t{schematic_name}\t{sheet_number}"
rule_mode, custom_value, sync_nc, base_mode = _rule_command_options(rule, value_mode)
@@ -1913,6 +1886,26 @@ def _command_text(
f"{task_id}\t{job_id}\t{project.path}{sheet_fields}\t"
f"{rule.old_part_number}\t{rule.new_part_number}\t{rule_mode}\t{custom_value}\t"
f"{'1' if sync_nc else '0'}\t{base_mode}"
+ (f"\t{scope}\t{selectors}" if targeted else "")
)
job_index += 1
return "\r\n".join(rows) + "\r\n"
def _validate_target_scope(projects, rules, sheet_targets) -> None:
scopes = {getattr(rule, "scope", "all") for rule in rules}
if scopes - {"all", "targets"} or len(scopes) > 1:
raise TaskCenterError("target_scope", "all-match and target rules cannot share a queue")
if scopes != {"targets"}:
return
if sheet_targets is None:
raise TaskCenterError("target_scope", "target queue requires sheet discovery")
available = {(_path_key(project.path), schematic, sheet)
for project in projects
for schematic, sheet in sheet_targets.get(_path_key(project.path), ())}
for rule in rules:
if not rule.targets:
raise TaskCenterError("empty_target_scope", "target rule has no components")
for target in rule.targets:
if (_path_key(target.project_path), target.schematic_name, target.sheet_number) not in available:
raise TaskCenterError("target_identity", "selected target sheet is missing from discovery")
@@ -0,0 +1,101 @@
"""Immutable execution protocol models and VBS field codec."""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True, slots=True)
class QuickRunResult:
"""The files an operator needs to run and diagnose one quick replacement pass."""
script_path: Path
command_path: Path
status_path: Path
log_path: Path
vbs_root_compatible: bool
@dataclass(frozen=True, slots=True)
class QuickRunStepResult:
"""The correlated result produced by one automatic replacement pass."""
script_path: Path
command_path: Path
status_path: Path
log_path: Path
state: str
message: str
next_project_path: Path | None = None
next_old_part_number: str | None = None
next_new_part_number: str | None = None
next_schematic_name: str | None = None
next_sheet_number: str | None = None
progress: QuickRunProgress | None = None
@dataclass(frozen=True, slots=True)
class QuickRunProgress:
"""Durable progress reconstructed from the correlated handoff files."""
completed_items: int
total_items: int
next_project_path: Path | None
next_old_part_number: str | None
next_new_part_number: str | None
completed_project_paths: tuple[Path, ...]
queue_complete: bool
no_match_items: int = 0
project_summaries: tuple[tuple[Path, str], ...] = ()
saved_items: int = 0
next_schematic_name: str | None = None
next_sheet_number: str | None = None
page_addressed: bool = False
failed_items: int = 0
failed_project_summaries: tuple[tuple[Path, str], ...] = ()
@dataclass(frozen=True, slots=True)
class ProjectDiscovery:
sheets: tuple[tuple[str, str], ...]
matched_old_parts: dict[tuple[str, str], frozenset[str]]
components: tuple = ()
# Preserve callers that injected the original discovery boundary.
_ProjectDiscovery = ProjectDiscovery
def _encode_vbs_field(value: str) -> str:
encoded: list[str] = []
for character in str(value):
code = ord(character)
if character != "%" and 32 <= code <= 126:
encoded.append(character)
continue
units = character.encode("utf-16-le")
encoded.extend(
f"%{int.from_bytes(units[index:index + 2], 'little'):04X}"
for index in range(0, len(units), 2)
)
return "".join(encoded)
def _decode_vbs_field(value: str) -> str:
if value.isascii() and '%' not in value:
return value
characters: list[str] = []
index = 0
while index < len(value):
if value[index] == "%" and index + 4 < len(value):
token = value[index + 1:index + 5]
if all(character in "0123456789abcdefABCDEF" for character in token):
characters.append(chr(int(token, 16)))
index += 5
continue
characters.append(value[index])
index += 1
try:
return "".join(characters).encode("utf-16-le", errors="surrogatepass").decode("utf-16-le")
except UnicodeError as error:
raise ValueError("VBS field contains malformed UTF-16") from error
@@ -0,0 +1,201 @@
"""Read-only execution view reconstructed from one cached set of handoff files."""
from __future__ import annotations
from dataclasses import dataclass, replace
import json
from pathlib import Path
from .errors import TaskCenterError
from .quick_run_protocol import QuickRunProgress
def failed_native_result_uncertain(root, commands, statuses, *, files=None):
"""Closing an unsaved project is not proof that native mutation rolled back."""
from . import quick_run as api
latest = {job: state for job, state, _, _ in statuses}
awaiting = {job for job, state, _, _ in statuses if state == 'awaiting_native_replace'}
for _, job, *_ in commands:
if latest.get(job) != api.BATCH_FAILED_STATE:
continue
if api._rollback_marker_verified(root, job):
continue
path = root / f'snapshot-{job}.tsv.native.json'
try:
report = json.loads(files.read(path) if files is not None else path.read_text(encoding='utf-8-sig'))
except (OSError, UnicodeError, json.JSONDecodeError):
if job in awaiting or path.exists():
return True
continue
if not isinstance(report, dict):
return True
if report.get('ok') is True or report.get('stage') in {
'native_replace_started', 'native_replace_applied', 'pin_promotion_started', 'native_replace_verified'}:
return True
return False
@dataclass(frozen=True, slots=True)
class QuickRunSnapshot:
progress: QuickRunProgress
has_evidence: bool
evidence_path: Path | None
interrupted: bool
phase: str
class _ReadFiles:
def __init__(self, control):
self.control = control
self.texts = {}
self.roots = {}
def checkpoint(self):
if self.control is not None:
self.control.checkpoint()
def _manifest(self, root):
self.checkpoint()
def stamp(path):
self.checkpoint()
try:
stat = path.stat()
return (stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns)
except OSError:
return None
root_stamp = stamp(root)
try:
# Include sidecar evidence used by hard-failure recovery as well as
# command/status and flags; creation/removal changes the root stamp.
entries = tuple(root.iterdir())
except OSError:
entries = ()
result = {path.name: stamp(path) for path in entries}
self.checkpoint()
return root_stamp, result
def track_root(self, root):
if root not in self.roots:
self.roots[root] = self._manifest(root)
def stable(self):
return all(self._manifest(root) == before for root, before in self.roots.items())
def path(self, path):
return _CachedPath(Path(path), self)
def read(self, path):
self.checkpoint()
if path not in self.texts:
chunks = []
with path.open('r', encoding='utf-8-sig') as source:
while True:
self.checkpoint()
chunk = source.read(65536)
self.checkpoint()
if not chunk:
break
chunks.append(chunk)
self.texts[path] = ''.join(chunks)
return self.texts[path]
class _CachedPath:
"""Path-shaped parser input: every parser sees the same immutable text."""
def __init__(self, path, files):
self.path, self.files = path, files
def read_text(self, **kwargs):
return self.files.read(self.path)
def with_name(self, name):
return self.files.path(self.path.with_name(name))
def exists(self):
self.files.checkpoint()
return self.path.exists()
def read_snapshot(preparer, task_id, projects, rules, *, copy_part_number_to_value=False,
read_control=None, project_path=None):
for _ in range(3):
files = _ReadFiles(read_control)
snapshot = _read_snapshot_once(preparer, task_id, projects, rules,
copy_part_number_to_value=copy_part_number_to_value, project_path=project_path, files=files)
if files.stable():
return snapshot
# Never publish executable continuation coordinates from a changing set.
progress = replace(snapshot.progress, next_project_path=None, next_old_part_number=None,
next_new_part_number=None, next_schematic_name=None, next_sheet_number=None)
files.checkpoint()
return replace(snapshot, progress=progress, interrupted=True)
def _read_snapshot_once(preparer, task_id, projects, rules, *, copy_part_number_to_value=False,
project_path=None, files):
# Import lazily to preserve the historical quick_run private parser boundaries.
from . import quick_run as api
files.checkpoint()
selected = api._selected_projects(projects)
queued = api._queue_projects(projects)
enabled = tuple(rule for rule in rules if rule.enabled)
expected = tuple((str(project.path), rule.old_part_number, rule.new_part_number)
for project in queued for rule in enabled)
first = expected[0] if expected else (None, None, None)
progress = QuickRunProgress(0, len(expected), api._optional_path(first[0]), first[1], first[2], (), False)
current = preparer._data_root / 'quick-run'
history = preparer._data_root / 'quick-run-history'
root = None
commands = ()
# Avoid enumerating history when the active handoff already matches.
def candidates():
yield current
files.checkpoint()
yield from sorted((path for path in history.glob('obsolete-*') if path.is_dir()), reverse=True)
for candidate in candidates():
files.checkpoint()
files.track_root(candidate)
command = candidate / 'command.tsv'
if not command.is_file() or not (candidate / 'status.tsv').is_file():
continue
try:
parsed = api._read_commands(files.path(command))
except TaskCenterError:
continue
if not parsed or {row[0] for row in parsed} != {task_id}:
continue
if project_path is not None and not any(api._path_key(row[2]) == api._path_key(project_path) for row in parsed):
continue
root, commands = candidate, parsed
break
if root is None:
files.checkpoint()
return QuickRunSnapshot(progress, False, None, False, 'selection')
interrupted = root == current and (root / 'uncertain.flag').is_file()
phase = 'selection'
try:
details = api._read_status_details(files.path(root / 'status.tsv'))
files.checkpoint()
if root == current:
latest = {job_id: state for job_id, state, _, _ in details}
interrupted = interrupted or any(state == api.BATCH_SAVED_UNVERIFIED_STATE for state in latest.values())
interrupted = interrupted or failed_native_result_uncertain(root, commands, details, files=files)
unfinished = api._next_unfinished_command(commands, details)
if unfinished is not None:
final = latest.get(unfinished[1])
interrupted = interrupted or final == 'awaiting_native_replace'
if final == 'hard_failure':
interrupted = interrupted or api._recover_pre_mutation_hard_failures(root, commands, details) == details
if selected and enabled:
preparer._validate_fields(selected, enabled)
command_path = files.path(root / 'command.tsv')
queued_projects = tuple(project for project in selected
if str(project.path) in {command[2] for command in commands})
if (api._value_mode_matches_option(api._queue_value_mode(command_path), copy_part_number_to_value)
and api._queue_matches_inputs(command_path, commands, queued_projects, enabled)):
sheets = api._read_command_sheet_targets(command_path)
files.checkpoint()
progress = api._progress_from_queue(queued_projects, commands, details, sheets)
if progress.queue_complete:
phase = 'retry' if progress.failed_items else 'complete'
except TaskCenterError:
pass
files.checkpoint()
return QuickRunSnapshot(progress, True, root, interrupted, phase)
@@ -0,0 +1,24 @@
"""Cooperative cancellation for read-only work; deadlines use monotonic time."""
from threading import Event
from time import monotonic
class QueryCancelled(Exception):
"""The caller no longer needs this read result."""
class QueryControl:
def __init__(self, deadline=None):
self.deadline = deadline
self._cancelled = Event()
@property
def cancelled(self):
return self._cancelled.is_set() or (self.deadline is not None and monotonic() >= self.deadline)
def cancel(self):
self._cancelled.set()
def checkpoint(self):
if self.cancelled:
raise QueryCancelled('Read request cancelled')
@@ -18,7 +18,7 @@ from .quick_run import (
_native_helper_launch_arguments, _next_unfinished_command, _path_key,
_queue_matches_inputs, _queue_value_mode, _read_command_sheet_targets,
_read_command_options, _read_commands, _read_status_details, _safe_run_token,
_value_mode_matches_option, _write_status_details, _write_uncertain_flag,
_value_mode_matches_option, _write_status_details, _write_uncertain_flag, _decode_vbs_field,
)
from .retention import maintain_quick_run_storage
from .schematic_backup import create_schematic_backup
@@ -34,6 +34,19 @@ def _is_link_or_reparse(path: Path) -> bool:
)
def _recovery_command(commands, statuses, *, root=None):
from .quick_run_snapshot import failed_native_result_uncertain
latest = {entry[0]: entry[1] for entry in statuses}
unverified = tuple(command for command in commands
if latest.get(command[1]) == 'batch_saved_unverified'
or (root is not None and failed_native_result_uncertain(root, (command,), statuses)))
if len(unverified) > 1:
raise TaskCenterError('quick_run_recovery', '多个保存后未核验步骤需要逐项人工核对,保护状态保持。')
if unverified:
return unverified[0]
return _next_unfinished_command(commands, statuses)
def _hashes(
root: Path,
*,
@@ -88,7 +101,7 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal
raise TaskCenterError('quick_run_recovery', '当前工程或规则与中断队列不同,不能恢复其他任务。')
if not _value_mode_matches_option(mode, copy_part_number_to_value) or len({command[1] for command in commands}) != len(commands):
raise TaskCenterError('quick_run_recovery', 'Value 策略变化或队列编号重复,已停止恢复。')
selected = _next_unfinished_command(commands, before)
selected = _recovery_command(commands, before, root=root)
if selected is None:
raise TaskCenterError('quick_run_recovery', '队列记录已完成但仍有保护锁,需要单独核对,未自动解除。')
job_id = _safe_run_token(selected[1])
@@ -105,15 +118,28 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal
metadata, components = read_snapshot(snapshot)
snapshot_options = (
(metadata[5], metadata[6], metadata[7])
if len(metadata) == 8
if len(metadata) >= 8
else (metadata[5], '', '1')
)
if len(metadata) not in {6, 8} or (_path_key(metadata[1]), metadata[2], metadata[3]) != (
if len(metadata) not in {6, 8, 10} or (_path_key(metadata[1]), metadata[2], metadata[3]) != (
_path_key(selected[2]), selected[3], selected[4]) or snapshot_options != (
selected_mode, selected_custom_value, '1' if selected_sync_nc else '0'):
raise ValueError('snapshot command mismatch')
if selected_sheet is not None and metadata[4] != f'{selected_sheet[0]}:{selected_sheet[1]}':
raise ValueError('snapshot sheet mismatch')
command_lines = (root / 'command.tsv').read_text(encoding='utf-8-sig').splitlines()
command_header = command_lines[0].split('\t')
if 'target_scope' in command_header:
candidates = [line.split('\t') for line in command_lines[1:]
if line.split('\t')[command_header.index('job_id')] == job_id]
if len(candidates) != 1:
raise ValueError('target command missing or duplicated')
scope = candidates[0][command_header.index('target_scope')]
selectors = candidates[0][command_header.index('target_selectors')]
if scope != 'targets' or len(metadata) != 10 or metadata[8:] != ['targets', _decode_vbs_field(selectors)]:
raise ValueError('snapshot target selector mismatch')
elif len(metadata) == 10:
raise ValueError('snapshot target scope missing from command')
report = json.loads(snapshot.with_suffix('.tsv.native.json').read_text(encoding='utf-8'))
binding = require_resumable_transaction(snapshot, report, metadata, components)
identity = binding['library_row'][4:6]
@@ -161,9 +187,14 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal
header = 'task_id\tjob_id\tproject_path\tschematic_name\tsheet_number\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode\trecovery_part_name\trecovery_part_label'
row = (*selected[:3], *selected_sheet, *selected[3:], *option_fields, *identity)
shutil.copyfile(root / 'sheets.tsv', worker / 'sheets.tsv')
if len(metadata) == 10:
header += '\ttarget_scope\ttarget_selectors'
row = (*row, 'targets', selectors)
(worker / 'command.tsv').write_text(header + '\n' + '\t'.join(row) + '\n', encoding='utf-8')
_write_status_details(worker / 'status.tsv', ())
launch = (str(preparer._cscript_resolver()), '//nologo', str(script), str(worker),
from .quick_run import _vbs_worker_paths
script_argument, root_argument = _vbs_worker_paths(script, worker)
launch = (str(preparer._cscript_resolver()), '//nologo', script_argument, root_argument,
*_native_helper_launch_arguments(), job_id)
try:
result = preparer._process_runner(launch, IDLE_PROGRESS_TIMEOUT_SECONDS)
@@ -208,7 +239,10 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal
raise
progress = preparer.progress(task_id, projects, rules, copy_part_number_to_value=copy_part_number_to_value)
message = ('磁盘工程与替换前快照一致,只读核验工程已关闭,已准备新的执行编号;尚未再次替换,请确认后执行。'
if state == 'retry_ready' else '已核验并恢复本项任务记录;没有重复执行原生替换。若补做了属性恢复,请保存当前工程。')
if state == 'retry_ready' else
'已核验并恢复本项任务记录,属性已保存并重开回读,工程已关闭;没有重复执行原生替换。'
if after[0][2] == 'recovery_saved_verified' else
'已核验并恢复本项任务记录;没有重复执行原生替换。若补做了属性恢复,请保存当前工程。')
return QuickRunStepResult(root / 'QuickPartReplace.vbs', root / 'command.tsv', root / 'status.tsv',
audit / 'worker-output.txt', state, message, progress.next_project_path,
progress.next_old_part_number, progress.next_new_part_number,
@@ -0,0 +1,18 @@
"""Reuse the replacement engine's mapping constraints for persisted and batch rules."""
import csv
import io
from pathlib import Path
from dx_productivity.part_replace.inputs import InputError, parse_mapping_bytes
from .errors import TaskCenterError
def validate_mapping_pairs(pairs):
output = io.StringIO(newline='')
writer = csv.writer(output, lineterminator='\n')
writer.writerow(('old_part_number', 'new_part_number'))
writer.writerows(pairs)
try:
parse_mapping_bytes(output.getvalue().encode('utf-8'), Path('task-center-rules.csv'))
except InputError as error:
raise TaskCenterError(error.code, error.message) from error
@@ -112,17 +112,7 @@ class TrialRunner:
recovery_event_id=f"v1-attemptless:{recovery.project_id}:task:after",
)
self._store.acknowledge_migration_recoveries(tuple(recovery.project_id for recovery in migration_recoveries))
interrupted_states = {
ProjectStatus.CAPTURING_BEFORE,
ProjectStatus.CAPTURING_AFTER,
ProjectStatus.VERIFYING,
}
interrupted = tuple(
project
for task in self._store.list_tasks()
for project in self._store.list_projects(task.task_id)
if project.status in interrupted_states
)
interrupted = self._store.interrupted_projects()
running_task_ids = {project.task_id for project in interrupted if self._store.get_task(project.task_id).status is TaskStatus.RUNNING}
for project in interrupted:
self._event_transition(
@@ -147,6 +137,8 @@ class TrialRunner:
"before",
)
recovered_project_ids = self._store.recover_interrupted_work()
log_recovery = self._logging.logger.warning if recovered_project_ids else self._logging.logger.info
log_recovery('recovered_interrupted_projects=%s', ','.join(recovered_project_ids) or 'none')
for project_id in recovered_project_ids:
project = self._project(project_id)
self._event_transition(
+388 -47
View File
@@ -11,12 +11,22 @@ import threading
from typing import TypeVar
from .errors import TaskCenterError
from .logging_setup import LoggingContext, _tail_utf8_lines, append_task_event
from .logging_setup import LoggingContext, _EVENT_BACKUP_COUNT, _tail_utf8_lines, append_task_event
from .models import ProjectRecord, ProjectStatus, RuleRecord, TaskRecord, TaskStatus
from .quick_run import QuickRunPreparer, QuickRunProgress, QuickRunResult, QuickRunStepResult, _path_key
from .runner import OperatorInstruction, RunnerSnapshot, TrialRunner
from .scanner import scan_projects
from .store import TaskStore
from .target_plan import compile_target_rules
from .project_tasks import create_project_tasks as _create_project_tasks
from .inventory import collect_target_inventory
from .spreadsheet_plan import export_target_plan as _export_target_plan, import_target_plan as _import_target_plan
from .bom_plan import read_bom_plan as _read_bom_plan
from .project_context import ProjectTaskContext
from .execution_metrics import measure_phase
from .read_control import QueryCancelled
from .batch_rules import batch_rule_view, mutate_batch_rules, seed_defaults
from .operation_control import check_cancelled, control_options, report_progress
_Result = TypeVar("_Result")
@@ -84,23 +94,175 @@ class TaskCenterService:
clock: Callable[[], datetime] = datetime.now,
probe_source_resolver: Callable[[TaskRecord, ProjectRecord], Path] | None = None,
quick_run_preparer: QuickRunPreparer | None = None,
runner: TrialRunner | None = None,
) -> None:
self._store = store
self._logging = logging_context
self._path_opener = path_opener
self._clock = clock
self._runner = TrialRunner(store, logging_context, probe_source_resolver=probe_source_resolver)
self._runner = runner or TrialRunner(store, logging_context, probe_source_resolver=probe_source_resolver)
self._quick_run_preparer = quick_run_preparer or QuickRunPreparer(logging_context.root)
self._batch_feedback = None
self._project_facades: dict[str, TaskCenterService] = {}
self._facade_lock = threading.RLock()
def create_task(self, name: str, *, note: str = "") -> TaskRecord:
return self._operation("create_task", None, lambda: self._store.create_task(name, note))
return self._idle_quick_run_operation("create_task", None, lambda: self._store.create_task(name, note))
def create_project_tasks(self, root: Path, *, selected_paths: tuple[Path, ...] | None = None) -> tuple[TaskRecord, ...]:
return self._idle_quick_run_operation("create_project_tasks", None,
lambda: _create_project_tasks(self._store, root, selected_paths=selected_paths,
excluded_roots=(self._logging.root,)))
def target_plan(self, task_id: str):
return self._operation("list_target_plan", task_id, lambda: self._store.list_target_plan(task_id))
def replace_target_plan(self, task_id: str, rows) -> tuple:
return self._idle_quick_run_operation("replace_target_plan", task_id,
lambda: self._store.replace_target_plan(task_id, tuple(rows)))
def preview_target_plan(self, task_id: str, path: Path):
from .spreadsheet_plan import read_target_plan
return self._operation("preview_target_plan", task_id, lambda: read_target_plan(self._store, task_id, path))
def import_target_plan(self, task_id: str, path: Path) -> tuple:
return self._idle_quick_run_operation("import_target_plan", task_id,
lambda: _import_target_plan(self._store, task_id, path))
def export_target_plan(self, task_id: str, path: Path) -> Path:
return self._operation("export_target_plan", task_id,
lambda: _export_target_plan(self._store, task_id, path))
def preview_bom_plan(self, task_id: str, path: Path) -> tuple:
return self._operation("preview_bom_plan", task_id,
lambda: _read_bom_plan(self._store, task_id, path))
def export_bom_template(self, task_id: str | None, path: Path) -> Path:
from .bom_batch import export_template
return self._operation("export_bom_template", task_id,
lambda: export_template(self._store, task_id, path))
def preview_bom_batch(self, task_id: str, path: Path, *, stop_event=None, on_progress=None):
from .bom_batch import preview_batch
return self._idle_quick_run_operation('preview_bom_batch', task_id,
lambda: preview_batch(self, task_id, path, **control_options(stop_event, on_progress)))
def save_bom_batch(self, preview, rows_by_task):
from .bom_batch import save_batch
return self._idle_quick_run_operation('save_bom_batch', preview.anchor_task_id,
lambda: save_batch(self, preview, rows_by_task))
def save_plan_drafts(self, batches, standalone):
"""Confirm all window drafts atomically, including multiple BOM batches."""
from .bom_batch import save_batch, _assert_editable
batches = tuple(batches)
def save():
result = {}
with self._store.transaction():
for preview, rows in batches:
result.update(save_batch(self, preview, rows))
for task_id, rows in standalone.items():
_assert_editable(self, task_id)
result[task_id] = self._store.replace_target_plan(task_id, rows)
return result
return self._idle_quick_run_operation('save_plan_drafts', None, save)
def for_project_task(self, task_id: str) -> "TaskCenterService":
"""Return a facade whose evidence root is isolated to this task."""
return self._facade_for_task_record(self._store.get_task(task_id), force=True)
def _facade_for_task_record(self, task: TaskRecord, *, force: bool = False) -> "TaskCenterService":
"""Resolve evidence routing from the caller's already consistent task record."""
if not force and not task.primary_project_id:
return self
task_id = task.task_id
child_root = self._logging.root / "tasks" / task_id
if self._quick_run_preparer.data_root == child_root:
return self
with self._facade_lock:
if task_id not in self._project_facades:
child_preparer = self._quick_run_preparer.for_data_root(child_root)
# Initializing a new runner replays startup recovery and mutates
# the database. A facade shares the initialized runner instead.
child = TaskCenterService(self._store, self._logging, path_opener=self._path_opener,
clock=self._clock, quick_run_preparer=child_preparer, runner=self._runner)
self._project_facades[task_id] = child
return self._project_facades[task_id]
def _project_task_service(self, task_id: str) -> "TaskCenterService":
return self._facade_for_task_record(self._store.get_task(task_id))
def scan_project_directory(self, root: Path, *, stop_event=None, on_progress=None):
from .project_tasks import scan_project_directory
return self._operation("scan_project_directory", None,
lambda: scan_project_directory(root, excluded_roots=(self._logging.root,),
stop_event=stop_event, on_progress=on_progress))
def move_project_task(self, task_id: str, offset: int):
return self._idle_quick_run_operation("move_project_task", task_id,
lambda: self._store.move_project_task(task_id, offset))
def get_task(self, task_id: str) -> TaskRecord:
return self._operation("get_task", task_id, lambda: self._store.get_task(task_id))
def tasks(self, status: TaskStatus | None = None) -> tuple[TaskRecord, ...]:
return self._operation("list_tasks", None, lambda: self._store.list_tasks(status))
def task_context(self, task_id: str, *, read_control=None) -> ProjectTaskContext:
"""Read a fresh immutable snapshot; only the per-task facade is cached."""
return self._refresh_project_context(task_id, allow_legacy=True, read_control=read_control)
def refresh_bound_project(self, task_id: str) -> ProjectTaskContext:
"""Check the bound file only; never recurse or change project membership."""
def refresh():
task = self._store.get_task(task_id)
projects = self._store.list_projects(task_id)
if task.primary_project_id is None or len(projects) != 1 or projects[0].project_id != task.primary_project_id:
raise TaskCenterError("project_binding", "refresh requires one bound project")
project = projects[0]
from .scanner import _reject_reparse
paths = ()
try:
_reject_reparse(project.path.lstat(), project.path)
if project.path.is_file():
paths = (project.path,)
except FileNotFoundError:
pass
self._store.sync_projects(task_id, project.discovery_root, paths)
return self._refresh_project_context(task_id, allow_legacy=False)
return self._idle_quick_run_operation("refresh_bound_project", task_id, refresh)
def _refresh_project_context(self, task_id: str, *, allow_legacy: bool, read_control=None) -> ProjectTaskContext:
def refresh() -> ProjectTaskContext:
if read_control is not None:
read_control.checkpoint()
bundle = self._store.read_task_bundle(task_id, read_control=read_control)
task, projects = bundle.task, bundle.projects
bound = None
if task.primary_project_id is not None and len(projects) == 1:
candidate = projects[0]
if candidate.project_id == task.primary_project_id:
bound = candidate
legacy = bound is None
if not allow_legacy and (task.primary_project_id is None or bound is None or len(projects) != 1):
raise TaskCenterError("project_binding", "bound task must own exactly one project")
rules, targets = (bundle.batch_rules if bundle.batch_rules is not None else bundle.rules), bundle.targets
facade = self._facade_for_task_record(task)
effective_rules = compile_target_rules(tuple(targets)) if task.target_plan_mode else rules
snapshot = facade._quick_run_preparer.read_snapshot(task_id, projects, effective_rules,
copy_part_number_to_value=task.copy_part_number_to_value, read_control=read_control)
progress = snapshot.progress
interrupted = snapshot.interrupted
has_evidence = snapshot.has_evidence
phase = snapshot.phase
context = ProjectTaskContext(task, bound, tuple(rules), tuple(targets), progress,
phase, has_evidence, interrupted, legacy)
return context
return self._operation("refresh_bound_project", task_id, refresh)
def _assert_mutable_membership(self, task_id: str) -> None:
if self._store.get_task(task_id).primary_project_id is not None:
raise TaskCenterError("project_binding", "bound project membership is immutable")
def tasks(self, status: TaskStatus | None = None, *, read_control=None) -> tuple[TaskRecord, ...]:
return self._operation("list_tasks", None, lambda: self._store.list_tasks(status, read_control=read_control))
def update_task(self, task_id: str, *, name: str, note: str) -> TaskRecord:
return self._idle_quick_run_operation(
@@ -121,10 +283,20 @@ class TaskCenterService:
raise TaskCenterError("task_not_deleted", "move the task to deleted before permanently removing it")
return self._store.purge_task(task_id)
return self._operation("purge_task", task_id, purge)
return self._idle_quick_run_operation("purge_task", task_id, purge)
def rules(self, task_id: str) -> tuple[RuleRecord, ...]:
return self._operation("list_rules", task_id, lambda: self._store.list_rules(task_id))
return self._operation("list_rules", task_id, lambda: batch_rule_view(self._store, task_id))
def _execution_rules(self, task_id: str):
task = self._store.get_task(task_id)
if task.target_plan_mode:
rows = self._store.list_target_plan(task_id)
rules = compile_target_rules(tuple(rows))
if not rules:
raise TaskCenterError("enabled_rule_required", "target plan has no enabled targets")
return rules
return batch_rule_view(self._store, task_id, strict=True)
def add_rule(
self,
@@ -140,17 +312,14 @@ class TaskCenterService:
return self._idle_quick_run_operation(
"add_rule",
task_id,
lambda: self._editable_rules(
task_id,
lambda: self._store.add_rule(
task_id,
old_part_number,
new_part_number,
lambda: mutate_batch_rules(
self, task_id, 'add',
old_part_number=old_part_number,
new_part_number=new_part_number,
enabled=enabled,
custom_value_enabled=custom_value_enabled,
custom_value=custom_value,
sync_nc=sync_nc,
),
),
)
@@ -168,17 +337,14 @@ class TaskCenterService:
return self._idle_quick_run_operation(
"update_rule",
None,
lambda: self._editable_rules(
self._store.get_rule(rule_id).task_id,
lambda: self._store.update_rule(
rule_id,
lambda: mutate_batch_rules(
self, self._store.get_rule(rule_id).task_id, 'update', rule_id=rule_id,
old_part_number=old_part_number,
new_part_number=new_part_number,
enabled=enabled,
custom_value_enabled=custom_value_enabled,
custom_value=custom_value,
sync_nc=sync_nc,
),
),
)
@@ -186,21 +352,58 @@ class TaskCenterService:
self._idle_quick_run_operation(
"delete_rule",
None,
lambda: self._editable_rules(self._store.get_rule(rule_id).task_id, lambda: self._store.delete_rule(rule_id)),
lambda: mutate_batch_rules(self, self._store.get_rule(rule_id).task_id, 'delete', rule_id=rule_id),
)
def move_rule(self, rule_id: str, offset: int) -> tuple[RuleRecord, ...]:
return self._idle_quick_run_operation(
"move_rule",
None,
lambda: self._editable_rules(self._store.get_rule(rule_id).task_id, lambda: self._store.move_rule(rule_id, offset)),
lambda: mutate_batch_rules(self, self._store.get_rule(rule_id).task_id, 'move', rule_id=rule_id, offset=offset),
)
def projects(self, task_id: str) -> tuple[ProjectRecord, ...]:
return self._operation("list_projects", task_id, lambda: self._store.list_projects(task_id))
def collect_target_inventory(self, task_id: str, old_part_numbers: tuple[str, ...] | None = None,
*, stop_event=None, on_progress=None):
delegated = self._project_task_service(task_id)
if delegated is not self:
return delegated.collect_target_inventory(task_id, old_part_numbers, **control_options(stop_event, on_progress))
def collect():
from .bom_batch import _assert_editable
_assert_editable(self, task_id)
check_cancelled(stop_event)
rules = batch_rule_view(self._store, task_id, strict=True)
prior = self._store.list_target_plan(task_id)
requested = old_part_numbers or tuple(rule.old_part_number for rule in rules if rule.enabled)
parts = tuple(dict.fromkeys((*requested, *(row.target.old_part_number for row in prior))))
if not parts:
raise TaskCenterError("target_inventory", "add an old Part Number before collecting inventory")
project = self._store.list_projects(task_id)
if len(project) != 1:
raise TaskCenterError("target_inventory", "target inventory requires one project task")
with measure_phase(self._logging, task_id, 'collect_inventory', unit='component',
project_path=str(project[0].path)) as metric:
report_progress(on_progress, f'正在采集工程:{project[0].display_name}')
rows = collect_target_inventory(self._quick_run_preparer, project[0].path, parts,
**control_options(stop_event, on_progress))
check_cancelled(stop_event)
metric['completed_units'] = len(rows)
with self._store.transaction():
if self._store.list_target_plan(task_id) != prior:
raise TaskCenterError('target_identity', '位号计划在采集时已改变,请重新采集')
current = self._store.record_target_inventory(task_id, rows)
known = {row.target.key: row for row in prior}
seeded = seed_defaults(current, rules)
result = tuple(known.get(row.target.key, row) for row in seeded)
check_cancelled(stop_event)
return self._store.replace_target_plan(task_id, result)
return self._idle_quick_run_operation("collect_target_inventory", task_id, collect)
def scan_projects(self, task_id: str, root: Path) -> tuple[ProjectRecord, ...]:
def scan_and_sync() -> tuple[ProjectRecord, ...]:
self._assert_mutable_membership(task_id)
task = self._store.get_task(task_id)
if self._has_current_quick_run_evidence(task_id):
raise TaskCenterError(
@@ -248,6 +451,7 @@ class TaskCenterService:
def set_project_selected(self, project_id: str, selected: bool) -> ProjectRecord:
def set_selected() -> ProjectRecord:
project = self._project_owner(project_id)
self._assert_mutable_membership(project.task_id)
if self._has_current_quick_run_evidence(project.task_id) and not self._retryable_quick_run(project.task_id):
raise TaskCenterError("quick_run_options_locked", "project selection is frozen while queue evidence exists")
snapshot = self._runner.set_project_selected(project.task_id, project_id, selected)
@@ -257,6 +461,7 @@ class TaskCenterService:
def select_all_projects(self, task_id: str) -> tuple[ProjectRecord, ...]:
def select() -> tuple[ProjectRecord, ...]:
self._assert_mutable_membership(task_id)
if self._has_current_quick_run_evidence(task_id) and not self._retryable_quick_run(task_id):
raise TaskCenterError("quick_run_options_locked", "project selection is frozen while queue evidence exists")
return self._runner.set_projects_selected(
@@ -269,6 +474,7 @@ class TaskCenterService:
def clear_project_selection(self, task_id: str) -> tuple[ProjectRecord, ...]:
def clear() -> tuple[ProjectRecord, ...]:
self._assert_mutable_membership(task_id)
if self._has_current_quick_run_evidence(task_id) and not self._retryable_quick_run(task_id):
raise TaskCenterError("quick_run_options_locked", "project selection is frozen while queue evidence exists")
return self._runner.set_projects_selected(task_id, False).projects
@@ -329,12 +535,17 @@ class TaskCenterService:
def prepare_quick_run(self, task_id: str) -> QuickRunResult:
"""Create the legacy VBS handoff without starting a task-center trial."""
delegated = self._project_task_service(task_id)
if delegated is not self:
return delegated.prepare_quick_run(task_id)
def prepare() -> QuickRunResult:
task = self._store.get_task(task_id)
result = self._quick_run_preparer.prepare(
preparer = (self._quick_run_preparer.ensure_batch_handoff
if task.target_plan_mode else self._quick_run_preparer.prepare)
result = preparer(
task_id,
self._store.list_projects(task_id),
self._store.list_rules(task_id),
self._execution_rules(task_id),
copy_part_number_to_value=task.copy_part_number_to_value,
)
append_task_event(
@@ -361,6 +572,8 @@ class TaskCenterService:
)
return result
from .task_queue import assert_task_queue_idle
assert_task_queue_idle(self._logging.root)
with _quick_run_lease(self._logging.root):
return self._operation("prepare_quick_run", task_id, prepare)
@@ -384,17 +597,22 @@ class TaskCenterService:
details={"copy_part_label_to_value": enabled})
return task
from .task_queue import assert_task_queue_idle
assert_task_queue_idle(self._logging.root)
with _quick_run_lease(self._logging.root):
return self._operation("set_value_policy", task_id, update)
def execute_quick_run(self, task_id: str, *, expected_item: tuple[str, str, str, str] | None = None) -> QuickRunStepResult:
"""Execute one replacement rule through restoration and verification."""
delegated = self._project_task_service(task_id)
if delegated is not self:
return delegated.execute_quick_run(task_id, expected_item=expected_item)
def execute() -> QuickRunStepResult:
task = self._store.get_task(task_id)
result = self._quick_run_preparer.execute_step(
task_id,
self._store.list_projects(task_id),
self._store.list_rules(task_id),
self._execution_rules(task_id),
copy_part_number_to_value=task.copy_part_number_to_value,
**({"expected_item": expected_item} if expected_item is not None else {}),
)
@@ -410,6 +628,8 @@ class TaskCenterService:
self._logging.logger.info("quick_run_executed task_id=%s state=%s", task_id, result.state)
return result
from .task_queue import assert_task_queue_idle
assert_task_queue_idle(self._logging.root)
with _quick_run_lease(self._logging.root):
return self._operation("execute_quick_run", task_id, execute)
@@ -420,26 +640,41 @@ class TaskCenterService:
expected_item,
stop_event: threading.Event,
continue_after_backup_failure: bool = False,
reuse_project_session: bool = True,
):
delegated = self._project_task_service(task_id)
if delegated is not self:
return delegated.execute_quick_run_queue(task_id, expected_item=expected_item,
stop_event=stop_event, continue_after_backup_failure=continue_after_backup_failure,
reuse_project_session=reuse_project_session)
from .batch import execute_batch
from .task_queue import assert_task_queue_idle
assert_task_queue_idle(self._logging.root)
with _quick_run_lease(self._logging.root):
if self._store.has_active_project():
raise TaskCenterError('active_project_exists', '人工流程已有活动工程,不能同时启动自动队列。')
if self._store.get_task(task_id).status not in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.RUNNING, TaskStatus.PAUSED}:
raise TaskCenterError('quick_run_task_state', '当前任务状态不允许启动自动队列。')
try:
result = self._operation(
'execute_quick_run_queue',
task_id,
lambda: execute_batch(
self,
with measure_phase(self._logging, task_id, 'task_total', unit='task') as metric:
result = self._operation(
'execute_quick_run_queue',
task_id,
expected_item=expected_item,
stop_event=stop_event,
continue_after_backup_failure=continue_after_backup_failure,
),
)
lambda: execute_batch(
self,
task_id,
expected_item=expected_item,
stop_event=stop_event,
continue_after_backup_failure=continue_after_backup_failure,
reuse_project_session=reuse_project_session,
),
)
metric['state'] = 'paused' if result.paused else 'failed' if result.progress.failed_items else 'completed'
metric['completed_units'] = int(result.progress.queue_complete and not result.progress.failed_items and not result.paused)
metric['completed_steps'] = result.progress.completed_items
metric['saved_steps'] = result.progress.saved_items
metric['failed_steps'] = result.progress.failed_items
if result.paused:
self._pause_quick_run_queue(task_id, 'queue paused at item boundary')
return result
@@ -451,14 +686,19 @@ class TaskCenterService:
def prepare_failed_quick_run(self, task_id: str) -> QuickRunProgress:
"""Reset only failed projects and discard the finished queue handoff."""
delegated = self._project_task_service(task_id)
if delegated is not self:
return delegated.prepare_failed_quick_run(task_id)
def prepare_retry() -> QuickRunProgress:
task = self._store.get_task(task_id)
if self._quick_run_preparer.has_interrupted(task_id):
raise TaskCenterError('quick_run_uncertain', '原生替换结果尚未核验,不能归档或重试。请先核验并恢复。')
if task.status is not TaskStatus.RUNNING:
raise TaskCenterError("quick_run_task_state", "当前任务没有可重试的失败项")
progress = self._quick_run_preparer.progress(
task_id,
self._store.list_projects(task_id),
self._store.list_rules(task_id),
self._execution_rules(task_id),
copy_part_number_to_value=task.copy_part_number_to_value,
)
failed_paths = {
@@ -492,19 +732,32 @@ class TaskCenterService:
self._quick_run_preparer.ensure_batch_handoff(
task_id,
self._store.list_projects(task_id),
self._store.list_rules(task_id),
self._execution_rules(task_id),
copy_part_number_to_value=task.copy_part_number_to_value,
)
return self._quick_run_preparer.progress(
task_id,
self._store.list_projects(task_id),
self._store.list_rules(task_id),
self._execution_rules(task_id),
copy_part_number_to_value=task.copy_part_number_to_value,
)
from .task_queue import assert_task_queue_idle
assert_task_queue_idle(self._logging.root)
with _quick_run_lease(self._logging.root):
return self._operation("prepare_failed_quick_run", task_id, prepare_retry)
def start_new_round(self, task_id: str) -> tuple[TaskRecord, ...]:
"""Archive and reopen completed members of the selected task's batch."""
from .new_round import start_new_round
return self._idle_quick_run_operation('start_new_round', task_id,
lambda: start_new_round(self, task_id))
def inspect_bom_batch(self, task_id: str, path: Path, *, stop_event=None, on_progress=None):
from .bom_import_report import inspect_batch
return self._idle_quick_run_operation('inspect_bom_batch', task_id,
lambda: inspect_batch(self, task_id, path, **control_options(stop_event, on_progress)))
def _pause_quick_run_queue(self, task_id: str, message: str) -> None:
if self._store.get_task(task_id).status is TaskStatus.RUNNING:
self._store.set_task_status(task_id, TaskStatus.PAUSED, summary=message)
@@ -514,8 +767,34 @@ class TaskCenterService:
def batch_feedback(self):
return self._batch_feedback
def execution_feedback(self, task_id: str | None, *, started_after: float, read_control=None):
"""Read the actual executing task, independent of the selected task."""
from .execution_feedback import ExecutionFeedback, read_feedback
if read_control is not None:
read_control.checkpoint()
queue = getattr(self, '_task_queue_feedback', None)
position, total = 1, 1
if queue:
_, task_id, position, total = queue
if not task_id:
return ExecutionFeedback(None)
child = self._facade_for_task_record(
self._store.get_task(task_id, read_control=read_control), force=True)
if read_control is not None:
read_control.checkpoint()
batch = child.batch_feedback()
message = batch[2] if batch else '正在准备执行'
value = read_feedback(task_id, position, total, message,
child._quick_run_preparer.data_root, started_after)
if read_control is not None:
read_control.checkpoint()
return value
def quick_run_phase(self, task_id: str) -> str:
"""Read the current task's local quick-run phase without executing COM work."""
delegated = self._project_task_service(task_id)
if delegated is not self:
return delegated.quick_run_phase(task_id)
def read_phase() -> str:
self._store.get_task(task_id)
if self._retryable_quick_run(task_id):
@@ -528,9 +807,15 @@ class TaskCenterService:
return self._operation("quick_run_phase", task_id, read_phase)
def has_interrupted_quick_run(self, task_id: str) -> bool:
delegated = self._project_task_service(task_id)
if delegated is not self:
return delegated.has_interrupted_quick_run(task_id)
return self._quick_run_preparer.has_interrupted(task_id)
def recover_quick_run(self, task_id: str, *, confirmed: bool = False) -> QuickRunStepResult:
delegated = self._project_task_service(task_id)
if delegated is not self:
return delegated.recover_quick_run(task_id, confirmed=confirmed)
from .recovery import recover
def reconcile() -> QuickRunStepResult:
@@ -538,10 +823,12 @@ class TaskCenterService:
if task.status is TaskStatus.DELETED:
raise TaskCenterError("quick_run_recovery", "请先恢复已删除的任务记录,再核验其中断步骤。")
projects = self._store.list_projects(task_id)
if any(project.selected and project.status not in {ProjectStatus.PENDING, ProjectStatus.COMPLETED} for project in projects):
if any(project.selected and project.status not in {ProjectStatus.PENDING, ProjectStatus.COMPLETED}
and not (project.status is ProjectStatus.FAILED
and project.summary.startswith('quick_run_result:')) for project in projects):
raise TaskCenterError("quick_run_recovery", "工程包含手动执行阶段或失败记录,不能混用自动队列恢复。")
result = recover(self._quick_run_preparer, task_id, projects,
self._store.list_rules(task_id), copy_part_number_to_value=task.copy_part_number_to_value,
self._execution_rules(task_id), copy_part_number_to_value=task.copy_part_number_to_value,
confirmed=confirmed)
if task.status in {TaskStatus.PAUSED, TaskStatus.FAILED}:
self._store.set_task_status(task_id, TaskStatus.READY, summary="interrupted quick-run reconciled")
@@ -550,28 +837,60 @@ class TaskCenterService:
message=result.message, details={"state": result.state, "evidence": str(result.log_path.parent)})
return result
from .task_queue import assert_task_queue_idle
assert_task_queue_idle(self._logging.root)
with _quick_run_lease(self._logging.root):
return self._operation("recover_quick_run", task_id, reconcile)
def quick_run_progress(self, task_id: str) -> QuickRunProgress:
delegated = self._project_task_service(task_id)
if delegated is not self:
return delegated.quick_run_progress(task_id)
return self._operation("quick_run_progress", task_id, lambda: self._synchronize_quick_run_progress(task_id))
def has_quick_run_evidence(self, task_id: str) -> bool:
return self._quick_run_preparer.evidence_path(task_id) is not None
return self._project_task_service(task_id)._quick_run_preparer.evidence_path(task_id) is not None
def _has_current_quick_run_evidence(self, task_id: str) -> bool:
evidence = self._quick_run_preparer.evidence_path(task_id)
return evidence == self._quick_run_preparer._data_root / "quick-run"
preparer = self._project_task_service(task_id)._quick_run_preparer
evidence = preparer.evidence_path(task_id)
return evidence == preparer.data_root / "quick-run"
def tail_log(self, task_id: str, *, limit: int = 100) -> tuple[str, ...]:
if limit < 1:
def tail_log(self, task_id: str, *, limit: int | None = 100) -> tuple[str, ...]:
if limit is not None and limit < 1:
raise TaskCenterError("log_limit", "log line limit must be positive")
self._store.get_task(task_id)
path = self._logging.root / "tasks" / task_id / "events.jsonl"
try:
if limit is None:
# Completed tasks show all retained steps, including rotated logs.
with self._logging._event_lock:
paths = [path.with_name(f'{path.name}.{i}') for i in range(_EVENT_BACKUP_COUNT, 0, -1)]
paths.append(path)
return tuple(line for source in paths if source.exists()
for line in source.read_text(encoding='utf-8').splitlines())
return _tail_utf8_lines(path, limit) if path.exists() else ()
except (OSError, UnicodeError) as error:
raise TaskCenterError("log_read", "cannot read task event log") from error
def read_task_log(self, task_id: str, *, mode='latest', cursor=None, limit=200, read_control=None):
"""Read a bounded page; callers may keep physical cursors across rotation."""
from .task_logs import TaskLogReader
if read_control is not None:
read_control.checkpoint()
self._store.get_task(task_id, read_control=read_control)
if mode not in {'latest', 'older', 'poll'} or not 1 <= limit <= 1000:
raise TaskCenterError('log_page', 'invalid log page request')
reader = TaskLogReader(self._logging.root / 'tasks' / task_id / 'events.jsonl',
self._logging._event_lock, backup_count=_EVENT_BACKUP_COUNT,
read_control=read_control)
try:
if mode == 'latest':
return reader.latest(limit=limit)
return reader.older(cursor, limit=limit) if mode == 'older' else reader.poll(cursor, limit=limit)
except (OSError, UnicodeError) as error:
raise TaskCenterError('log_read', 'cannot read task event log') from error
def open_task_log(self, task_id: str) -> Path:
def open_path() -> Path:
self._store.get_task(task_id)
@@ -589,6 +908,9 @@ class TaskCenterService:
return self._logging.report_exception("ui", error)
def open_evidence(self, task_id: str, project_id: str) -> Path:
delegated = self._project_task_service(task_id)
if delegated is not self:
return delegated.open_evidence(task_id, project_id)
def open_path() -> Path:
project = next((item for item in self._store.list_projects(task_id) if item.project_id == project_id), None)
if project is None:
@@ -605,21 +927,38 @@ class TaskCenterService:
return self._operation("open_evidence", task_id, open_path)
def open_quick_run_evidence(self, task_id: str) -> Path:
delegated = self._project_task_service(task_id)
if delegated is not self:
return delegated.open_quick_run_evidence(task_id)
def open_path() -> Path:
self._store.get_task(task_id)
path = self._quick_run_preparer.evidence_path(task_id)
if path is None:
raise TaskCenterError("evidence_missing", "quick-run evidence is unavailable for this task")
from .new_round import latest_archive
path = latest_archive(self._quick_run_preparer)
if path is None:
raise TaskCenterError("evidence_missing", "quick-run evidence is unavailable for this task")
self._path_opener(path)
return path
return self._operation("open_quick_run_evidence", task_id, open_path)
def open_round_history(self, task_id: str) -> Path:
"""Open all retained rounds, or the current evidence before the first reset."""
facade = self._project_task_service(task_id)
rounds = facade._quick_run_preparer.data_root / 'rounds'
if rounds.is_dir():
return self._operation('open_round_history', task_id,
lambda: (self._path_opener(rounds), rounds)[1])
return facade.open_quick_run_evidence(task_id)
def _operation(self, name: str, task_id: str | None, action: Callable[[], _Result]) -> _Result:
timestamp = self._clock().isoformat()
self._logging.logger.info("operation_start=%s task_id=%s at=%s", name, task_id or "", timestamp)
try:
result = action()
except QueryCancelled:
raise
except TaskCenterError as error:
self._logging.report_exception(name, error)
raise
@@ -635,12 +974,14 @@ class TaskCenterService:
task_id: str | None,
action: Callable[[], _Result],
) -> _Result:
from .task_queue import assert_task_queue_idle
assert_task_queue_idle(self._logging.root)
with _quick_run_lease(self._logging.root):
return self._operation(name, task_id, action)
def _manual_operation(self, name: str, task_id: str, action: Callable[[], _Result]) -> _Result:
def checked_action():
if self._quick_run_preparer.evidence_path(task_id) is not None:
if self._project_task_service(task_id)._quick_run_preparer.evidence_path(task_id) is not None:
raise TaskCenterError('quick_run_manual_operation', '此任务属于自动队列,不能混用人工采集、跳过或重试。请使用继续队列或核验恢复。')
return action()
@@ -658,7 +999,7 @@ class TaskCenterService:
progress = self._quick_run_preparer.progress(
task_id,
projects,
self._store.list_rules(task_id),
self._execution_rules(task_id),
copy_part_number_to_value=task.copy_part_number_to_value,
)
by_path = {os.path.normcase(os.path.abspath(str(project.path))): project.project_id for project in projects}
@@ -0,0 +1,18 @@
"""Give the legacy single-step entry the same durable private execution boundary."""
from uuid import uuid4
from .errors import TaskCenterError
from .schematic_backup import create_schematic_backup
def prepare_private_single_step(preparer, task_id, projects, rules, copy_part_number_to_value):
progress = preparer.progress(task_id, projects, rules,
copy_part_number_to_value=copy_part_number_to_value)
if progress.queue_complete or progress.next_project_path is None:
raise TaskCenterError('quick_run_complete', 'all replacement rules in this queue are complete')
# Back up before discovery or any CAD activation. A standalone invocation
# has no batch backup coordinator to provide this boundary.
create_schematic_backup(preparer.data_root, progress.next_project_path,
preparer.data_root / 'quick-run-history' / ('batch-' + uuid4().hex))
preparer.ensure_batch_handoff(task_id, projects, rules,
copy_part_number_to_value=copy_part_number_to_value)
@@ -0,0 +1,122 @@
"""Optional Excel interchange for target plans."""
from __future__ import annotations
from pathlib import Path
from openpyxl import Workbook, load_workbook
from openpyxl.styles import Font, PatternFill
from openpyxl.worksheet.datavalidation import DataValidation
from .errors import TaskCenterError
from .target_plan import TargetPlanRow, compile_target_rules
HEADERS = ("project_path", "project_name", "schematic_name", "sheet_number", "uid",
"refdes", "old_part_number", "old_value", "enabled", "new_part_number",
"custom_value_enabled", "custom_value", "sync_nc")
def export_target_plan(store, task_id: str, path: Path) -> Path:
rows = store.list_target_plan(task_id)
workbook = Workbook()
sheet = workbook.active
sheet.title = "Target Plan"
sheet.append(HEADERS)
for row in rows:
target = row.target
values = (str(target.project_path), target.project_path.name, target.schematic_name,
target.sheet_number, target.uid, target.refdes, target.old_part_number,
target.old_value, row.enabled, row.new_part_number, row.custom_value_enabled,
row.custom_value, row.sync_nc)
sheet.append(values)
for cell in sheet[sheet.max_row]:
if isinstance(cell.value, str):
cell.data_type = "s"
for cell in sheet[1]:
cell.font = Font(bold=True, color="FFFFFF")
cell.fill = PatternFill("solid", fgColor="28545A")
sheet.freeze_panes = "I2"
sheet.auto_filter.ref = sheet.dimensions
for column in ("I", "K", "M"):
check = DataValidation(type="list", formula1='"TRUE,FALSE"')
sheet.add_data_validation(check)
check.add(f"{column}2:{column}{max(sheet.max_row, 2)}")
for column, width in {"A": 45, "B": 22, "C": 20, "D": 12, "E": 26,
"F": 14, "G": 20, "H": 20, "I": 12, "J": 20,
"K": 22, "L": 20, "M": 12}.items():
sheet.column_dimensions[column].width = width
path = Path(path)
workbook.save(path)
return path
def import_target_plan(store, task_id: str, path: Path) -> tuple[TargetPlanRow, ...]:
rows = read_target_plan(store, task_id, path)
return store.replace_target_plan(task_id, rows)
def read_target_plan(store, task_id: str, path: Path) -> tuple[TargetPlanRow, ...]:
baseline = store.list_target_plan(task_id)
expected = {row.target.key: row for row in baseline}
if not expected:
raise TaskCenterError("target_inventory", "collect component inventory before importing a plan")
try:
workbook = load_workbook(Path(path), read_only=True, data_only=False)
if len(workbook.worksheets) != 1:
raise ValueError("workbook must have exactly one plan sheet")
records = list(workbook.active.iter_rows(values_only=False))
if not records or tuple(cell.value for cell in records[0]) != HEADERS:
raise ValueError("plan columns changed")
by_key: dict[tuple[str, str, str, str], TargetPlanRow] = {}
for cells in records[1:]:
values = tuple(cell.value for cell in cells)
if all(value is None for value in values):
continue
if len(values) != len(HEADERS) or any(cell.data_type == "f" for cell in cells):
raise ValueError("invalid or formula plan row")
identity = tuple("" if value is None else str(value) for value in values[:8])
key = (str(Path(identity[0]).resolve(strict=False)).casefold(),
identity[2], identity[3], identity[4])
original = expected.get(key)
if original is None or key in by_key:
raise ValueError("forged or duplicate target")
target = original.target
if identity != (str(target.project_path), target.project_path.name, target.schematic_name,
target.sheet_number, target.uid, target.refdes, target.old_part_number,
target.old_value):
raise ValueError("target baseline changed")
enabled, new_part, custom_enabled, custom_value, sync_nc = values[8:13]
enabled = _excel_bool(enabled)
custom_enabled = _excel_bool(custom_enabled)
sync_nc = _excel_bool(sync_nc)
if not isinstance(new_part, str) and new_part is not None:
raise ValueError("new Part Number must be text")
if not isinstance(custom_value, str) and custom_value is not None:
raise ValueError("custom Value must be text")
by_key[key] = TargetPlanRow(target, enabled, new_part or "", custom_enabled,
custom_value or "", sync_nc)
if set(by_key) != set(expected):
raise ValueError("plan rows are missing")
result = tuple(by_key.values())
compile_target_rules(result)
return result
except (OSError, ValueError, TypeError, KeyError) as error:
raise TaskCenterError("target_plan_import", str(error)) from error
finally:
try:
workbook.close()
except (UnboundLocalError, AttributeError):
pass
def _excel_bool(value) -> bool:
if type(value) is bool:
return value
if isinstance(value, (int, float)) and value in (0, 1):
return bool(value)
if isinstance(value, str) and value.strip().casefold() in {"true", "是", "1"}:
return True
if isinstance(value, str) and value.strip().casefold() in {"false", "否", "0"}:
return False
raise ValueError("plan switches must be Boolean")
+111 -219
View File
@@ -6,22 +6,22 @@ from collections.abc import Iterator, Sequence
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
import csv
import hashlib
import io
import os
from pathlib import Path
import sqlite3
import threading
from uuid import uuid4
from dx_productivity.part_replace.inputs import InputError, parse_mapping_bytes
from .rule_validation import validate_mapping_pairs
from .store_schema import StoreSchema
from .store_target_plan import TargetPlanRepository
from .store_read_model import TaskBundle, checkpoint, read_lock, read_task_bundle
from .errors import TaskCenterError
from .models import ProjectRecord, ProjectStatus, RuleRecord, TaskRecord, TaskStatus
_SCHEMA_VERSION = 5
_INTERRUPTED_PROJECT_STATES = {
ProjectStatus.CAPTURING_BEFORE,
ProjectStatus.CAPTURING_AFTER,
@@ -133,217 +133,89 @@ class TaskStore:
self._connection.row_factory = sqlite3.Row
with self._lock:
self._connection.execute("PRAGMA foreign_keys = ON")
self._schema = StoreSchema(self)
self._target_plans = TargetPlanRepository(self)
self._initialize_schema()
def read_task_bundle(self, task_id: str, read_control=None) -> TaskBundle:
return read_task_bundle(self, task_id, read_control)
def close(self) -> None:
with self._lock:
self._connection.close()
def _initialize_schema(self) -> None:
with self.transaction():
self._connection.execute(
"CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL)"
)
version_row = self._connection.execute(
"SELECT value FROM metadata WHERE key = 'schema_version'"
).fetchone()
if version_row is None:
self._create_schema_v1()
self._create_attempt_schema()
self._create_migration_recovery_schema()
self._create_external_request_schema()
self._connection.execute(
"INSERT INTO metadata(key, value) VALUES ('schema_version', ?)",
(str(_SCHEMA_VERSION),),
)
elif int(version_row["value"]) == 1:
self._create_attempt_schema()
self._create_migration_recovery_schema()
self._create_external_request_schema()
self._migrate_v1_attemptless_active_work()
self._connection.execute("UPDATE metadata SET value = ? WHERE key = 'schema_version'", (str(_SCHEMA_VERSION),))
elif int(version_row["value"]) == 2:
self._create_migration_recovery_schema()
self._create_external_request_schema()
self._connection.execute("UPDATE metadata SET value = ? WHERE key = 'schema_version'", (str(_SCHEMA_VERSION),))
elif int(version_row["value"]) == 3:
self._create_external_request_schema()
self._connection.execute("UPDATE metadata SET value = ? WHERE key = 'schema_version'", (str(_SCHEMA_VERSION),))
elif int(version_row["value"]) == 4:
self._connection.execute("UPDATE metadata SET value = ? WHERE key = 'schema_version'", (str(_SCHEMA_VERSION),))
elif int(version_row["value"]) != _SCHEMA_VERSION:
raise TaskCenterError("schema_version", "task database schema version is unsupported")
else:
self._create_migration_recovery_schema()
self._create_external_request_schema()
self._ensure_task_columns()
self._ensure_rule_columns()
return self._schema._initialize_schema()
def _create_schema_v1(self) -> None:
statements = (
"""CREATE TABLE IF NOT EXISTS tasks (
task_id TEXT PRIMARY KEY,
name TEXT NOT NULL COLLATE NOCASE UNIQUE,
note TEXT NOT NULL,
discovery_root TEXT,
status TEXT NOT NULL,
created_utc TEXT NOT NULL,
updated_utc TEXT NOT NULL,
started_utc TEXT,
completed_utc TEXT,
deleted_utc TEXT,
status_before_delete TEXT,
error_id TEXT,
summary TEXT NOT NULL DEFAULT ''
)""",
"""CREATE TABLE IF NOT EXISTS rules (
rule_id TEXT PRIMARY KEY,
task_id TEXT NOT NULL REFERENCES tasks(task_id),
position INTEGER NOT NULL,
old_part_number TEXT NOT NULL,
new_part_number TEXT NOT NULL,
enabled INTEGER NOT NULL CHECK(enabled IN (0, 1)),
custom_value_enabled INTEGER NOT NULL DEFAULT 0 CHECK(custom_value_enabled IN (0, 1)),
custom_value TEXT NOT NULL DEFAULT '',
sync_nc INTEGER NOT NULL DEFAULT 1 CHECK(sync_nc IN (0, 1)),
UNIQUE(task_id, position)
)""",
"""CREATE TABLE IF NOT EXISTS projects (
project_id TEXT PRIMARY KEY,
task_id TEXT NOT NULL REFERENCES tasks(task_id),
display_name TEXT NOT NULL,
path TEXT NOT NULL,
path_identity TEXT NOT NULL,
discovery_root TEXT NOT NULL,
selected INTEGER NOT NULL CHECK(selected IN (0, 1)),
available INTEGER NOT NULL CHECK(available IN (0, 1)),
status TEXT NOT NULL,
retry_count INTEGER NOT NULL DEFAULT 0,
error_id TEXT,
summary TEXT NOT NULL DEFAULT '',
UNIQUE(task_id, path_identity)
)""",
)
for statement in statements:
self._connection.execute(statement)
return self._schema._create_schema_v1()
def _create_attempt_schema(self) -> None:
self._connection.execute(
"""CREATE TABLE IF NOT EXISTS attempts (
project_id TEXT NOT NULL REFERENCES projects(project_id),
attempt_number INTEGER NOT NULL,
probe_source TEXT NOT NULL,
baseline_size INTEGER NOT NULL,
baseline_sha256 TEXT NOT NULL,
baseline_modified_ns INTEGER NOT NULL,
rules_json TEXT NOT NULL,
before_path TEXT,
before_size INTEGER,
before_sha256 TEXT,
before_modified_ns INTEGER,
instruction_json TEXT,
PRIMARY KEY(project_id, attempt_number)
)"""
)
return self._schema._create_attempt_schema()
def _create_migration_recovery_schema(self) -> None:
self._connection.execute(
"""CREATE TABLE IF NOT EXISTS migration_recoveries (
project_id TEXT PRIMARY KEY REFERENCES projects(project_id),
task_id TEXT NOT NULL REFERENCES tasks(task_id),
project_before TEXT NOT NULL,
project_after TEXT NOT NULL,
task_before TEXT,
task_after TEXT,
error_id TEXT NOT NULL,
project_summary TEXT NOT NULL,
task_summary TEXT
)"""
)
return self._schema._create_migration_recovery_schema()
def _create_external_request_schema(self) -> None:
self._connection.execute(
"""CREATE TABLE IF NOT EXISTS external_requests (
source TEXT NOT NULL,
idempotency_key TEXT NOT NULL,
request_hash TEXT NOT NULL,
task_id TEXT NOT NULL,
created_utc TEXT NOT NULL,
PRIMARY KEY(source, idempotency_key)
)"""
)
return self._schema._create_external_request_schema()
def _migrate_v1_attemptless_active_work(self) -> None:
"""Fail closed because v1 active projects cannot have an attempt evidence context."""
states = tuple(status.value for status in _V1_ATTEMPTLESS_ACTIVE_STATES)
rows = self._connection.execute(
f"SELECT project_id, task_id, status FROM projects WHERE status IN ({', '.join('?' for _ in states)})",
states,
).fetchall()
if not rows:
return
error = TaskCenterError("v1_attempt_context_missing", "migration interrupted active project; retry the project")
for row in rows:
summary = f"migration interrupted prior project state: {row['status']}; retry the project"
task = self.get_task(row["task_id"])
task_summary = "migration interrupted active project; retry the project"
self._connection.execute(
"UPDATE projects SET status = ?, error_id = ?, summary = ? WHERE project_id = ?",
(ProjectStatus.FAILED.value, error.error_id, summary, row["project_id"]),
)
self._connection.execute(
"""INSERT OR REPLACE INTO migration_recoveries(
project_id, task_id, project_before, project_after, task_before, task_after,
error_id, project_summary, task_summary
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(
row["project_id"],
row["task_id"],
row["status"],
ProjectStatus.FAILED.value,
TaskStatus.RUNNING.value if task.status is TaskStatus.RUNNING else None,
TaskStatus.PAUSED.value if task.status is TaskStatus.RUNNING else None,
error.error_id,
summary,
task_summary if task.status is TaskStatus.RUNNING else None,
),
)
for task_id in sorted({row["task_id"] for row in rows}):
task = self.get_task(task_id)
if task.status is TaskStatus.RUNNING:
now = self._next_timestamp(task.updated_utc)
self._connection.execute(
"UPDATE tasks SET status = ?, updated_utc = ?, error_id = ?, summary = ? WHERE task_id = ?",
(
TaskStatus.PAUSED.value,
_utc_text(now),
error.error_id,
"migration interrupted active project; retry the project",
task_id,
),
)
return self._schema._migrate_v1_attemptless_active_work()
def _ensure_task_columns(self) -> None:
columns = {row["name"] for row in self._connection.execute("PRAGMA table_info(tasks)")}
if "status_before_delete" not in columns:
self._connection.execute("ALTER TABLE tasks ADD COLUMN status_before_delete TEXT")
if "copy_part_number_to_value" not in columns:
return self._schema._ensure_task_columns()
def _create_target_plan_schema(self) -> None:
return self._schema._create_target_plan_schema()
def bind_project_task(self, task_id: str, project_id: str, group_id: str, position: int) -> TaskRecord:
return self._target_plans.bind_project_task(task_id, project_id, group_id, position)
def move_project_task(self, task_id: str, offset: int) -> tuple[TaskRecord, ...]:
return self._target_plans.move_project_task(task_id, offset)
def list_project_group(self, group_id: str) -> tuple[TaskRecord, ...]:
return self._target_plans.list_project_group(group_id)
def replace_target_plan(self, task_id: str, rows) -> tuple:
return self._target_plans.replace_target_plan(task_id, rows)
def record_target_inventory(self, task_id: str, targets) -> tuple:
return self._target_plans.record_target_inventory(task_id, targets)
def list_target_plan(self, task_id: str) -> tuple:
return self._target_plans.list_target_plan(task_id)
def reset_completed_round(self, task_id: str, summary: str) -> TaskRecord:
"""Dedicated reset gate; keep binding, rules and numbered attempt history."""
with self.transaction():
task = self.get_task(task_id)
if task.status is not TaskStatus.COMPLETED:
raise TaskCenterError('new_round_state', 'task is not completed')
self._connection.execute('DELETE FROM target_plan WHERE task_id = ?', (task_id,))
self._connection.execute(
"ALTER TABLE tasks ADD COLUMN copy_part_number_to_value INTEGER NOT NULL DEFAULT 0 CHECK(copy_part_number_to_value IN (0, 1))"
)
"""UPDATE projects SET status = ?, error_id = NULL, summary = '',
retry_count = MAX(retry_count, COALESCE((SELECT MAX(attempt_number)
FROM attempts WHERE attempts.project_id = projects.project_id), 0)) WHERE task_id = ?""",
(ProjectStatus.PENDING.value, task_id))
self._connection.execute(
"""UPDATE tasks SET status = ?, started_utc = NULL, completed_utc = NULL,
error_id = NULL, summary = ?, target_plan_mode = 1, updated_utc = ? WHERE task_id = ?""",
(TaskStatus.DRAFT.value, summary, _utc_text(self._next_timestamp(task.updated_utc)), task_id))
return self.get_task(task_id)
def record_round_commit(self, round_id: str) -> None:
"""Immutable token committed in the same transaction as round resets."""
self._connection.execute('INSERT INTO metadata(key, value) VALUES (?, ?)',
(f'round_committed:{round_id}', '1'))
def round_committed(self, round_id: str) -> bool:
with self._lock:
return self._connection.execute('SELECT 1 FROM metadata WHERE key = ?',
(f'round_committed:{round_id}',)).fetchone() is not None
def _ensure_rule_columns(self) -> None:
columns = {row["name"] for row in self._connection.execute("PRAGMA table_info(rules)")}
if "custom_value_enabled" not in columns:
self._connection.execute(
"ALTER TABLE rules ADD COLUMN custom_value_enabled INTEGER NOT NULL DEFAULT 0 CHECK(custom_value_enabled IN (0, 1))"
)
if "custom_value" not in columns:
self._connection.execute("ALTER TABLE rules ADD COLUMN custom_value TEXT NOT NULL DEFAULT ''")
if "sync_nc" not in columns:
self._connection.execute(
"ALTER TABLE rules ADD COLUMN sync_nc INTEGER NOT NULL DEFAULT 1 CHECK(sync_nc IN (0, 1))"
)
return self._schema._ensure_rule_columns()
@contextmanager
def transaction(self) -> Iterator[None]:
@@ -360,18 +232,21 @@ class TaskStore:
self._transaction_depth += 1
try:
yield
except BaseException:
if outermost:
self._connection.execute("ROLLBACK")
else:
self._connection.execute(f"ROLLBACK TO SAVEPOINT {savepoint}")
self._connection.execute(f"RELEASE SAVEPOINT {savepoint}")
raise
else:
if outermost:
self._connection.execute("COMMIT")
else:
self._connection.execute(f"RELEASE SAVEPOINT {savepoint}")
except BaseException:
try:
if outermost:
self._connection.execute("ROLLBACK")
else:
self._connection.execute(f"ROLLBACK TO SAVEPOINT {savepoint}")
self._connection.execute(f"RELEASE SAVEPOINT {savepoint}")
except BaseException:
# Preserve the original body/commit failure for diagnosis.
pass
raise
finally:
self._transaction_depth -= 1
@@ -432,25 +307,31 @@ class TaskStore:
)
return self.get_task(task.task_id), projects, True
def get_task(self, task_id: str) -> TaskRecord:
with self._lock:
def get_task(self, task_id: str, *, read_control=None) -> TaskRecord:
with read_lock(self, read_control):
row = self._connection.execute("SELECT * FROM tasks WHERE task_id = ?", (task_id,)).fetchone()
checkpoint(read_control)
if row is None:
raise TaskCenterError("unknown_task", "task does not exist")
return self._task_record(row)
def list_tasks(self, status: TaskStatus | None = None) -> tuple[TaskRecord, ...]:
with self._lock:
def list_tasks(self, status: TaskStatus | None = None, *, read_control=None) -> tuple[TaskRecord, ...]:
with read_lock(self, read_control):
if status is None:
rows = self._connection.execute(
"SELECT * FROM tasks WHERE status != ? ORDER BY updated_utc DESC, task_id",
(TaskStatus.DELETED.value,),
).fetchall()
)
else:
rows = self._connection.execute(
"SELECT * FROM tasks WHERE status = ? ORDER BY updated_utc DESC, task_id", (TaskStatus(status).value,)
).fetchall()
return tuple(self._task_record(row) for row in rows)
)
result = []
for row in rows:
checkpoint(read_control)
result.append(self._task_record(row))
checkpoint(read_control)
return tuple(result)
def update_task(self, task_id: str, *, name: str, note: str) -> TaskRecord:
normalized_name = self._task_name(name)
@@ -557,10 +438,13 @@ class TaskStore:
project = self._project_record(self._project_row(project_id))
if project.task_id != task_id:
raise TaskCenterError("project_task_mismatch", "project does not belong to the task")
if project.status not in {ProjectStatus.PENDING, ProjectStatus.COMPLETED}:
raise TaskCenterError("quick_run_project_state", "project state does not allow quick-run completion")
summary = (project_summaries or {}).get(project_id, "current-sheet quick-run queue completed")
if project.status is ProjectStatus.PENDING or project.summary != summary:
recovered_native_failure = (project.status is ProjectStatus.FAILED
and project.summary.startswith('quick_run_result:')
and summary.startswith('quick_run_result:') and summary.endswith(':saved'))
if project.status not in {ProjectStatus.PENDING, ProjectStatus.COMPLETED} and not recovered_native_failure:
raise TaskCenterError("quick_run_project_state", "project state does not allow quick-run completion")
if project.status is not ProjectStatus.COMPLETED or project.summary != summary:
self._connection.execute(
"UPDATE projects SET status = ?, error_id = NULL, summary = ? WHERE project_id = ?",
(ProjectStatus.COMPLETED.value, summary, project_id),
@@ -631,6 +515,7 @@ class TaskStore:
)
self._connection.execute("DELETE FROM migration_recoveries WHERE task_id = ?", (task_id,))
self._connection.execute("DELETE FROM external_requests WHERE task_id = ?", (task_id,))
self._connection.execute("DELETE FROM target_plan WHERE task_id = ?", (task_id,))
self._connection.execute("DELETE FROM rules WHERE task_id = ?", (task_id,))
self._connection.execute("DELETE FROM projects WHERE task_id = ?", (task_id,))
self._connection.execute("DELETE FROM tasks WHERE task_id = ?", (task_id,))
@@ -1038,6 +923,16 @@ class TaskStore:
with self._lock:
return self._project_record(self._project_row(project_id))
def interrupted_projects(self) -> tuple[ProjectRecord, ...]:
"""Read recovery candidates directly, without walking every idle task."""
with self._lock:
states = tuple(status.value for status in _INTERRUPTED_PROJECT_STATES)
rows = self._connection.execute(
f"SELECT * FROM projects WHERE status IN ({', '.join('?' for _ in states)}) ORDER BY project_id",
states,
).fetchall()
return tuple(self._project_record(row) for row in rows)
def recover_interrupted_work(self) -> tuple[str, ...]:
"""Mark projects interrupted during capture or verification as retryable failures."""
with self.transaction():
@@ -1120,14 +1015,7 @@ class TaskStore:
"SELECT old_part_number, new_part_number FROM rules WHERE task_id = ? AND enabled = 1 ORDER BY position",
(task_id,),
).fetchall()
output = io.StringIO(newline="")
writer = csv.writer(output, lineterminator="\n")
writer.writerow(("old_part_number", "new_part_number"))
writer.writerows((row["old_part_number"], row["new_part_number"]) for row in rows)
try:
parse_mapping_bytes(output.getvalue().encode("utf-8"), Path("task-center-rules.csv"))
except InputError as error:
raise TaskCenterError(error.code, error.message) from error
validate_mapping_pairs((row['old_part_number'], row['new_part_number']) for row in rows)
def _rule_row(self, rule_id: str) -> sqlite3.Row:
row = self._connection.execute("SELECT * FROM rules WHERE rule_id = ?", (rule_id,)).fetchone()
@@ -1193,6 +1081,10 @@ class TaskStore:
error_id=row["error_id"],
summary=row["summary"],
copy_part_number_to_value=bool(row["copy_part_number_to_value"]),
group_id=row["group_id"],
group_position=row["group_position"],
primary_project_id=row["primary_project_id"],
target_plan_mode=bool(row["target_plan_mode"]),
)
@staticmethod
@@ -0,0 +1,100 @@
"""Consistent, cancellable task read models on the owning SQLite connection."""
from __future__ import annotations
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from .models import TaskRecord, ProjectRecord, RuleRecord, TaskStatus
from .target_plan import ComponentTarget, TargetPlanRow
@dataclass(frozen=True, slots=True)
class TaskBundle:
"""One database snapshot including task binding/status and its target plan."""
task: TaskRecord
projects: tuple[ProjectRecord, ...]
rules: tuple[RuleRecord, ...]
targets: tuple[TargetPlanRow, ...]
batch_rules: tuple[RuleRecord, ...] | None = None
def checkpoint(read_control):
if read_control is not None:
read_control.checkpoint()
@contextmanager
def read_lock(store, read_control=None):
checkpoint(read_control)
while not store._lock.acquire(timeout=0.05):
checkpoint(read_control)
try:
checkpoint(read_control)
yield
finally:
store._lock.release()
def read_task_bundle(store, task_id: str, read_control=None) -> TaskBundle:
def checkpoint():
if read_control is not None:
read_control.checkpoint()
with read_lock(store, read_control):
started = False
try:
checkpoint()
if store._transaction_depth == 0:
store._connection.execute("BEGIN")
started = True
task = store.get_task(task_id)
checkpoint()
def records(sql, convert):
result = []
for row in store._connection.execute(sql, (task_id,)):
checkpoint()
result.append(convert(row))
checkpoint()
return tuple(result)
projects = records(
"SELECT * FROM projects WHERE task_id = ? ORDER BY path_identity, project_id",
store._project_record,
)
rules = records(
"SELECT * FROM rules WHERE task_id = ? ORDER BY position", store._rule_record,
)
batch_rules = None
if task.group_id and task.status is not TaskStatus.DELETED:
from .batch_rules import merge_rule_view
group_rules = []
for row in store._connection.execute(
"SELECT r.* FROM rules r JOIN tasks t ON t.task_id = r.task_id "
"WHERE t.group_id = ? AND t.status <> ? ORDER BY t.group_position, t.created_utc, t.task_id, r.position",
(task.group_id, TaskStatus.DELETED.value)):
checkpoint()
group_rules.append(store._rule_record(row))
batch_rules = merge_rule_view(group_rules, {r.old_part_number.casefold(): r for r in rules})
def target_record(row):
return TargetPlanRow(
ComponentTarget(Path(row['project_path']), row['schematic_name'], row['sheet_number'],
row['uid'], row['refdes'], row['old_part_number'], row['old_value']),
bool(row['enabled']), row['new_part_number'], bool(row['custom_value_enabled']),
row['custom_value'], bool(row['sync_nc']),
)
targets = records(
"SELECT * FROM target_plan WHERE task_id = ? ORDER BY project_path, schematic_name, sheet_number, refdes, uid",
target_record,
)
checkpoint()
if started:
store._connection.execute("COMMIT")
started = False
return TaskBundle(task, projects, rules, targets, batch_rules)
except BaseException:
if started:
store._connection.execute("ROLLBACK")
raise
@@ -0,0 +1,244 @@
"""Transactional schema upgrades using the owning store connection."""
from __future__ import annotations
from .errors import TaskCenterError
from .models import ProjectStatus, TaskStatus
_SCHEMA_VERSION = 6
_V1_ATTEMPTLESS_ACTIVE_STATES = {ProjectStatus.CAPTURING_BEFORE, ProjectStatus.AWAITING_OPERATOR, ProjectStatus.CAPTURING_AFTER, ProjectStatus.VERIFYING}
class StoreSchema:
def __init__(self, store) -> None:
self._store = store
def _initialize_schema(self) -> None:
with self._store.transaction():
self._store._connection.execute(
"CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL)"
)
version_row = self._store._connection.execute(
"SELECT value FROM metadata WHERE key = 'schema_version'"
).fetchone()
if version_row is None:
self._store._create_schema_v1()
self._store._create_attempt_schema()
self._store._create_migration_recovery_schema()
self._store._create_external_request_schema()
self._store._connection.execute(
"INSERT INTO metadata(key, value) VALUES ('schema_version', ?)",
(str(_SCHEMA_VERSION),),
)
elif int(version_row["value"]) == 1:
self._store._create_attempt_schema()
self._store._create_migration_recovery_schema()
self._store._create_external_request_schema()
self._store._migrate_v1_attemptless_active_work()
self._store._connection.execute("UPDATE metadata SET value = ? WHERE key = 'schema_version'", (str(_SCHEMA_VERSION),))
elif int(version_row["value"]) == 2:
self._store._create_migration_recovery_schema()
self._store._create_external_request_schema()
self._store._connection.execute("UPDATE metadata SET value = ? WHERE key = 'schema_version'", (str(_SCHEMA_VERSION),))
elif int(version_row["value"]) == 3:
self._store._create_external_request_schema()
self._store._connection.execute("UPDATE metadata SET value = ? WHERE key = 'schema_version'", (str(_SCHEMA_VERSION),))
elif int(version_row["value"]) in {4, 5}:
self._store._connection.execute("UPDATE metadata SET value = ? WHERE key = 'schema_version'", (str(_SCHEMA_VERSION),))
elif int(version_row["value"]) != _SCHEMA_VERSION:
raise TaskCenterError("schema_version", "task database schema version is unsupported")
else:
self._store._create_migration_recovery_schema()
self._store._create_external_request_schema()
self._store._ensure_task_columns()
self._store._ensure_rule_columns()
self._store._create_target_plan_schema()
def _create_schema_v1(self) -> None:
statements = (
"""CREATE TABLE IF NOT EXISTS tasks (
task_id TEXT PRIMARY KEY,
name TEXT NOT NULL COLLATE NOCASE UNIQUE,
note TEXT NOT NULL,
discovery_root TEXT,
status TEXT NOT NULL,
created_utc TEXT NOT NULL,
updated_utc TEXT NOT NULL,
started_utc TEXT,
completed_utc TEXT,
deleted_utc TEXT,
status_before_delete TEXT,
error_id TEXT,
summary TEXT NOT NULL DEFAULT ''
)""",
"""CREATE TABLE IF NOT EXISTS rules (
rule_id TEXT PRIMARY KEY,
task_id TEXT NOT NULL REFERENCES tasks(task_id),
position INTEGER NOT NULL,
old_part_number TEXT NOT NULL,
new_part_number TEXT NOT NULL,
enabled INTEGER NOT NULL CHECK(enabled IN (0, 1)),
custom_value_enabled INTEGER NOT NULL DEFAULT 0 CHECK(custom_value_enabled IN (0, 1)),
custom_value TEXT NOT NULL DEFAULT '',
sync_nc INTEGER NOT NULL DEFAULT 1 CHECK(sync_nc IN (0, 1)),
UNIQUE(task_id, position)
)""",
"""CREATE TABLE IF NOT EXISTS projects (
project_id TEXT PRIMARY KEY,
task_id TEXT NOT NULL REFERENCES tasks(task_id),
display_name TEXT NOT NULL,
path TEXT NOT NULL,
path_identity TEXT NOT NULL,
discovery_root TEXT NOT NULL,
selected INTEGER NOT NULL CHECK(selected IN (0, 1)),
available INTEGER NOT NULL CHECK(available IN (0, 1)),
status TEXT NOT NULL,
retry_count INTEGER NOT NULL DEFAULT 0,
error_id TEXT,
summary TEXT NOT NULL DEFAULT '',
UNIQUE(task_id, path_identity)
)""",
)
for statement in statements:
self._store._connection.execute(statement)
def _create_attempt_schema(self) -> None:
self._store._connection.execute(
"""CREATE TABLE IF NOT EXISTS attempts (
project_id TEXT NOT NULL REFERENCES projects(project_id),
attempt_number INTEGER NOT NULL,
probe_source TEXT NOT NULL,
baseline_size INTEGER NOT NULL,
baseline_sha256 TEXT NOT NULL,
baseline_modified_ns INTEGER NOT NULL,
rules_json TEXT NOT NULL,
before_path TEXT,
before_size INTEGER,
before_sha256 TEXT,
before_modified_ns INTEGER,
instruction_json TEXT,
PRIMARY KEY(project_id, attempt_number)
)"""
)
def _create_migration_recovery_schema(self) -> None:
self._store._connection.execute(
"""CREATE TABLE IF NOT EXISTS migration_recoveries (
project_id TEXT PRIMARY KEY REFERENCES projects(project_id),
task_id TEXT NOT NULL REFERENCES tasks(task_id),
project_before TEXT NOT NULL,
project_after TEXT NOT NULL,
task_before TEXT,
task_after TEXT,
error_id TEXT NOT NULL,
project_summary TEXT NOT NULL,
task_summary TEXT
)"""
)
def _create_external_request_schema(self) -> None:
self._store._connection.execute(
"""CREATE TABLE IF NOT EXISTS external_requests (
source TEXT NOT NULL,
idempotency_key TEXT NOT NULL,
request_hash TEXT NOT NULL,
task_id TEXT NOT NULL,
created_utc TEXT NOT NULL,
PRIMARY KEY(source, idempotency_key)
)"""
)
def _migrate_v1_attemptless_active_work(self) -> None:
"""Fail closed because v1 active projects cannot have an attempt evidence context."""
from .store import _utc_text
states = tuple(status.value for status in _V1_ATTEMPTLESS_ACTIVE_STATES)
rows = self._store._connection.execute(
f"SELECT project_id, task_id, status FROM projects WHERE status IN ({', '.join('?' for _ in states)})",
states,
).fetchall()
if not rows:
return
error = TaskCenterError("v1_attempt_context_missing", "migration interrupted active project; retry the project")
for row in rows:
summary = f"migration interrupted prior project state: {row['status']}; retry the project"
task = self._store.get_task(row["task_id"])
task_summary = "migration interrupted active project; retry the project"
self._store._connection.execute(
"UPDATE projects SET status = ?, error_id = ?, summary = ? WHERE project_id = ?",
(ProjectStatus.FAILED.value, error.error_id, summary, row["project_id"]),
)
self._store._connection.execute(
"""INSERT OR REPLACE INTO migration_recoveries(
project_id, task_id, project_before, project_after, task_before, task_after,
error_id, project_summary, task_summary
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(
row["project_id"],
row["task_id"],
row["status"],
ProjectStatus.FAILED.value,
TaskStatus.RUNNING.value if task.status is TaskStatus.RUNNING else None,
TaskStatus.PAUSED.value if task.status is TaskStatus.RUNNING else None,
error.error_id,
summary,
task_summary if task.status is TaskStatus.RUNNING else None,
),
)
for task_id in sorted({row["task_id"] for row in rows}):
task = self._store.get_task(task_id)
if task.status is TaskStatus.RUNNING:
now = self._store._next_timestamp(task.updated_utc)
self._store._connection.execute(
"UPDATE tasks SET status = ?, updated_utc = ?, error_id = ?, summary = ? WHERE task_id = ?",
(
TaskStatus.PAUSED.value,
_utc_text(now),
error.error_id,
"migration interrupted active project; retry the project",
task_id,
),
)
def _ensure_task_columns(self) -> None:
columns = {row["name"] for row in self._store._connection.execute("PRAGMA table_info(tasks)")}
if "status_before_delete" not in columns:
self._store._connection.execute("ALTER TABLE tasks ADD COLUMN status_before_delete TEXT")
if "copy_part_number_to_value" not in columns:
self._store._connection.execute(
"ALTER TABLE tasks ADD COLUMN copy_part_number_to_value INTEGER NOT NULL DEFAULT 0 CHECK(copy_part_number_to_value IN (0, 1))"
)
if "group_id" not in columns:
self._store._connection.execute("ALTER TABLE tasks ADD COLUMN group_id TEXT")
if "group_position" not in columns:
self._store._connection.execute("ALTER TABLE tasks ADD COLUMN group_position INTEGER NOT NULL DEFAULT 0")
if "primary_project_id" not in columns:
self._store._connection.execute("ALTER TABLE tasks ADD COLUMN primary_project_id TEXT")
if "target_plan_mode" not in columns:
self._store._connection.execute("ALTER TABLE tasks ADD COLUMN target_plan_mode INTEGER NOT NULL DEFAULT 0 CHECK(target_plan_mode IN (0,1))")
def _create_target_plan_schema(self) -> None:
self._store._connection.execute("""CREATE TABLE IF NOT EXISTS target_plan (
task_id TEXT NOT NULL REFERENCES tasks(task_id), project_path TEXT NOT NULL,
schematic_name TEXT NOT NULL, sheet_number TEXT NOT NULL, uid TEXT NOT NULL,
refdes TEXT NOT NULL, old_part_number TEXT NOT NULL, old_value TEXT NOT NULL,
enabled INTEGER NOT NULL DEFAULT 0 CHECK(enabled IN (0,1)),
new_part_number TEXT NOT NULL DEFAULT '',
custom_value_enabled INTEGER NOT NULL DEFAULT 0 CHECK(custom_value_enabled IN (0,1)),
custom_value TEXT NOT NULL DEFAULT '', sync_nc INTEGER NOT NULL DEFAULT 1 CHECK(sync_nc IN (0,1)),
PRIMARY KEY(task_id, project_path, schematic_name, sheet_number, uid)
)""")
def _ensure_rule_columns(self) -> None:
columns = {row["name"] for row in self._store._connection.execute("PRAGMA table_info(rules)")}
if "custom_value_enabled" not in columns:
self._store._connection.execute(
"ALTER TABLE rules ADD COLUMN custom_value_enabled INTEGER NOT NULL DEFAULT 0 CHECK(custom_value_enabled IN (0, 1))"
)
if "custom_value" not in columns:
self._store._connection.execute("ALTER TABLE rules ADD COLUMN custom_value TEXT NOT NULL DEFAULT ''")
if "sync_nc" not in columns:
self._store._connection.execute(
"ALTER TABLE rules ADD COLUMN sync_nc INTEGER NOT NULL DEFAULT 1 CHECK(sync_nc IN (0, 1))"
)
@@ -0,0 +1,135 @@
"""Project binding and immutable target inventory persistence."""
from __future__ import annotations
from pathlib import Path
from .errors import TaskCenterError
from .models import TaskRecord, TaskStatus
from .target_plan import ProjectIdentityResolver
def _target_baseline(target, identities) -> tuple:
return (identities.target(target), target.refdes, target.old_part_number, target.old_value)
def merge_target_inventory(existing, targets) -> tuple:
"""Validate an additive inventory snapshot and retain every existing edit."""
from .target_plan import TargetPlanRow
existing, targets = tuple(existing), tuple(targets)
identities = ProjectIdentityResolver()
incoming = {identities.target(target): target for target in targets}
if len(incoming) != len(targets):
raise TaskCenterError("target_identity", "component inventory contains duplicate UID")
if any(identities.target(row.target) not in incoming or
_target_baseline(row.target, identities) != _target_baseline(incoming[identities.target(row.target)], identities)
for row in existing):
raise TaskCenterError("target_identity", "component inventory identity changed")
known = {identities.target(row.target) for row in existing}
return existing + tuple(TargetPlanRow(target) for key, target in incoming.items() if key not in known)
class TargetPlanRepository:
def __init__(self, store) -> None:
self._store = store
def bind_project_task(self, task_id: str, project_id: str, group_id: str, position: int) -> TaskRecord:
with self._store.transaction():
project = self._store.get_project(project_id)
if project.task_id != task_id or len(self._store.list_projects(task_id)) != 1:
raise TaskCenterError("project_binding", "new task must own exactly one project")
self._store._connection.execute("UPDATE tasks SET group_id = ?, group_position = ?, primary_project_id = ? WHERE task_id = ?",
(group_id, position, project_id, task_id))
return self._store.get_task(task_id)
def move_project_task(self, task_id: str, offset: int) -> tuple[TaskRecord, ...]:
with self._store.transaction():
task = self._store.get_task(task_id)
if task.group_id is None:
raise TaskCenterError("project_order", "task is not in a project group")
tasks = list(self._store.list_project_group(task.group_id))
if any(item.status in {TaskStatus.RUNNING, TaskStatus.PAUSED} for item in tasks):
raise TaskCenterError("project_order", "project group is active")
index = next(index for index, item in enumerate(tasks) if item.task_id == task_id)
destination = max(0, min(len(tasks) - 1, index + int(offset)))
if destination != index:
tasks.insert(destination, tasks.pop(index))
for position, item in enumerate(tasks):
self._store._connection.execute("UPDATE tasks SET group_position = ? WHERE task_id = ?",
(position, item.task_id))
return self._store.list_project_group(task.group_id)
def list_project_group(self, group_id: str) -> tuple[TaskRecord, ...]:
with self._store._lock:
rows = self._store._connection.execute("SELECT * FROM tasks WHERE group_id = ? ORDER BY group_position, created_utc",
(group_id,)).fetchall()
return tuple(self._store._task_record(row) for row in rows)
def replace_target_plan(self, task_id: str, rows) -> tuple:
from .target_plan import compile_target_rules
with self._store.transaction():
task = self._store.get_task(task_id)
if task.status not in {TaskStatus.DRAFT, TaskStatus.READY}:
raise TaskCenterError("target_plan_locked", "task plan is locked")
rows = tuple(rows)
compile_target_rules(rows)
identities = ProjectIdentityResolver()
projects = self._store.list_projects(task_id)
allowed = {identities.project(project.path) for project in projects}
if any(identities.project(row.target.project_path) not in allowed for row in rows):
raise TaskCenterError("target_identity", "target project is not in task")
inventory = {identities.target(row.target): row.target for row in self._store.list_target_plan(task_id)}
if not inventory and not (task.target_plan_mode and not rows):
raise TaskCenterError("target_inventory", "collect component inventory before editing the plan")
keys = {identities.target(row.target) for row in rows}
if len(keys) != len(rows) or set(inventory) != keys or any(
_target_baseline(inventory[identities.target(row.target)], identities) != _target_baseline(row.target, identities)
for row in rows):
raise TaskCenterError("target_identity", "target baseline identity changed")
self._store._connection.execute("DELETE FROM target_plan WHERE task_id = ?", (task_id,))
for row in rows:
target = row.target
self._store._connection.execute("""INSERT INTO target_plan VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(task_id, identities.project(target.project_path), target.schematic_name,
target.sheet_number, target.uid, target.refdes, target.old_part_number, target.old_value,
int(row.enabled), row.new_part_number, int(row.custom_value_enabled), row.custom_value,
int(row.sync_nc)))
self._store._connection.execute("UPDATE tasks SET target_plan_mode = 1 WHERE task_id = ?", (task_id,))
return self._store.list_target_plan(task_id)
def record_target_inventory(self, task_id: str, targets) -> tuple:
with self._store.transaction():
task = self._store.get_task(task_id)
if task.status not in {TaskStatus.DRAFT, TaskStatus.READY}:
raise TaskCenterError("target_plan_locked", "task plan is locked")
targets = tuple(targets)
if not targets:
if self._store.list_target_plan(task_id):
raise TaskCenterError("target_identity", "inventory unexpectedly became empty")
self._store._connection.execute("UPDATE tasks SET target_plan_mode = 1 WHERE task_id = ?", (task_id,))
return ()
existing = self._store.list_target_plan(task_id)
merged = merge_target_inventory(existing, targets)
rows = merged[len(existing):]
identities = ProjectIdentityResolver()
projects = self._store.list_projects(task_id)
allowed = {identities.project(project.path) for project in projects}
if any(identities.project(row.target.project_path) not in allowed for row in rows):
raise TaskCenterError("target_identity", "inventory project is not in task")
for row in rows:
target = row.target
self._store._connection.execute("""INSERT INTO target_plan VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, '', 0, '', 1)""",
(task_id, identities.project(target.project_path), target.schematic_name,
target.sheet_number, target.uid, target.refdes, target.old_part_number, target.old_value))
self._store._connection.execute("UPDATE tasks SET target_plan_mode = 1 WHERE task_id = ?", (task_id,))
return self._store.list_target_plan(task_id)
def list_target_plan(self, task_id: str) -> tuple:
from .target_plan import ComponentTarget, TargetPlanRow
with self._store._lock:
self._store.get_task(task_id)
rows = self._store._connection.execute("SELECT * FROM target_plan WHERE task_id = ? ORDER BY project_path, schematic_name, sheet_number, refdes, uid", (task_id,)).fetchall()
return tuple(TargetPlanRow(
ComponentTarget(Path(row["project_path"]), row["schematic_name"], row["sheet_number"],
row["uid"], row["refdes"], row["old_part_number"], row["old_value"]),
bool(row["enabled"]), row["new_part_number"], bool(row["custom_value_enabled"]),
row["custom_value"], bool(row["sync_nc"])) for row in rows)
@@ -0,0 +1,121 @@
"""Stable component identities and editable replacement plans."""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from .errors import TaskCenterError
class ProjectIdentityResolver:
"""Resolve each project once within one validation pass, never across passes."""
def __init__(self):
self._projects = {}
def project(self, path):
spelling = str(path)
if spelling not in self._projects:
self._projects[spelling] = str(Path(path).resolve(strict=False)).casefold()
return self._projects[spelling]
def target(self, target):
return (self.project(target.project_path), target.schematic_name, target.sheet_number, target.uid)
@dataclass(frozen=True, slots=True)
class ComponentTarget:
project_path: Path
schematic_name: str
sheet_number: str
uid: str
refdes: str
old_part_number: str
old_value: str
def __post_init__(self) -> None:
fields = (self.schematic_name, self.sheet_number, self.uid, self.refdes, self.old_part_number)
if any(not isinstance(value, str) or not value for value in fields):
raise TaskCenterError("target_identity", "component identity is incomplete")
if any(any(ord(char) < 32 for char in value) for value in fields):
raise TaskCenterError("target_identity", "component identity contains control characters")
@property
def key(self) -> tuple[str, str, str, str]:
return ProjectIdentityResolver().target(self)
@dataclass(frozen=True, slots=True)
class TargetPlanRow:
target: ComponentTarget
enabled: bool = False
new_part_number: str = ""
custom_value_enabled: bool = False
custom_value: str = ""
sync_nc: bool = True
def __post_init__(self) -> None:
if any(type(value) is not bool for value in (self.enabled, self.custom_value_enabled, self.sync_nc)):
raise TaskCenterError("target_plan", "plan switches must be Boolean")
if not isinstance(self.new_part_number, str) or not isinstance(self.custom_value, str):
raise TaskCenterError("target_plan", "Part Number and Value must be text")
if any(character in value for value in (self.new_part_number, self.custom_value)
for character in "\t\r\n"):
raise TaskCenterError("target_plan", "Part Number and Value cannot contain TSV controls")
@dataclass(frozen=True, slots=True)
class TargetRule:
old_part_number: str
new_part_number: str
targets: tuple[ComponentTarget, ...]
custom_value_enabled: bool = False
custom_value: str = ""
sync_nc: bool = True
enabled: bool = True
rule_id: str = ""
task_id: str = ""
position: int = 0
scope: str = "targets"
def __post_init__(self) -> None:
if not self.targets:
raise TaskCenterError("empty_target_scope", "target rule needs at least one component")
if any(target.old_part_number.casefold() != self.old_part_number.casefold() for target in self.targets):
raise TaskCenterError("target_identity", "target old Part Number differs from rule")
def compile_target_rules(rows: tuple[TargetPlanRow, ...]) -> tuple[TargetRule, ...]:
"""Group selected rows by sheet and replacement options, retaining UID scope."""
seen: set[tuple[str, str, str, str]] = set()
grouped: dict[tuple[str, str, str, str, str, str, bool, str, bool], list[ComponentTarget]] = {}
old_parts: set[str] = set()
new_parts: set[str] = set()
identities = ProjectIdentityResolver()
for row in rows:
target = row.target
if not all((target.uid, target.refdes, target.schematic_name, target.sheet_number,
target.old_part_number)):
raise TaskCenterError("target_identity", "component identity is incomplete")
target_key = identities.target(target)
if target_key in seen:
raise TaskCenterError("target_overlap", "target UID appears more than once")
seen.add(target_key)
if not row.enabled:
continue
new = row.new_part_number.strip()
old = target.old_part_number.strip()
if not new or old.casefold() == new.casefold():
raise TaskCenterError("mapping_rule", "source and target Part Numbers must differ")
if row.custom_value_enabled and not row.custom_value:
raise TaskCenterError("value_option", "custom Value is empty")
old_parts.add(old.casefold())
new_parts.add(new.casefold())
key = (target_key[0], target.schematic_name,
target.sheet_number, old, new, row.custom_value_enabled,
row.custom_value if row.custom_value_enabled else "", row.sync_nc)
grouped.setdefault(key, []).append(target)
if old_parts & new_parts:
raise TaskCenterError("mapping_chain", "chain or cycle replacement is not allowed")
return tuple(TargetRule(key[3], key[4], tuple(targets), key[5], key[6], key[7],
position=index) for index, (key, targets) in enumerate(grouped.items()))
@@ -0,0 +1,174 @@
"""Bounded event-log pages and physical cursors, independent of the UI."""
from __future__ import annotations
from dataclasses import dataclass
from contextlib import contextmanager
import os
from pathlib import Path
from threading import RLock
@dataclass(frozen=True)
class LogCursor:
identity: tuple[int, int]
offset: int
anchor: bytes = b''
@dataclass(frozen=True)
class LogPage:
lines: tuple[str, ...] = ()
cursor: LogCursor | None = None
older_cursor: LogCursor | None = None
has_older: bool = False
reset: bool = False
def _identity(handle):
value = os.fstat(handle.fileno())
return value.st_dev, value.st_ino
def _cursor(handle, offset):
handle.seek(max(0, offset - 64))
return LogCursor(_identity(handle), offset, handle.read(min(64, offset)))
def _matches(handle, cursor):
if _identity(handle) != cursor.identity or os.fstat(handle.fileno()).st_size < cursor.offset:
return False
return _cursor(handle, cursor.offset).anchor == cursor.anchor
def _backward(handle, end, limit, check=lambda: None):
"""Read complete lines backwards, retaining their exact byte boundaries."""
position = end
chunks = []
count = 0
while position > 0 and count <= limit:
check()
amount = min(8192, position)
position -= amount
handle.seek(position)
chunk = handle.read(amount)
chunks.append(chunk)
count += chunk.count(b'\n')
payload = b''.join(reversed(chunks))
if position:
cut = payload.find(b'\n') + 1
payload = payload[cut:]
position += cut
rows = []
for line in payload.splitlines(keepends=True):
check()
next_position = position + len(line)
if line.endswith(b'\n'):
rows.append((position, next_position, line.rstrip(b'\r\n').decode('utf-8')))
position = next_position
return rows[-limit:]
class TaskLogReader:
def __init__(self, path: Path, lock: RLock, *, backup_count: int = 5, read_control=None):
self.path, self.lock, self.backup_count = path, lock, backup_count
self.read_control = read_control
def _check(self):
if self.read_control is not None:
self.read_control.checkpoint()
@contextmanager
def _locked(self):
self._check()
while not self.lock.acquire(timeout=0.05):
self._check()
try:
self._check()
yield
finally:
self.lock.release()
def _paths(self):
return [self.path.with_name(f'{self.path.name}.{i}') for i in range(self.backup_count, 0, -1)] + [self.path]
def latest(self, *, limit=200):
return self.older(None, limit=limit)
def older(self, before: LogCursor | None, *, limit=200):
if limit < 1:
raise ValueError('log page limit must be positive')
with self._locked():
paths = [path for path in self._paths() if path.is_file()]
result = []
started = before is None
newest_cursor = oldest_cursor = None
has_older = False
for index in range(len(paths) - 1, -1, -1):
self._check()
with paths[index].open('rb') as handle:
if not started:
if not _matches(handle, before):
continue
end = before.offset
started = True
else:
end = os.fstat(handle.fileno()).st_size
rows = _backward(handle, end, limit - len(result), self._check)
if rows:
if newest_cursor is None:
newest_cursor = _cursor(handle, rows[-1][1])
oldest_cursor = _cursor(handle, rows[0][0])
result[0:0] = [row[2] for row in rows]
elif newest_cursor is None and before is None:
# Incomplete trailing line must be retried from its start.
newest_cursor = _cursor(handle, 0)
if len(result) >= limit:
has_older = bool(rows and rows[0][0] > 0) or any(p.stat().st_size for p in paths[:index])
break
if before is not None and not started:
page = self.latest(limit=limit)
return LogPage(page.lines, page.cursor, page.older_cursor, page.has_older, True)
return LogPage(tuple(result), newest_cursor, oldest_cursor, has_older)
def poll(self, after: LogCursor | None, *, limit=200):
if after is None:
return self.latest(limit=limit)
if limit < 1:
raise ValueError('log page limit must be positive')
with self._locked():
paths = [path for path in self._paths() if path.is_file()]
found = False
lines = []
cursor = after
for path in paths:
self._check()
with path.open('rb') as handle:
if not found:
if not _matches(handle, after):
continue
found = True
offset = after.offset
else:
offset = 0
handle.seek(offset)
while len(lines) < limit:
self._check()
chunks = []
while True:
self._check()
chunk = handle.readline(65536)
chunks.append(chunk)
if not chunk or chunk.endswith(b'\n'):
break
line = b''.join(chunks)
if not line or not line.endswith(b'\n'):
break
lines.append(line.rstrip(b'\r\n').decode('utf-8'))
offset = handle.tell()
cursor = _cursor(handle, offset)
if len(lines) >= limit:
break
if not found:
page = self.latest(limit=limit)
return LogPage(page.lines, page.cursor, page.older_cursor, page.has_older, True)
return LogPage(tuple(lines), cursor)
@@ -0,0 +1,212 @@
"""Durable serial scheduling of single-project tasks, above the existing runner."""
from contextlib import contextmanager
from dataclasses import asdict, dataclass, is_dataclass
import hashlib
import json
import os
from pathlib import Path
from threading import Event, Lock, get_ident
from uuid import uuid4
from .errors import TaskCenterError
from .quick_run import _write_atomic_queue_text
_QUEUE_LOCK = Lock()
_QUEUE_OWNER: int | None = None
_SAFE_FAILURES = frozenset({'quick_run_preflight', 'quick_run_session', 'quick_run_backup',
'target_identity', 'empty_target_scope', 'enabled_rule_required'})
_TERMINAL = frozenset({'completed', 'failed', 'skipped'})
@dataclass(frozen=True)
class TaskQueueEntry:
task_id: str
state: str
message: str = ''
@dataclass(frozen=True)
class TaskQueueResult:
queue_id: str
entries: tuple[TaskQueueEntry, ...]
paused: bool
current_task_id: str | None = None
def _os_lock(handle, acquire):
handle.seek(0)
if os.name == 'nt':
import msvcrt
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK if acquire else msvcrt.LK_UNLCK, 1)
else:
import fcntl
fcntl.flock(handle.fileno(), (fcntl.LOCK_EX | fcntl.LOCK_NB) if acquire else fcntl.LOCK_UN)
def _lock_file(root: Path):
root.mkdir(parents=True, exist_ok=True)
handle = (root / '.task-queue.execution.lock').open('a+b')
if handle.seek(0, os.SEEK_END) == 0:
handle.write(b'\0')
handle.flush()
return handle
def assert_task_queue_idle(root: Path) -> None:
"""Reject external mutations while a queue owns CAD; its runner may call services."""
if _QUEUE_OWNER == get_ident():
return
if _QUEUE_LOCK.locked():
raise TaskCenterError('quick_run_busy', '任务队列正在执行,请先安全暂停。')
with _lock_file(Path(root)) as handle:
try:
_os_lock(handle, True)
except OSError as error:
raise TaskCenterError('quick_run_busy', '另一窗口正在执行任务队列。') from error
_os_lock(handle, False)
@contextmanager
def _queue_lease(root: Path):
global _QUEUE_OWNER
if not _QUEUE_LOCK.acquire(blocking=False):
raise TaskCenterError('quick_run_busy', '已有任务队列正在执行。')
handle = None
locked = False
try:
handle = _lock_file(root)
try:
_os_lock(handle, True)
locked = True
except OSError as error:
raise TaskCenterError('quick_run_busy', '另一窗口正在执行任务队列。') from error
_QUEUE_OWNER = get_ident()
yield
finally:
_QUEUE_OWNER = None
if handle is not None:
if locked:
_os_lock(handle, False)
handle.close()
_QUEUE_LOCK.release()
def _record(value):
if is_dataclass(value):
return asdict(value)
return vars(value)
def _plan_hash(child, task_id: str) -> str:
task = child.get_task(task_id)
payload = {
'projects': [(str(project.path.resolve(strict=False)).casefold(), project.selected, project.available)
for project in child.projects(task_id)],
'rules': [_record(rule) for rule in child.rules(task_id)],
'targets': [_record(row) for row in child.target_plan(task_id)],
'copy_value': task.copy_part_number_to_value,
'target_plan_mode': getattr(task, 'target_plan_mode', False),
}
return hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=False,
default=str).encode('utf-8')).hexdigest()
def _save(path: Path, state: dict) -> None:
_write_atomic_queue_text(path, json.dumps(state, ensure_ascii=False, indent=2),
'task_queue_state', '不能保存任务队列检查点。')
def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
queue_id: str | None = None) -> TaskQueueResult:
"""Execute the frozen order; uncertain state stops before the next project."""
ids = tuple(task_ids)
if not ids or len(set(ids)) != len(ids):
raise TaskCenterError('task_queue_selection', '请选择不同的单工程任务。')
root = service._logging.root
with _queue_lease(root):
children = {task_id: service.for_project_task(task_id) for task_id in ids}
project_paths = []
for task_id, child in children.items():
task = child.get_task(task_id)
projects = child.projects(task_id)
if not getattr(task, 'primary_project_id', None) or len(projects) != 1:
raise TaskCenterError('project_binding', '顺序执行仅支持绑定单个工程的任务。')
project_paths.append(str(projects[0].path.resolve(strict=False)).casefold())
if len(set(project_paths)) != len(ids):
raise TaskCenterError('task_queue_selection', '不能在同一队列重复处理同一个工程。')
hashes = {task_id: _plan_hash(child, task_id) for task_id, child in children.items()}
token = queue_id or uuid4().hex
if len(token) != 32 or any(char not in '0123456789abcdef' for char in token):
raise TaskCenterError('task_queue_state', '任务队列编号无效。')
path = root / 'task-queues' / f'{token}.json'
path.parent.mkdir(parents=True, exist_ok=True)
if queue_id is not None:
try:
state = json.loads(path.read_text(encoding='utf-8'))
if (state['version'] != 1 or state['task_ids'] != list(ids)
or state['plan_hashes'] != hashes or set(state['entries']) != set(ids)
or any(not isinstance(entry, dict) or set(entry) != {'state', 'message'}
or entry['state'] not in {'pending', 'running', 'paused', 'blocked', *_TERMINAL}
or not isinstance(entry['message'], str)
for entry in state['entries'].values())):
raise ValueError('queue inputs changed')
except (OSError, ValueError, KeyError, TypeError) as error:
raise TaskCenterError('task_queue_state', '任务顺序或计划已变化,不能恢复原队列。') from error
else:
state = {'version': 1, 'task_ids': list(ids), 'plan_hashes': hashes,
'entries': {task_id: {'state': 'pending', 'message': ''} for task_id in ids}}
_save(path, state)
paused = False
current = None
try:
for task_id in ids:
if state['entries'][task_id]['state'] in _TERMINAL:
continue
if stop_event.is_set():
paused = True
break
current = task_id
child = children[task_id]
service._task_queue_feedback = (token, task_id, ids.index(task_id) + 1, len(ids))
try:
if child.has_interrupted_quick_run(task_id):
raise TaskCenterError('quick_run_uncertain', '该任务有待核验步骤。')
progress = child.quick_run_progress(task_id)
if progress.queue_complete:
entry = {'state': 'failed' if getattr(progress, 'failed_items', 0) else 'completed',
'message': '该任务队列已有完整执行结果。'}
else:
state['entries'][task_id] = {'state': 'running', 'message': ''}
_save(path, state)
expected = (str(progress.next_project_path), progress.next_old_part_number,
progress.next_new_part_number,
'part_label' if child.get_task(task_id).copy_part_number_to_value else 'preserve')
result = child.execute_quick_run_queue(task_id, expected_item=expected,
stop_event=stop_event)
if child.has_interrupted_quick_run(task_id) or (
result.last_result is not None and result.last_result.state == 'batch_saved_unverified'
):
raise TaskCenterError('quick_run_uncertain', '保存结果尚未确认,任务队列已停止。')
incomplete = result.paused or not result.progress.queue_complete
entry = {'state': 'paused' if incomplete else (
'failed' if getattr(result.progress, 'failed_items', 0) else 'completed'),
'message': '已安全暂停。' if incomplete else '任务已收尾。'}
if incomplete:
paused = True
except TaskCenterError as error:
safe = error.code in _SAFE_FAILURES and not child.has_interrupted_quick_run(task_id)
entry = {'state': 'failed' if safe else 'blocked', 'message': error.message}
paused = not safe
except Exception as error:
entry = {'state': 'blocked', 'message': str(error)}
paused = True
state['entries'][task_id] = entry
_save(path, state)
if paused:
break
return TaskQueueResult(token, tuple(TaskQueueEntry(task_id, **state['entries'][task_id])
for task_id in ids), paused, current if paused else None)
finally:
service._task_queue_feedback = None
Loaded 100 of 195 files, more files were not shown because too many files have changed in this diff. Show more