Initial import of DxDesigner part replacement tool (r21)
This commit is contained in:
commit
ffe066cb1e
151 files changed
+58745
No files matched your search
+17
@@ -0,0 +1,17 @@
|
||||
/.venv/
|
||||
/.pytest_cache/
|
||||
/build/
|
||||
/dist/
|
||||
/data/
|
||||
/runs/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.db
|
||||
*.db-*
|
||||
*.sqlite*
|
||||
*.log
|
||||
*.jsonl
|
||||
*.zip
|
||||
*.rar
|
||||
.coverage
|
||||
coverage.xml
|
||||
@@ -0,0 +1,174 @@
|
||||
# DxDesigner 元件替换项目代码审查
|
||||
|
||||
审查日期:2026-09-06。基线:当前磁盘源码;目录没有 Git 元数据,不能绑定提交或推断修改历史。
|
||||
|
||||
## 结论
|
||||
|
||||
**不建议把当前版本用于唯一工程副本或无人值守批量替换。** 确认 10 项问题:5 项 P1、5 项 P2。主要风险不是代码风格,而是错误成功判定、错误上下文撤销、恢复约束丢失和执行重入。
|
||||
|
||||
采用 Superpowers 的 systematic-debugging、requesting-code-review、verification-before-completion 工作流:先理解功能,再检查具体调用链,以隔离复现和持久事件验证结论。审查不等于修复;本次没有修改业务源码。
|
||||
|
||||
## 1. 功能与实际执行路径
|
||||
|
||||
### 当前桌面主路径
|
||||
|
||||
PySide6 窗口管理任务、扫描并选择 `.prj` 工程、维护旧料号到新料号的规则。主按钮“自动替换并校验”调用 `TaskCenterService.execute_quick_run()`,生成共享 `quick-run` 目录中的 TSV 命令、状态和快照,调用 VBS,再由 Python helper 连接 DxDesigner、执行原生替换及引脚编号提升,最后由 VBS 恢复实例参数并检查当前图页结果。
|
||||
|
||||
入口:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\ui\main_window.py:595`。
|
||||
|
||||
这条路径以**当前图页**为实际工作范围;不应把按钮显示的“队列完成”等同于全工程所有图页都完成替换、保存或通过外部电气检查。
|
||||
|
||||
### 仍保留的另外两条路径
|
||||
|
||||
- 人工证据任务流程:`TrialRunner` 管理 Capture Before、人工替换、Capture After 和 SQLite 状态,使用 `compare_profiles()`。当前主窗口没有把这些人工操作按钮放入主操作布局,但服务、测试及相关代码仍保留。
|
||||
- 原批处理 CLI:`BatchController` 管理不可变输入、完整库存、认证、关闭/备份/重开、逐规则替换、保存、外部检查以及 Undo/恢复。其安全检查**不会自动覆盖桌面 quick-run 路径**。
|
||||
|
||||
对应入口:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\runner.py:193`;`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\part_replace\controller.py:1511`。
|
||||
|
||||
### 文档边界
|
||||
|
||||
用户指南仍主要描述人工替换、不写 Value/样式的旧流程,当前 EXE 已走自动替换和参数恢复。不能据此假定自动路径继承了旧 CLI 的备份、认证和全项目校验保障。建议分别声明三条路径的范围、保存责任及失败处理,而不是共用一个安全承诺。本项作为发布说明缺口,不计入下列 10 项缺陷。
|
||||
|
||||
## 2. 已确认发现
|
||||
|
||||
### F01 · P1 · 回滚前未核对项目/图页,可能撤销其他工程的编辑
|
||||
|
||||
- 路径:当前桌面自动替换;类别:工程数据安全。
|
||||
- 位置:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\integration\dxdesigner795\QuickPartReplace.vbs:156`。
|
||||
- 触发:替换或恢复期间切换活动项目/图页。恢复阶段在第 371 行检测到上下文不符后抛错,外层第 94 行进入回滚,但回滚函数先对当前应用发送 `undo`,随后才检查恢复结果。
|
||||
- 复现:使用项目 A 的快照、活动项目 B 的假应用,真实回滚函数输出 `ACTIVE_PROJECT=C:\UnrelatedB\b.prj`、`WRONG_CONTEXT_COMMAND=undo`,之后才输出 `replacement component not found`。
|
||||
- 影响:对 A 的失败处理可能先撤销 B 的合法编辑,且不能恢复 A。事后报错不能抵消已经发出的错误命令。
|
||||
- 修复:任何 Undo 前核对项目、图页和本次事务归属;上下文变化时只阻断,不向当前未知撤销栈发送命令。不能仅增加 Undo 后的检查。
|
||||
- 证据边界:真实函数和假应用验证了命令顺序,没有在真实 DxDesigner 中制造工程损坏。
|
||||
|
||||
### F02 · P1 · 只改料号、保留旧符号,也能被当成原生替换成功
|
||||
|
||||
- 路径:当前桌面自动替换的续跑分支;类别:功能正确性、库身份完整性。
|
||||
- 位置:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\native_helper.py:162`;同文件第 121 行。
|
||||
- 触发:已有快照,元件 Part Number 已变为目标值,但 UID、旧 Part Name、旧 Part Label 和引脚仍保留。`source_uids != wanted` 分支只检查目标料号以及非空库身份字段,直接跳过目标库查找和原生替换。
|
||||
- 复现:真实 helper 返回 `exit=0`、`ok=True`、`stage=native_replace_verified`、`already_replaced=True`,而 Part Name 仍为 `OLD_SYMBOL`、Part Label 仍为 `OLD_LABEL`。独立的 VBS 假对象复现也写出 `restored_ok`。
|
||||
- 影响:产生“新料号+旧库身份”的假成功,而不是用户要求的库元件替换。
|
||||
- 修复:续跑必须验证与当前作业绑定的原生替换记录、目标中央库身份和符号/接口指纹;不能以目标料号存在推断已完成替换。
|
||||
- 证据边界:helper 与 VBS 分别进行了隔离函数测试,不宣称完成了真实软件端到端复现。
|
||||
|
||||
### F03 · P1 · 恢复库存不一致后,再次 Continue 会丢失恢复约束
|
||||
|
||||
- 路径:原批处理 CLI;类别:恢复安全、错误成功判定。
|
||||
- 位置:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\part_replace\controller.py:2237`。
|
||||
- 触发:失败替换经 Undo 后 reconcile,带有可信 `expected_snapshot_path`;第一次新库存不符合该快照,被 `recovery_snapshot_mismatch` 阻断。再次运行 operator step 时,按最新 reconcile 切分周期,旧的 mutation/recovery 证据不再进入判断,于是生成不带可信快照的 `read_only_retry`。
|
||||
- 复现:先提交缺失元件的库存,第一次正确 blocked;再 Continue 并提交同一库存,最终 `complete=True`、状态 `verified_saved`。主线程从临时目录重新构造全流程复核,安全断言失败。
|
||||
- 影响:恢复校验可以被正常续跑操作降级掉;异常空库存甚至会借零匹配的 `no_changes_required` 直接成为成功。
|
||||
- 修复:恢复义务必须跨库存重试持续存在,直到可信快照真正通过核验;不能用“本周期没有写事件”推断整个作业从未写入。
|
||||
|
||||
### F04 · P1 · 执行中刷新任务会重新启用替换按钮,允许重入
|
||||
|
||||
- 路径:当前桌面自动替换;类别:并发安全、鲁棒性。
|
||||
- 位置:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\ui\main_window.py:390`。
|
||||
- 触发:后台 worker 正在运行,用户切换任务或重新加载任务数据。`_run_async()` 暂时禁用按钮,但 `_update_gates()` 只检查选择与队列状态,没有检查仍在执行的 worker,重新启用按钮。
|
||||
- 复现:用 Event 阻塞 worker,确认按钮已禁用;调用真实 `open_task()` 后按钮立即恢复 enabled,worker 尚未结束。
|
||||
- 影响:用户能够再次发起执行。服务层没有对应的执行互斥,两个执行会共用 `quick-run/command.tsv`、状态、快照和活动 DxDesigner;事后关联状态失败并不能预防前面的并发操作。
|
||||
- 修复:执行中保持全局操作占用,服务层加原子互斥/租约;支持多实例时还需跨进程锁。按钮禁用和结果 generation 检查不能代替执行锁。
|
||||
- 证据边界:已复现 UI 重入条件;没有对真实 DxDesigner 执行并发写入。
|
||||
|
||||
### F05 · P1 · 保护证据缺失或库存声明矛盾时,比较器仍放行
|
||||
|
||||
- 路径:保留的人工证据任务流程,不是当前 quick-run helper;类别:校验完整性。
|
||||
- 位置:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\comparison.py:152`;同文件第 179、225 行。
|
||||
- 触发:接口标志仍为 available,但匹配元件 `pins=[]`、`units=0` 或 `net_identity=None`。空列表、零单元和未知网络身份均通过当前 schema 检查;前后相等后不再产生错误。
|
||||
- 复现:以上三个输入均返回 `passed=True, issues=[]`。额外两个用例中,`enumeration.available=False` 或声明 200 个元件却只有 2 条记录,也返回通过,因为枚举声明没有参与比较。
|
||||
- 影响:无法证明引脚、单元或连接安全的证据被作为成功依据。枚举矛盾用例证明输入校验缺口,不代表现有 probe 必然会生成这种矛盾文件。
|
||||
- 修复:对匹配的真实器件要求正单元数、非空引脚及明确网络/未连接状态,检查全项目枚举能力与记录数一致性;缺证据与“无变化”必须分开处理。
|
||||
|
||||
### F06 · P2 · 已保存的 before 哈希没有在最终比较前复核
|
||||
|
||||
- 路径:保留的人工证据任务流程;类别:本地证据完整性。
|
||||
- 位置:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\runner.py:273`。
|
||||
- 触发:Capture Before 后、Capture After 前,已保存的 before 文件被改写。数据库虽保存 SHA-256,但最终读取只调用 `_load_profile(context.before_path)`;`_require_attempt()` 只要求哈希字段存在。
|
||||
- 复现:原 before 的引脚 x 为 0;捕获后把存档 before 的 x 改为 999,再输入同样 x=999 的 after。流程将项目标为 `completed`,没有发现存档内容已偏离捕获时哈希。
|
||||
- 影响:损坏、误编辑或被替换的本地证据可成为新的可信基线。这是本地完整性问题,不是远程攻击或权限提升结论。
|
||||
- 修复:对最终实际读取的字节重新计算大小和 SHA-256,与持久化记录匹配后再解析;项目身份、schema、duplicate key 校验也应复用捕获入口。
|
||||
|
||||
### F07 · P2 · 写 API 已执行,错误报告却仍为 preflight,跳过恢复
|
||||
|
||||
- 路径:当前桌面自动替换的续跑分支;类别:异常处理、工程安全。
|
||||
- 位置:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\native_helper.py:164`。
|
||||
- 触发:already-replaced 分支调用 `PromoteSymbolNumbers(1,1)` 后,引脚枚举失败或为空。该分支在调用成功返回以后才设置 stage;失败报告因此仍保留初始 `preflight`。
|
||||
- 复现:假 Block 记录了 `promotions=[(1,1)]`,随后真实 helper 返回 `exit=1, stage=preflight, Replacement produced no pins`。
|
||||
- 影响:VBS 只把 `native_replace_started` / `native_replace_verified` 当作可能写入,故此失败路径漏掉恢复处理;这不是误报成功,而是已发出写操作后丢失了写入阶段信息。
|
||||
- 修复:任何写 API 前持久化“可能已写入”阶段;明确原生替换、引脚提升、参数恢复各阶段及对应恢复责任。
|
||||
|
||||
### F08 · P2 · 最后一条规则验证后中断,作业无法正常续跑到保存
|
||||
|
||||
- 路径:原批处理 CLI;类别:崩溃恢复。
|
||||
- 位置:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\part_replace\controller.py:1777`。
|
||||
- 触发:`rule_verified` 已落盘,但迁移至 `AWAITING_SAVE_CONFIRMATION` 前异常退出。重开后状态仍为 applying,同时既没有 pending command,也没有剩余规则。
|
||||
- 复现:故障注入产生的持久事件以 `rule_verified / target_state=applying` 结束;主线程重新打开并调用 operator step,返回 `rule_order: project has no remaining replacement rule to prepare`。
|
||||
- 影响:已经验证成功的替换不能通过正常 Continue 进入保存;重新 verify 和 prepare-save 也不符合各自状态条件,需要额外恢复操作。
|
||||
- 修复:最终 rule_verified 应原子驱动待保存状态,或启动重放时能幂等补全该迁移。
|
||||
|
||||
### F09 · P2 · mailbox 已移动但归档事件未提交,中断后先检查旧路径导致续跑失败
|
||||
|
||||
- 路径:原批处理 CLI;类别:文件/事件一致性、崩溃恢复。
|
||||
- 位置:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\part_replace\controller.py:1009`。
|
||||
- 触发:归档把 snapshot 移入 history 后、追加 `mailbox_outputs_archived` 前中断。重新 prepare Apply 先调用当前快照校验,仍使用缺失的原 mailbox 路径,尚未到可补全归档的代码。
|
||||
- 复现:故障目录中 history 已有快照而归档事件缺失;重开后 `prepare_apply()` 返回 `stale_project: current snapshot is unavailable`。
|
||||
- 影响:证据存在却无法通过正常重试恢复,已实现的部分归档续做逻辑不可达。
|
||||
- 修复:使用持久化归档意图和可重放的文件发布步骤,在解析当前快照来源前先恢复未完成归档;不能随意忽略 stale_project。
|
||||
|
||||
### F10 · P2 · 合法 Library Wins 引脚名变化被误判成保护字段变化
|
||||
|
||||
- 路径:保留的人工证据任务流程;类别:功能兼容性、误报。
|
||||
- 位置:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\comparison.py:277`。
|
||||
- 触发:目标库只改变引脚显示名称,号码、位置、网络及其他保护字段不变。比较器将整个 pins 字典列表作为硬保护字段直接比较。
|
||||
- 复现:仅把 pin name 改为 `LIBRARY-RENAMED-PIN`,得到 `passed=False, pins_changed`。原核心 verifier 则在同类条件下记录非阻断的 `library_pin_name_changed`,与用户指南对库控制字段的说明一致。
|
||||
- 影响:有效替换被标记 Failed,两个校验实现的允许变化集合不一致。
|
||||
- 修复:按 pin number 对齐后逐个校验坐标、网络等硬保护字段;库控制名称变化单独报告,不把合法变化当作连接变化。
|
||||
|
||||
## 3. 验证结果与可复现附件
|
||||
|
||||
### 现有定向测试:216 passed
|
||||
|
||||
在项目目录中执行,均为实际完成并取得退出码 0 的测试,不包含被中止的运行:
|
||||
|
||||
```powershell
|
||||
$env:QT_QPA_PLATFORM='offscreen'
|
||||
.\.venv\Scripts\python.exe -m pytest tests/trial_task_center tests/part_replace/test_verification.py tests/part_replace/test_inputs.py tests/part_replace/test_protocol.py tests/part_replace/test_models.py tests/part_replace/test_reports.py -q --tb=short
|
||||
# 192 passed in 25.53s
|
||||
.\.venv\Scripts\python.exe -m pytest tests/integration/test_automatic_replacement_regression.py tests/integration/test_quick_part_replace_contract.py -q --tb=short
|
||||
# 24 passed in 1.08s
|
||||
```
|
||||
|
||||
### 审查复现:12 个安全预期断言失败
|
||||
|
||||
这些文件故意断言“正确安全行为”,因此当前实现应显示失败;失败是缺陷证据,不是已修复或测试通过。三个附件最后合并运行结果为 `12 failed in 19.76s`,全部是预期行为断言失败,没有 fixture 初始化错误。附件放在 docs/reviews,而非默认 tests 收集目录,未改变正常测试发现配置。
|
||||
|
||||
- `F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\docs\reviews\2026-09-06-review-repros.py:1`:8 failed,覆盖 F04、F05、F06、F10。
|
||||
- `F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\docs\reviews\2026-09-06-native-repros.py:1`:3 failed,覆盖 F01、F02 的 helper 分支、F07;Win32/UI 均为桩,VBS 排除了自动连接应用的顶层启动代码。
|
||||
- `F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\docs\reviews\2026-09-06-controller-repros.py:1`:1 failed,用现有 fixture 在临时目录从头复现 F03。
|
||||
|
||||
```powershell
|
||||
$env:QT_QPA_PLATFORM='offscreen'
|
||||
.\.venv\Scripts\python.exe -m pytest docs/reviews/2026-09-06-review-repros.py docs/reviews/2026-09-06-native-repros.py docs/reviews/2026-09-06-controller-repros.py -q --tb=short
|
||||
```
|
||||
|
||||
F08/F09 的故障注入持久证据位于以下临时目录;本次已重新打开验证相应错误。临时文件可能被系统清理,不能当作永久交付存储:
|
||||
|
||||
- `C:\Users\ABS_Windows\AppData\Local\Temp\dx-controller-readonly-audit-fafuffpn\last-rule-transition\run\events.jsonl:1`
|
||||
- `C:\Users\ABS_Windows\AppData\Local\Temp\dx-controller-readonly-audit-fafuffpn\archive-before-event\run\events.jsonl:1`
|
||||
|
||||
### 全量测试不能宣称通过
|
||||
|
||||
初始收集范围有 587 项测试;完整运行没有完成。UI 的现有测试仍模拟旧的 `awaiting_native_replace` 两步协议,但当前 execute_step 要求 `restored_ok`。产生异常后,可见窗口的 `_show_error()` 进入 `QMessageBox.exec()`,无人点击使测试卡住。
|
||||
|
||||
单测定位:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\tests\ui\test_trial_task_center_workflow.py:113`。使用 `-o faulthandler_timeout=8` 得到主线程堆栈停在 `F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\ui\main_window.py:792`。已停止本次卡住/过慢的测试进程,不把部分进度计为通过。应更新测试协议,并给错误对话框提供自动化处理机制。
|
||||
|
||||
## 4. 修复顺序与边界
|
||||
|
||||
1. 首先处理 F01/F02/F03:错误上下文 Undo、原生替换假成功和恢复约束降级。
|
||||
2. 给 quick-run 增加服务级互斥,先防止并发写入,再修复 F07 的写入阶段记录。
|
||||
3. 统一证据解析与校验策略,处理 F05/F06/F10,避免三条路径各自实现不同安全标准。
|
||||
4. 为 F08/F09 增加每个持久化边界的中断恢复测试,最后更新 UI 测试和用户指南。
|
||||
|
||||
已有正面基础包括规则链/环校验、核心完整快照比较、命令关联、部分原子发布和备份校验;216 项定向测试通过能证明这些被覆盖的场景可工作,不能抵消本报告的反例。
|
||||
|
||||
本次未连接或操作真实 DxDesigner,未修改设计、未安装组件、未修改用户环境变量、未重新打包 EXE;仅新增审查文档和隔离复现代码。真实多图页/多门器件传播、原生 Undo 栈粒度、中央库现场行为及打包产物与源码一致性仍需可丢弃副本上的专项验收。本报告不是对产品无其他漏洞的保证,也不声称发现远程代码执行或网络攻击入口。
|
||||
@@ -0,0 +1,43 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def test_recovery_constraint_survives_failed_inventory_retry(tmp_path: Path) -> None:
|
||||
helpers = runpy.run_path(str(ROOT / "tests" / "part_replace" / "test_controller.py"))
|
||||
controller, markers, certification_path = helpers["_create_controller"](tmp_path)
|
||||
project_id = controller.projects[0].project_id
|
||||
inventory, _ = helpers["_ingest"](controller, tmp_path, project_id, markers[0])
|
||||
helpers["_certify"](certification_path, inventory)
|
||||
helpers["_ready_for_apply"](controller, project_id, inventory)
|
||||
command = controller.prepare_apply(project_id, 0)
|
||||
helpers["_publish_bridge_snapshot"](
|
||||
controller,
|
||||
command,
|
||||
"applied",
|
||||
helpers["_snapshot"](project_id, markers[0], "WRONG-1", "unsafe", symbol="LIB:NEW"),
|
||||
)
|
||||
assert not controller.verify_apply(project_id, 0).passed
|
||||
undo = controller.prepare_undo(project_id)
|
||||
helpers["_publish_bridge_snapshot"](
|
||||
controller, undo, "undo_verified", inventory, status_command=command
|
||||
)
|
||||
controller.confirm_undo(project_id)
|
||||
controller.reconcile(project_id)
|
||||
command = controller.prepare_inventory(project_id)
|
||||
wrong_inventory = replace(inventory, components=())
|
||||
helpers["_publish_bridge_snapshot"](controller, command, "inventory_exported", wrong_inventory)
|
||||
with pytest.raises(helpers["ControllerError"], match="recovery_snapshot_mismatch"):
|
||||
controller.ingest_inventory(project_id)
|
||||
controller = helpers["BatchController"].open(controller.root)
|
||||
step = controller.operator_step()
|
||||
helpers["_publish_bridge_snapshot"](controller, step.command, "inventory_exported", wrong_inventory)
|
||||
step = controller.operator_step()
|
||||
assert not step.complete, "previously rejected inventory became verified_saved after Continue"
|
||||
@@ -0,0 +1,114 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
from types import ModuleType, SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center import native_helper
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class OriginalComponent:
|
||||
UID = "original-uid"
|
||||
Refdes = "R1"
|
||||
|
||||
def FindAttribute(self, name):
|
||||
value = {"Part Number": "NEW", "Part Name": "OLD_SYMBOL", "Part Label": "OLD_LABEL"}[name]
|
||||
return SimpleNamespace(InstanceValue=value, Value=value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("has_pins", (True, False))
|
||||
def test_resume_does_not_infer_native_replacement_from_part_number(monkeypatch, tmp_path: Path, has_pins: bool) -> None:
|
||||
modules = {name: ModuleType(name) for name in ("win32api", "win32con", "win32gui", "win32process", "pywinauto")}
|
||||
modules["pywinauto"].Desktop = object
|
||||
for name, module in modules.items():
|
||||
monkeypatch.setitem(sys.modules, name, module)
|
||||
component = OriginalComponent()
|
||||
promotions = []
|
||||
pin = SimpleNamespace(Component=component, Number="1")
|
||||
pin._oleobj_ = pin
|
||||
view = SimpleNamespace(
|
||||
GetName=lambda flag: "A",
|
||||
Block=SimpleNamespace(SheetNum=1, PromoteSymbolNumbers=lambda *args: promotions.append(args)),
|
||||
Query=lambda *args: [pin] if has_pins else [],
|
||||
)
|
||||
app = SimpleNamespace(
|
||||
ActiveView=view,
|
||||
GetProjectData=lambda: SimpleNamespace(GetProjectFilePath=lambda: r"C:\DisposableA\a.prj"),
|
||||
)
|
||||
snapshot = tmp_path / "snapshot.tsv"
|
||||
snapshot.write_text(
|
||||
"M\tC:\\DisposableA\\a.prj\tOLD\tNEW\tA:1\n"
|
||||
"C\toriginal-uid\tR1\t0\t0\t0\t1\tnet\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
monkeypatch.setattr(native_helper, "attach", lambda: (app, SimpleNamespace(IVdCmpPin=lambda value: value)))
|
||||
monkeypatch.setattr(native_helper, "components_on_sheet", lambda *args: [component])
|
||||
monkeypatch.setattr(native_helper, "selection", lambda *args: None)
|
||||
exit_code = native_helper.run(snapshot)
|
||||
report = json.loads(Path(str(snapshot) + ".native.json").read_text(encoding="utf-8"))
|
||||
if has_pins:
|
||||
assert exit_code != 0, f"old library identity accepted: {report}"
|
||||
else:
|
||||
assert promotions == [(1, 1)]
|
||||
assert exit_code != 0
|
||||
assert report["stage"] != "preflight", f"write API called but mutation state lost: {report}"
|
||||
|
||||
|
||||
def test_native_rollback_rejects_wrong_project_before_undo(tmp_path: Path) -> None:
|
||||
source = (ROOT / "integration" / "dxdesigner795" / "QuickPartReplace.vbs").read_text(encoding="ascii")
|
||||
declarations = source[:source.index("Set QP_Fso =")]
|
||||
routines = source[source.index("Sub QPMain()") :]
|
||||
snapshot = tmp_path / "snapshot.tsv"
|
||||
snapshot.write_text(
|
||||
"M\tC:\\DisposableA\\a.prj\tOLD\tNEW\tA:1\n"
|
||||
"C\told-uid\tR1\t0\t0\t0\t1\tnet\n"
|
||||
"A\told-uid\tPart Number\tOLD\t\t0\t0\t0\t0\t10\t0\t1\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
body = r'''
|
||||
Set QP_Fso = CreateObject("Scripting.FileSystemObject")
|
||||
Set QP_App = New WrongProjectApp
|
||||
WScript.Echo "ACTIVE_PROJECT=" & QPProjectPath()
|
||||
On Error Resume Next
|
||||
QPRollbackNativeReplacement "SNAPSHOT"
|
||||
WScript.Echo "ERROR_AFTER_UNDO=" & Err.Description
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
WScript.Quit 0
|
||||
Class WrongProjectApp
|
||||
Public Function ExecuteCommand(ByVal Command)
|
||||
WScript.Echo "WRONG_CONTEXT_COMMAND=" & Command
|
||||
ExecuteCommand = True
|
||||
End Function
|
||||
Public Function GetProjectData()
|
||||
Set GetProjectData = Me
|
||||
End Function
|
||||
Public Function GetProjectFilePath()
|
||||
GetProjectFilePath = "C:\UnrelatedB\b.prj"
|
||||
End Function
|
||||
Public Property Get ActiveView
|
||||
Set ActiveView = Me
|
||||
End Property
|
||||
Public Function Query(ByVal Flags, ByVal Selected)
|
||||
Set Query = CreateObject("Scripting.Dictionary")
|
||||
End Function
|
||||
End Class
|
||||
'''.replace("SNAPSHOT", str(snapshot))
|
||||
wrapper = tmp_path / "isolated-rollback.vbs"
|
||||
wrapper.write_text(declarations + body + routines, encoding="ascii")
|
||||
completed = subprocess.run(
|
||||
["cscript.exe", "//nologo", str(wrapper)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=15,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW,
|
||||
)
|
||||
assert completed.returncode == 0, completed.stderr
|
||||
assert "WRONG_CONTEXT_COMMAND=undo" not in completed.stdout, completed.stdout
|
||||
@@ -0,0 +1,49 @@
|
||||
# 2026-09-06 审查整改记录
|
||||
|
||||
整改范围:`2026-09-06-code-review.md` 的 F01-F10,以及 `2026-09-06-ui-review.md` 的 U01-U05、V01-V04。整改采用 Superpowers 的 receiving-code-review、systematic-debugging、test-driven-development 和 verification-before-completion 流程。
|
||||
|
||||
## 代码审查项
|
||||
|
||||
- F01:所有 Undo 前核对作业、工程、图页和事务归属;上下文变化时阻断,不向未知撤销栈发送命令。
|
||||
- F02/F07:原生替换与目标库行、符号、快照哈希和作业绑定;任何写 API 前持久化 mutation stage,失败后不丢失恢复责任。
|
||||
- F03:恢复快照义务跨重试保留,直到可信库存真正匹配。
|
||||
- F04:GUI worker generation、进程内锁和跨进程文件锁共同阻止重复 quick-run;执行期间删除及输入修改也由服务层阻断。
|
||||
- F05/F10:完整项目枚举、单元、引脚和网络证据成为硬门禁;Library Wins 引脚名称变化单独作为非阻断警告。
|
||||
- F06:最终比较前重新读取 before 原始字节并复核大小、SHA-256、JSON/schema 和项目身份。
|
||||
- F08:最后规则验证与待保存状态原子提交,并兼容修复旧日志中断状态。
|
||||
- F09:mailbox 部分归档可重放,同时保留旧工程 stale 检查顺序。
|
||||
|
||||
## UI 审查项
|
||||
|
||||
- U01:quick-run 执行期间禁用删除、扫描、工程选择和规则修改;服务层锁可阻止直接调用及其他进程实例绕过 UI。
|
||||
- U02:从关联的 command/status 文件重建并持久化队列进度;项目和任务最终进入 Completed。界面明确该状态只代表所选工程的当前图页规则队列,不代表全工程、保存或外部检查完成。
|
||||
- U03:证据按钮指向任务绑定的真实 `quick-run` 输出;后续队列归档后仍可从 `quick-run-history` 定位旧任务证据。
|
||||
- U04:规则表“启用”列改为可操作复选框,编辑对话框也可启用或停用规则;执行中统一锁定。
|
||||
- U05:错误提示保留具体底层原因、当前工程/规则、写入不确定性和稳定错误编号;`quick_run_complete` 使用普通完成提示,不再显示失败弹窗。
|
||||
- V01-V03:自动替换按钮成为主操作,删除操作使用危险语义;增加真实队列计数、当前项、忙碌指示和运行时长,左侧操作改为紧凑两列布局。
|
||||
- V04:窗口最小尺寸由 1100x700 调整为 900x600;工程、规则和执行区域继续使用可拖动 QSplitter,表格列保持 Interactive,并用滚动处理小窗口内容。
|
||||
|
||||
## 验证结果
|
||||
|
||||
```text
|
||||
原代码审查复现 + 新 UI 审查复现 + 任务中心/UI 定向回归:154 passed
|
||||
最终完整 pytest:937 passed in 1889.45s
|
||||
打包专项测试:7 passed
|
||||
PyInstaller:构建成功,Python 3.12.13
|
||||
源码与打包 QuickPartReplace.vbs:SHA-256 一致
|
||||
dist EXE 冒烟:通过
|
||||
部署目录 EXE 冒烟:ExitCode=0,application_start/clean_shutdown 均存在
|
||||
900x600 离屏渲染:无控件重叠,分隔区和表格滚动正常
|
||||
```
|
||||
|
||||
部署位置:`F:\Sync Tool Skyworth\Work Maps\DxPartReplace-Test`。
|
||||
|
||||
部署 EXE SHA-256:`1F682EB83E2F5DD723CD36361F7F552129BF15D98949F40311FD8D37CCEAC38D`。
|
||||
|
||||
部署 VBS SHA-256:`B7A3FE65D275462F8CB2F0E68447797F6959F2174D8723A6792FBDCE0B82BD04`。
|
||||
|
||||
旧部署备份:`F:\Sync Tool Skyworth\Work Maps\DxPartReplace-Test.backup-20260906-130722`。
|
||||
|
||||
## 现场验证边界
|
||||
|
||||
本机没有目标中央库,因此本次没有宣称真实库元件替换或现场端到端验收完成。当前结果证明代码复现、自动化回归、构建、部署和应用启动链路通过;真实 DxDesigner 联调仍需在连接正确中央库的可丢弃完整工程副本上执行,并由操作员审阅后决定是否保存。
|
||||
@@ -0,0 +1,133 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
from threading import Event
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.part_replace.models import MappingRule
|
||||
from dx_productivity.trial_task_center.comparison import compare_profiles
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
FIXTURES = ROOT / "tests" / "fixtures" / "trial_task_center"
|
||||
|
||||
|
||||
def profile(name: str) -> dict:
|
||||
return json.loads((FIXTURES / name).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("missing", ("pins", "units", "net_identity"))
|
||||
def test_comparison_requires_observed_connectivity(missing: str) -> None:
|
||||
before = profile("profile-before.json")
|
||||
after = profile("profile-after-valid.json")
|
||||
for snapshot in (before, after):
|
||||
component = snapshot["components"][0]
|
||||
if missing == "pins":
|
||||
component["pins"] = []
|
||||
component["nets"] = []
|
||||
elif missing == "units":
|
||||
component["units"] = 0
|
||||
else:
|
||||
component["pins"][0]["net_identity"] = None
|
||||
component["nets"] = []
|
||||
result = compare_profiles(before, after, (MappingRule("OLD-1", "NEW-1"),))
|
||||
assert not result.passed, f"missing {missing} unexpectedly passed: {result.to_json()}"
|
||||
|
||||
|
||||
def test_library_wins_pin_name_change_is_not_connectivity_change() -> None:
|
||||
before = profile("profile-before.json")
|
||||
after = profile("profile-after-valid.json")
|
||||
after["components"][0]["pins"][0]["name"] = "LIBRARY-RENAMED-PIN"
|
||||
result = compare_profiles(before, after, (MappingRule("OLD-1", "NEW-1"),))
|
||||
assert result.passed, result.to_json()
|
||||
|
||||
|
||||
def test_incomplete_enumeration_cannot_pass() -> None:
|
||||
before = profile("profile-before.json")
|
||||
after = profile("profile-after-valid.json")
|
||||
for snapshot in (before, after):
|
||||
snapshot["enumeration"] = {
|
||||
"available": False,
|
||||
"component_count": 200,
|
||||
"route": "Application.DesignComponents",
|
||||
}
|
||||
result = compare_profiles(before, after, (MappingRule("OLD-1", "NEW-1"),))
|
||||
assert not result.passed, result.to_json()
|
||||
|
||||
|
||||
def test_component_count_mismatch_cannot_pass() -> None:
|
||||
before = profile("profile-before.json")
|
||||
after = profile("profile-after-valid.json")
|
||||
for snapshot in (before, after):
|
||||
snapshot["enumeration"] = {
|
||||
"available": True,
|
||||
"component_count": 200,
|
||||
"route": "Application.DesignComponents",
|
||||
}
|
||||
result = compare_profiles(before, after, (MappingRule("OLD-1", "NEW-1"),))
|
||||
assert not result.passed, result.to_json()
|
||||
|
||||
|
||||
def test_saved_before_hash_is_rechecked_before_completion(tmp_path: Path) -> None:
|
||||
helpers = runpy.run_path(str(ROOT / "tests" / "trial_task_center" / "test_runner.py"))
|
||||
runner, store, task_id, project_ids, probe = helpers["_runner_with_probe_source"](tmp_path)
|
||||
project_id = project_ids[0]
|
||||
project_path = store.list_projects(task_id)[0].path
|
||||
try:
|
||||
runner.start_task(task_id, disposable_copy_confirmed=True)
|
||||
helpers["_write_profile"]("profile-before.json", probe, project_path)
|
||||
runner.capture_before(task_id, project_id, probe)
|
||||
context = store.current_attempt(project_id)
|
||||
altered = json.loads(context.before_path.read_text(encoding="utf-8"))
|
||||
altered["components"][0]["pins"][0]["x"] = 999
|
||||
context.before_path.write_text(json.dumps(altered), encoding="utf-8")
|
||||
helpers["_write_profile"]("profile-after-valid.json", probe, project_path)
|
||||
after = json.loads(probe.read_text(encoding="utf-8"))
|
||||
after["components"][0]["pins"][0]["x"] = 999
|
||||
probe.write_text(json.dumps(after), encoding="utf-8")
|
||||
with pytest.raises(Exception, match="evidence_integrity"):
|
||||
runner.capture_after(task_id, project_id, probe)
|
||||
assert store.list_projects(task_id)[0].status.value == "failed"
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
def test_busy_quick_run_stays_disabled_when_task_is_reopened(qtbot, tmp_path: Path) -> None:
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
|
||||
|
||||
store = TaskStore(tmp_path / "task-center.db")
|
||||
service = TaskCenterService(store, configure_logging(tmp_path / "storage"))
|
||||
task = service.create_task("Audit fixture")
|
||||
project_root = tmp_path / "projects"
|
||||
project_root.mkdir()
|
||||
(project_root / "test.prj").touch()
|
||||
project = service.scan_projects(task.task_id, project_root)[0]
|
||||
service.set_project_selected(project.project_id, True)
|
||||
service.add_rule(task.task_id, "OLD-1", "NEW-1")
|
||||
window = TrialTaskCenterWindow(service)
|
||||
qtbot.addWidget(window)
|
||||
window.open_task(task.task_id)
|
||||
started = Event()
|
||||
release = Event()
|
||||
|
||||
def blocked_worker() -> None:
|
||||
started.set()
|
||||
release.wait(5)
|
||||
|
||||
try:
|
||||
window._run_async(blocked_worker, lambda _result: None, window.run_panel.quick_run_button)
|
||||
qtbot.waitUntil(started.is_set, timeout=2000)
|
||||
assert not window.run_panel.quick_run_button.isEnabled()
|
||||
window.open_task(task.task_id)
|
||||
assert not window.run_panel.quick_run_button.isEnabled(), "task refresh reenabled an executing mutation"
|
||||
finally:
|
||||
release.set()
|
||||
qtbot.waitUntil(lambda: not window._workers, timeout=3000)
|
||||
window.close()
|
||||
store.close()
|
||||
@@ -0,0 +1,108 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from threading import Event
|
||||
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
from dx_productivity.trial_task_center.models import ProjectStatus, TaskStatus
|
||||
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
|
||||
|
||||
|
||||
def setup_window(qtbot, root: Path, started: Event | None = None, release: Event | None = None):
|
||||
storage = root / "storage"
|
||||
projects = root / "projects"
|
||||
projects.mkdir()
|
||||
(projects / "board.prj").touch()
|
||||
|
||||
def fake_worker(command, timeout):
|
||||
if started is not None:
|
||||
started.set()
|
||||
if release is not None:
|
||||
assert release.wait(5)
|
||||
handoff = storage / "quick-run"
|
||||
job_id = (handoff / "command.tsv").read_text(encoding="utf-8").splitlines()[1].split("\t")[1]
|
||||
with (handoff / "status.tsv").open("a", encoding="utf-8") as status:
|
||||
status.write(f"{job_id}\tawaiting_native_replace\t\tFixture selection\n")
|
||||
status.write(f"{job_id}\trestored_ok\t\tFixture completion\n")
|
||||
return subprocess.CompletedProcess(command, 0, "", "")
|
||||
|
||||
store = TaskStore(storage / "task-center.db")
|
||||
service = TaskCenterService(
|
||||
store,
|
||||
configure_logging(storage),
|
||||
path_opener=lambda path: None,
|
||||
quick_run_preparer=QuickRunPreparer(
|
||||
storage,
|
||||
process_runner=fake_worker,
|
||||
cscript_resolver=lambda: Path("unused-cscript.exe"),
|
||||
),
|
||||
)
|
||||
task = service.create_task("UI fixture")
|
||||
project = service.scan_projects(task.task_id, projects)[0]
|
||||
service.set_project_selected(project.project_id, True)
|
||||
service.add_rule(task.task_id, "OLD", "NEW")
|
||||
window = TrialTaskCenterWindow(service, quick_run_confirmer=lambda *args: True)
|
||||
qtbot.addWidget(window)
|
||||
window.open_task(task.task_id)
|
||||
return window, service, store, task, project
|
||||
|
||||
|
||||
def finish_fixture(window, service, task):
|
||||
result = service.execute_quick_run(task.task_id)
|
||||
assert result.state == "restored_ok" and result.next_project_path is None
|
||||
window._show_quick_run_result(result)
|
||||
window._update_gates()
|
||||
return result
|
||||
|
||||
|
||||
def test_success_updates_project_and_task_state(qtbot, tmp_path: Path) -> None:
|
||||
window, service, store, task, project = setup_window(qtbot, tmp_path)
|
||||
try:
|
||||
finish_fixture(window, service, task)
|
||||
assert service.projects(task.task_id)[0].status is ProjectStatus.COMPLETED
|
||||
assert service.get_task(task.task_id).status is TaskStatus.COMPLETED
|
||||
finally:
|
||||
window.close()
|
||||
store.close()
|
||||
|
||||
|
||||
def test_success_enables_evidence_button(qtbot, tmp_path: Path) -> None:
|
||||
window, service, store, task, project = setup_window(qtbot, tmp_path)
|
||||
try:
|
||||
finish_fixture(window, service, task)
|
||||
assert window.run_panel.open_evidence_button.isEnabled()
|
||||
finally:
|
||||
window.close()
|
||||
store.close()
|
||||
|
||||
|
||||
def test_evidence_action_opens_current_execution_outputs(qtbot, tmp_path: Path) -> None:
|
||||
window, service, store, task, project = setup_window(qtbot, tmp_path)
|
||||
try:
|
||||
result = finish_fixture(window, service, task)
|
||||
opened = service.open_evidence(task.task_id, project.project_id)
|
||||
assert opened.resolve() == result.status_path.parent.resolve()
|
||||
finally:
|
||||
window.close()
|
||||
store.close()
|
||||
|
||||
|
||||
def test_deletion_is_blocked_while_quick_run_executes(qtbot, tmp_path: Path) -> None:
|
||||
started = Event()
|
||||
release = Event()
|
||||
window, service, store, task, project = setup_window(qtbot, tmp_path, started, release)
|
||||
try:
|
||||
window._prepare_quick_run()
|
||||
qtbot.waitUntil(started.is_set, timeout=2000)
|
||||
assert window._workers
|
||||
window._delete_task()
|
||||
assert service.get_task(task.task_id).status is not TaskStatus.DELETED
|
||||
finally:
|
||||
release.set()
|
||||
qtbot.waitUntil(lambda: not window._workers, timeout=3000)
|
||||
window.close()
|
||||
store.close()
|
||||
@@ -0,0 +1,120 @@
|
||||
# UI 专项审查:DxDesigner 器件批量替换任务中心
|
||||
|
||||
日期:2026-09-06。审查当前源码中的实际 PySide6 窗口,而非仅评价样式表。用临时工程、SQLite 数据库和模拟成功的 worker 渲染界面;没有连接 DxDesigner。
|
||||
|
||||
## 结论
|
||||
|
||||
UI 最大的问题是**自动执行流程与旧任务中心的状态、权限、证据入口没有统一**,并非单纯“不够美观”。确认 5 类功能/交互问题,其中执行重入是上一份报告已记录的问题;另有 4 类视觉与可用性改进点。以下不把外观偏好等同于代码漏洞。
|
||||
|
||||
## 一、功能与交互缺陷
|
||||
|
||||
### U01 · P1 · 执行期间的操作保护不完整
|
||||
|
||||
- 位置:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\ui\main_window.py:390`。
|
||||
- 原已复现:后台 worker 未结束时重新打开任务,替换按钮被 `_update_gates()` 重新启用,允许重复发起执行。
|
||||
- 新增复现:后台 worker 被 Event 阻塞时,调用界面的删除操作,任务从 draft 变为 deleted,而 worker 仍继续执行。位置:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\ui\main_window.py:457`。
|
||||
- 原因:quick-run 没有将任务置为运行中,数据库的“禁止删除运行中任务”规则没有生效;按钮状态也没有统一绑定真实执行占用。删除不会取消 worker,切换任务后其结果还可能因上下文检查而不再呈现在当前界面。
|
||||
- 建议:执行生命周期由服务层统一管理;执行中锁住重复启动、删除及会改变执行输入的操作。切换查看别的任务可以允许,但必须始终保留当前活动作业的状态入口。安全取消需要有明确恢复语义,不能简单杀进程。
|
||||
|
||||
### U02 · P2 · 成功提示与工程、任务状态相互矛盾
|
||||
|
||||
- 位置:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\ui\main_window.py:610`;`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\service.py:228`。
|
||||
- 复现:让真实 execute_quick_run 消费模拟的有效 `awaiting_native_replace → restored_ok` 状态,所有规则均完成。实际输出:`result=restored_ok`、`next=None`,但 `task=draft`、`project=pending`。
|
||||
- 窗口底部写“当前队列已完成”,工程表仍写“待处理”,左侧仍在“进行中”;重新加载也不能凭空补上未持久化的完成状态。“已完成”筛选因此无法展示这些自动完成的任务/工程。
|
||||
- 建议:统一队列、工程和任务的状态来源,并且区分“当前图页校验完成”“整个工程完成”“保存完成”;不能只把按钮改成完成文案。
|
||||
|
||||
### U03 · P2 · 证据按钮不可用,诊断入口还会打开旧流程的空目录
|
||||
|
||||
- 位置:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\ui\main_window.py:400`;`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\service.py:290`。
|
||||
- 复现一:成功完成快速替换后,“打开证据目录”按钮仍为 disabled。它依赖人工 TrialRunner 的 active_project,而 quick-run 不产生该记录。
|
||||
- 复现二:直接调用与诊断按钮相同的 open_evidence 服务,打开的是 `tasks/<task>/evidence/<project>/attempt-1`,当前执行的 TSV、快照和 native 报告却在 `quick-run`。服务还会创建那个旧流程目录,让用户看到一个存在但没有当前证据的文件夹。
|
||||
- 建议:证据入口绑定具体 execution/run ID 及真实输出路径;成功、失败、状态不确定三种结果都应能打开对应证据,而不是依赖“当前活动项目”。
|
||||
|
||||
### U04 · P2 · “启用”列只有展示,没有启用/禁用规则的操作入口
|
||||
|
||||
- 位置:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\ui\mapping_table.py:30`;`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\ui\main_window.py:552`。
|
||||
- 静态确认:表格设为 NoEditTriggers,“启用”列只是“是/否”文本。编辑对话框只有旧料号、新料号,提交时继续传入原来的 `enabled=rule.enabled`。
|
||||
- 影响:用户无法临时停用某条规则,只能删除或在界面外修改数据;已有 disabled 规则也不能从界面重新启用。
|
||||
- 建议:启用列提供复选框或在编辑对话框提供开关,调用已有 service.update_rule;执行中统一锁定。
|
||||
|
||||
### U05 · P2 · 错误反馈丢失具体原因,把不同故障统一描述为连接问题
|
||||
|
||||
- 位置:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\ui\main_window.py:778`。
|
||||
- 静态确认:界面仅按 error.code 显示 ERROR_TEXT 和错误编号,不显示 stable_error.message。不同 quick_run_execution 原因会被统一引导为“确认已打开正确工程和图页”;quick_run_uncertain 还固定描述为“执行超时”,但该错误也可来自状态无法关联或状态文件损坏。
|
||||
- 影响:用户看不到目标库不匹配、校验失败等具体原因,容易按错误方向重复操作;与 U03 的证据入口问题叠加后,诊断链路更差。
|
||||
- 建议:保留简短中文结论,另提供可展开的具体原因、当前工程/规则、是否已写入和下一步;显示经过适当处理的错误细节,不把所有错误文本原样塞进主提示条。
|
||||
|
||||
## 二、视觉与可用性问题
|
||||
|
||||
### V01 · 主操作缺少视觉层级
|
||||
|
||||
`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\ui\styles.py:10` 把蓝色主按钮样式绑定给旧的 startTaskButton,当前真正显示的 quickRunButton 没有对应样式,因此与“添加、编辑、删除”等普通按钮同级。
|
||||
|
||||
建议:将“自动替换并校验”设为明确主操作;把危险的删除操作和辅助操作区分开。不能仅靠颜色表达是否可执行,还要有状态文案。
|
||||
|
||||
### V02 · 缺少执行进度及运行中反馈
|
||||
|
||||
当前快跑操作在后台执行,但窗口没有对应的阶段显示、运行时长或队列进度;主要即时变化是按钮被禁用。成功、普通指导和错误也共用黄色提示带,缺少明确的语义区分。
|
||||
|
||||
建议:显示“工程 1/3、规则 2/5、当前阶段、耗时”,执行期间提供忙碌标识;结果摘要分别显示完成、失败、待人工确认。阶段进度需要真实事件支持,不应伪造百分比。
|
||||
|
||||
### V03 · 信息布局偏重空表格,缺少工程任务摘要
|
||||
|
||||
1280×800 的隔离渲染中,左侧任务列占据较大宽度且底部横排四个按钮;右侧两个表格保留大量空白,却没有清楚的“已选工程数、启用规则数、当前执行对象、上次执行结果”汇总。成功信息在提示条与日志区域重复,工程状态却没有同步。
|
||||
|
||||
建议:压缩左侧工具栏,把操作摘要放到执行区附近;明确“配置输入 → 执行确认 → 结果检查”的阅读顺序。日志作为可展开诊断区域,不承担唯一的结果展示职责。
|
||||
|
||||
### V04 · 小可用桌面和高缩放场景存在适配风险
|
||||
|
||||
位置:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\ui\main_window.py:156`,窗口硬性最小尺寸为 1100×700。可用逻辑桌面低于该尺寸时,窗口无法缩小适配;例如某些低分辨率叠加系统缩放的环境。
|
||||
|
||||
这是根据固定最小尺寸推导的兼容性风险,本次没有改变用户显示缩放进行现场验证。建议做紧凑布局、可折叠导航和滚动兜底,并分别测试常用可用逻辑分辨率;不要只降低字体来强行塞入。
|
||||
|
||||
## 三、验证记录
|
||||
|
||||
新增附件:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\docs\reviews\2026-09-06-ui-repros.py:1`。
|
||||
|
||||
```powershell
|
||||
$env:QT_QPA_PLATFORM='offscreen'
|
||||
.\.venv\Scripts\python.exe -m pytest docs/reviews/2026-09-06-ui-repros.py -q --tb=short
|
||||
```
|
||||
|
||||
实际结果:`4 failed in 0.96s`。分别在“成功后应更新状态”“证据按钮应可用”“证据入口应打开当前输出”“执行中应阻止删除”四个业务断言处失败;没有连接真实 DxDesigner,未修改业务代码。U01 的按钮重入复现沿用上一份审查附件;U04/U05 为完整 UI 调用路径的静态确认。
|
||||
|
||||
模拟成功后的界面截图:
|
||||
|
||||

|
||||
|
||||
截图使用临时演示数据和模拟 worker,不是实际工程替换完成的证明。建议先修复 U01–U03 的流程与状态,再补齐 U04/U05,最后进行视觉优化。
|
||||
|
||||
## 四、补充复核:功能完整性、美观度与错误警告
|
||||
|
||||
本节重新读取了当前源码。main_window.py 和 service.py 已出现新增的 busy gate / quick-run lease 实现,因此前文 U01 的执行重入结论属于此前审查基线,不能不经复测直接认定最新源码仍未修复。本轮不改动这些新实现,仅核对当前提示逻辑。
|
||||
|
||||
### 实际验证的六种提示偏差
|
||||
|
||||
使用隔离 service 产生真实重复规则、规则链和任务重名错误;另外向真实隐藏窗口注入三类 TaskCenterError,以验证错误呈现函数。窗口未显示,未进入模态事件循环,也没有连接 DxDesigner。验证命令正常退出。
|
||||
|
||||
| 实际错误/状态 | 当前 UI 文案 | 更准确的处理 |
|
||||
| --- | --- | --- |
|
||||
| 重复旧料号 | 操作失败:操作未完成,请查看日志了解详细原因。 | 在规则输入处指出具体旧料号已经存在,保留输入便于修改 |
|
||||
| A→B、B→C 的规则链 | 同上 | 说明目标料号同时被用作其他规则的来源,指出冲突规则 |
|
||||
| 任务重名 | 同上 | 在任务名称输入框旁提示名称已存在 |
|
||||
| quick_run_uncertain:状态无法关联,而非超时 | 操作失败:替换执行超时,工程状态不确定。请人工核对后再继续。 | 表达“无法确认本次结果”,明确可能已修改,不伪称超时 |
|
||||
| quick_run_execution:底层报告具体目标库错误 | 统一提示确认正确工程和图页 | 展示具体错误类别及详情,不误导用户反复打开工程 |
|
||||
| quick_run_complete:全部规则已完成 | 操作失败:当前任务中的替换规则已经全部完成。 | 用普通完成/无须重复执行提示,而不是失败弹窗 |
|
||||
|
||||
原因位于 `F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src\dx_productivity\trial_task_center\ui\main_window.py:785`:所有 TaskCenterError 共用失败前缀和 Critical 弹窗,只按 code 查固定文案,且丢弃具体 message。quick_run_uncertain 本身包含多种根因,不宜统一翻译为超时。
|
||||
|
||||
### 还需要修正的安全提示
|
||||
|
||||
- “请人工核对后再继续”没有对应的验证恢复流程。uncertain.flag 存在时后台仍会拒绝执行;用户仅核对界面并不能解除状态。应提供带证据和状态核验的恢复步骤,不能通过直接删除 flag 或普通“继续”绕过保护。
|
||||
- 当前自动替换确认框只显示已选工程数、规则数和“打开正确工程/图页”,没有展示这次即将执行的准确工程、图页、旧料号→新料号和命中数量,也未明确要求使用可恢复副本。
|
||||
- 最终“连接校验均已完成”没有解释当前图页的范围,也没有区分当前图页、全工程、保存和外部检查。应只声明实际执行并验证的范围,避免把局部成功理解为整项目验收完成。
|
||||
|
||||
### 产品完整性与视觉建议
|
||||
|
||||
- 执行前提供只读匹配预览;执行中提供真实阶段、队列进度和当前对象;结束后提供成功/失败/未匹配的结构化结果及证据入口。
|
||||
- 批量规则维护可以增加导入、导出、搜索和筛选;这些是新增产品能力建议,并非已承诺但失效的代码功能。
|
||||
- 视觉层级采用“当前任务摘要 → 工程与规则配置 → 执行及结果”,主操作显著,日志折叠;成功、警告、失败、状态不确定使用不同语义及文字,不只更换颜色。
|
||||
- 表单输入错误优先内联;普通完成状态不弹失败框;只有涉及可能写入、恢复或数据损失的情况才使用阻断性警告。
|
||||
@@ -0,0 +1,48 @@
|
||||
# R11 实际 EXE 验收及功能修复
|
||||
|
||||
## 验收边界
|
||||
|
||||
通过 Explorer 实际双击候选 EXE 快捷方式,使用独立数据目录和可丢弃工程副本完成界面操作。没有使用服务层调用替代任务创建、规则编辑、执行确认、暂停恢复或错误对话框操作。SQLite 仅作只读断言;保存后的 CAD 读回用于独立验证,不替代实际 EXE 执行。
|
||||
|
||||
## 实际验证
|
||||
|
||||
| 场景 | 结果 |
|
||||
| --- | --- |
|
||||
| 任务增删改、重名/空名校验、软删除、恢复、永久删除及取消 | 通过实际 GUI 验证 |
|
||||
| 工程扫描、重扫保留选择、全选/清空、待处理/已完成过滤 | 通过 |
|
||||
| 规则新增、编辑、删除、启停、排序、重复/链式/自映射校验 | 通过 |
|
||||
| 内部分隔条、日志开关、布局重置及重启保留、只读滚动和列宽调整 | 通过 |
|
||||
| 两工程三规则混合队列 | 6/6:4 项未命中、2 项已保存替换 |
|
||||
| 20 工程全部未命中 | 自动连续完成 20/20,无逐项确认或不确定保护 |
|
||||
| 勾选 Part Number 写入 Value | 40 个器件保存后读回符合要求 |
|
||||
| 未勾选 Value | 20 个器件保留目标库值 10n,不额外改写为 Part Number |
|
||||
| 显示样式、位置方向、实例字段、引脚/连接 | 保存后读回核验通过 |
|
||||
| 暂停、删除、恢复后续跑 | 从 2/6 继续,不重做已完成项 |
|
||||
| 原生替换期间移动鼠标、拖动窗口/分隔条 | 队列继续且没有不确定状态 |
|
||||
| 旧料号未命中后目标库料号不存在 | 未命中跳过;缺失目标在原生替换前停止,后续规则不执行;20 个源器件保持不变 |
|
||||
| 明确确认后重试替换前失败 | 不重做前面未命中项;不误报已改图 |
|
||||
| 正在查看另一任务时后台队列结束/失败 | 错误可见、按钮解锁、任务列表更新,旧任务进度不被覆盖 |
|
||||
| 实际中断属性恢复阶段 | 检出旧版遗留非终态;GUI 核验磁盘中已有效保存的结果,不重复原生替换,完成 1/1 |
|
||||
| 已打开工程的所有权保护 | 拒绝接管,未执行替换 |
|
||||
| 两图页工程保护 | 捕获/替换前拒绝,显示单图页限制和停止状态 |
|
||||
|
||||
## 根因修复
|
||||
|
||||
- 自动队列持久化暂停状态,人工流程与自动执行共用互斥保护。
|
||||
- 修改性控件及时禁用,表格保留只读查看和调整能力。
|
||||
- 完整旧队列先归档再校验新任务 Value 策略;历史进度绑定对应任务证据。
|
||||
- 列表刷新不触发瞬时旧选择回调;后台完成始终刷新当前界面的按钮状态,错误绑定发起任务。
|
||||
- 区分启动/工程检查失败、原生替换前校验失败以及结果不确定,停止后不继续显示“正在执行”。
|
||||
- 非终态退出或可能改图后失败建立保护;没有保护标志的旧版遗留任务也能显示核验入口。解除保护仍要求快照、规则、Value 策略和原生事务绑定核验。
|
||||
- 只读恢复确认磁盘仍是源器件时,先关闭恢复过程打开的只读工程再给出重试;关闭失败或文档所有权变化不解锁重试。
|
||||
- 标题和日志共用 R11 版本常量。
|
||||
|
||||
## 自动化回归与限制
|
||||
|
||||
317 项回归通过,包含执行队列、任务状态互斥、Qt 界面、Windows VBS、恢复、Value 策略和打包检查。冻结包中 30 个代码对象、VBS 和独立启动检查通过。
|
||||
|
||||
真实中断验收得到的是“磁盘结果已有效保存”的分支;“磁盘仍是旧器件”的重试准备及只读关闭保护有 Python/VBS 回归覆盖,不冒充已完成该分支的真实 CAD 验收。
|
||||
|
||||
连续模式目前仅支持单图页工程,不遍历多图页。未命中是正常跳过结果;缺失目标、真实异常和结果不确定仍必须停止。317 项测试和上述真实样本不能证明不存在其他缺陷。
|
||||
|
||||
原生产任务和原工程没有用于本次执行验收。发布需保留旧版、备份原生产数据、校验合并源文件与发布包,并对正式路径下的 EXE 再做独立数据目录的实际点击验收。
|
||||
@@ -0,0 +1,45 @@
|
||||
# R12 多图页实际 EXE 验收
|
||||
|
||||
## 验收边界
|
||||
|
||||
通过桌面快捷方式实际双击候选 EXE,使用全新隔离数据目录和可丢弃的双图页工程副本完成任务创建、工程扫描、规则添加、Value 策略勾选、确认和自动执行。正式发布后又从正式路径实际双击一次,确认复制后的冻结包可独立启动并干净退出。
|
||||
|
||||
## 实际结果
|
||||
|
||||
| 场景 | 结果 |
|
||||
| --- | --- |
|
||||
| 双图页枚举 | 识别 `Schematic1:1` 和 `Schematic1:2`,生成两条明确绑定图页的队列项 |
|
||||
| 第 1 页替换 | `C0603-100U-J -> C0603-10N-J`,20 个器件替换、保存、重新打开回读通过 |
|
||||
| 第 2 页未命中 | 记录 `no_match/batch_closed` 并自动继续,队列未停止 |
|
||||
| 队列结果 | 全工程图页队列 `2/2`,替换校验 1 项,未命中跳过 1 项 |
|
||||
| Value 策略 | 20 个目标器件的有效 Value 均为 `C0603-10N-J` |
|
||||
| Value 显示样式 | 20 个器件的位置、颜色、字体、字号、方向和可见性均与替换前快照一致 |
|
||||
| 执行中拖动 | 执行期间将内部工程/规则分隔条拖动 55 像素,后台任务继续并正常完成 |
|
||||
| CAD 所有权 | 验收前无 DxDesigner;由程序启动的实例只处理验收副本,工程关闭后用于只读回读并正常退出 |
|
||||
| UI 完成提示 | 黄色区域表示“已完成但存在未命中”,不作为错误,也不阻断后续图页 |
|
||||
|
||||
执行证据位于:
|
||||
|
||||
`C:\Users\ABS_Windows\.codex\visualizations\2026\09\06\01a07479-a905-7cd3-bb57-5f99b03d06fb\round13-multisheet-r12-20260907`
|
||||
|
||||
其中 `gui-data-r12\quick-run\sheets.tsv`、`command.tsv` 和 `status.tsv` 分别记录固定图页清单、逐页命令和终态。完成界面截图为 `r12-multisheet-complete.png`。
|
||||
|
||||
## 自动化回归
|
||||
|
||||
- 旧替换模块:454 项通过。
|
||||
- 旧 VBS/批处理集成组:342 项通过。
|
||||
- 多图页、任务中心、UI、Value、会话和打包核心组:323 项通过。
|
||||
- 构建前应用与打包检查:7 项通过。
|
||||
- 冻结包中的 `QuickPartReplace.vbs` 与源码 SHA256 一致,构建前后 7 个关键源码文件哈希未变化。
|
||||
|
||||
## 发布记录
|
||||
|
||||
- 正式路径:`F:\Sync Tool Skyworth\Work Maps\DxPartReplace-Test\DxPartReplace.exe`
|
||||
- 版本:`2026.09.07-R12`
|
||||
- EXE SHA256:`E16344DCED13B25C6122A6377D6A1AD560B40387142CD2C5EACAC40D18DA1AD7`
|
||||
- 冻结包:3699 个文件,669687137 字节;正式路径逐文件长度和 SHA256 与候选包一致。
|
||||
- R11 整包和原任务数据备份:`F:\Sync Tool Skyworth\Work Maps\DxPartReplace-Backups\release-20260907-112502`
|
||||
|
||||
## 剩余边界
|
||||
|
||||
真实 CAD 验收覆盖了一个两图页工程,其中一页实际命中、一页未命中。多工程、多规则、暂停续跑、图页清单变化保护和恢复绑定已由自动化测试覆盖,但本轮没有用大量真实多图页工程做压力测试。多工程仍严格串行,避免同时启动多个 CAD 工程造成资源竞争;真实批量性能需要按实际工程规模继续观察。
|
||||
@@ -0,0 +1,31 @@
|
||||
# R13 Value、NC 与永久删除验收
|
||||
|
||||
## 功能边界
|
||||
|
||||
- 未勾选“替换后将 Part Label 写入 Value”时,不读取或要求目标 Part Label,保留替换后目标器件的原生 Value。
|
||||
- 勾选后,将目标器件的有效 Part Label 写入 Value,并进行最终回读校验。
|
||||
- 旧 Value 含以 `/` 分隔的独立 `NC` 段时,两种 Value 模式都将 `/NC` 同步到替换后的 Value。
|
||||
- `NC`、`NCM` 和 `NC_OPTION` 等相似文本不视为 `/NC` 标记;目标值已有 `/NC` 时不重复追加。
|
||||
- 已删除任务可直接永久删除,不受自动队列锁限制;工程文件和诊断证据仍保留。
|
||||
|
||||
## 自动化结果
|
||||
|
||||
| 场景 | 结果 |
|
||||
| --- | --- |
|
||||
| Value、NC、批量与 UI 专项 | 94 项通过 |
|
||||
| Bridge 重解析路径复现 | 同步盘临时目录被安全检查拒绝;改用非重解析临时目录后通过 |
|
||||
| 完整测试套件 | 1135 项直接通过;唯一过期的 R12 窗口标题断言更新为 R13 后通过,合计 1136 项通过 |
|
||||
| NC 日志 | 输出 `位号 R1 R0603/NC -> R0805/NC,识别到 NC,已同步` |
|
||||
|
||||
## 发布记录
|
||||
|
||||
- 正式路径:`F:\Sync Tool Skyworth\Work Maps\DxPartReplace-Test\DxPartReplace.exe`
|
||||
- 版本:`2026.09.07-R13`
|
||||
- EXE SHA256:`95A88D4DD216761671A68687F7FE1F126886AF1AB1D7F2C271C9F167FC1D92A0`
|
||||
- 冻结包:3660 个文件,667523788 字节;正式目录逐文件长度和 SHA256 与候选包一致。
|
||||
- R12 整包备份:`F:\Sync Tool Skyworth\Work Maps\DxPartReplace-Backups\release-20260907-145943-R12-before-R13`
|
||||
- 正式路径隔离冒烟:`application_start version=2026.09.07-R13`,`application_clean_shutdown exit_code=0`。
|
||||
|
||||
## 剩余验证
|
||||
|
||||
自动化已覆盖缺失 Value、缺失或空白 Part Label、已有 `/NC`、相似文本误识别边界和批量日志聚合。发布前仍应使用可丢弃的真实 DxDesigner 工程分别验收勾选与未勾选模式,并核对保存后的工程文件。
|
||||
@@ -0,0 +1,37 @@
|
||||
# R14 工程目录切换验收
|
||||
|
||||
## 问题与修复
|
||||
|
||||
- 原实现切换扫描目录后只把旧工程标记为不可用,仍将它们返回给界面,因此新旧目录工程会同时显示。
|
||||
- 目录文本变化后,界面立即清空工程表,显示“目录已更改,等待重新扫描”,并在完成新扫描前禁用执行入口。
|
||||
- 尚未执行的任务切换目录时,持久层删除旧目录工程清单,再写入新目录扫描结果;新目录项目默认不勾选。
|
||||
- 同一目录重扫继续保留选择状态,并将本次缺失的工程标记为不可用。
|
||||
- 已有项目执行状态、attempt、恢复记录或自动队列证据时拒绝切换目录,保留旧清单并提示新建任务,避免丢失或混合审计证据。
|
||||
|
||||
## 验证结果
|
||||
|
||||
| 场景 | 结果 |
|
||||
| --- | --- |
|
||||
| 新目录替换未执行旧清单 | 通过 |
|
||||
| 已有执行记录时拒绝切换并保留原数据 | 通过 |
|
||||
| UI 修改目录后立即隐藏旧项目 | 通过 |
|
||||
| 当前源码专项重跑 | 9 项通过 |
|
||||
| 存储、服务、队列、恢复、批量及 UI 回归 | 172 项通过 |
|
||||
| 构建前检查 | 7 项通过 |
|
||||
| 正式路径隔离冒烟 | `application_start version=2026.09.07-R14`;`application_clean_shutdown exit_code=0` |
|
||||
|
||||
## 发布记录
|
||||
|
||||
- 版本:`2026.09.07-R14`
|
||||
- 正式程序:`F:\Sync Tool Skyworth\Work Maps\DxPartReplace-Test\DxPartReplace.exe`
|
||||
- 最新归档:`F:\Sync Tool Skyworth\Work Maps\DxPartReplace-R14-20260907.zip`
|
||||
- 归档大小:249279473 字节;3928 个 ZIP 条目;未压缩文件合计 667525074 字节。
|
||||
- ZIP SHA256:`B87878C775BB7A975E6531815343EC27398EF5998CB348E4F167C41124E6ABEC`
|
||||
- ZIP 内 EXE SHA256:`C8F37D4C55E974BEBD94F79972DDE0C1641972555AE8316DFF6230F8C04555B8`
|
||||
- ZIP 内 `QuickPartReplace.vbs` SHA256:`53EF207FFA2E5D97857EC9C069E2F58CC0F4FCFF2392F31EF13F6359D56BA107`
|
||||
|
||||
## 清理记录
|
||||
|
||||
- 已删除 R13 ZIP、R13 部署回滚候选、本轮 `build`、`dist` 和 R14 测试临时目录。
|
||||
- 保留源码目录、正式 R14 目录和唯一 R14 ZIP。
|
||||
- 更早的历史回滚备份与验收证据没有在本轮永久删除,避免在未单独确认保留策略时误删不可重建证据。
|
||||
@@ -0,0 +1,81 @@
|
||||
# R15 批量、恢复与长期运行验收
|
||||
|
||||
## 验收范围
|
||||
|
||||
本轮验证 `2026.09.08-R15` 的真实多图页执行、20 工程串行批量、未命中继续、故障恢复与暂停续跑、长期日志和历史留存、自动化回归、冻结包构建及独立冒烟。按用户要求,第 5 项干净电脑外发验收未执行。
|
||||
|
||||
所有真实 CAD 写入均使用可丢弃工程副本。测试期间只清理本轮明确启动的 DxDesigner 进程,没有结束并发测试或其他未知进程。
|
||||
|
||||
## 真实 DxDesigner 7.9.5
|
||||
|
||||
| 场景 | 结果 |
|
||||
| --- | --- |
|
||||
| 双图页、两条规则 | 4 个队列项全部结束:1 个 `saved_ok`,3 个 `no_match`;未命中没有中断队列 |
|
||||
| 实际命中 | `C0603-10N-J -> C0603-100U-J`,20 个器件替换、保存、重新打开回读并关闭 |
|
||||
| Value 策略 | 勾选 Part Label 写入 Value;日志确认 `value_mode=part_label`,20 个器件回读通过 |
|
||||
| 图页范围 | 发现 `Schematic1:1`、`Schematic1:2`,命令逐页绑定,没有只处理当前页 |
|
||||
| 实际失败 | `C0603 -> C0805` 的连接校验失败后自动回滚并停止,未把失败当成未命中继续 |
|
||||
| 20 工程未命中批量 | 20/20 项均为 `no_match/batch_closed`,队列完成,无 `uncertain.flag`,无残留 `current-state.tsv` |
|
||||
| 备份顺序 | 20 个工程均在图页枚举前完成独立备份;全部备份和枚举完成后才进入替换队列 |
|
||||
| 性能 | 20 工程总耗时 653.431 秒;DxDesigner 单实例复用,观测工作集约 198.4 MiB 至峰值 249.3 MiB |
|
||||
|
||||
双图页证据:
|
||||
|
||||
`C:\Users\ABS_Windows\.codex\visualizations\2026\09\06\01a07479-a905-7cd3-bb57-5f99b03d06fb\r15-long-run-acceptance-20260907\multisheet-hit\data`
|
||||
|
||||
20 工程证据:
|
||||
|
||||
`C:\Users\ABS_Windows\.codex\visualizations\2026\09\06\01a07479-a905-7cd3-bb57-5f99b03d06fb\r15-long-run-acceptance-20260907\lb-003934`
|
||||
|
||||
回滚失败证据:
|
||||
|
||||
`C:\Users\ABS_Windows\.codex\visualizations\2026\09\06\01a07479-a905-7cd3-bb57-5f99b03d06fb\r15-long-run-acceptance-20260907\hit-miss-5\data`
|
||||
|
||||
## 故障与恢复
|
||||
|
||||
- 超时先请求安全停止,继续无响应才终止受控 worker;worker 及其允许的子进程不会残留。
|
||||
- 暂停后从下一条未完成命令继续,已完成命令不重复执行。
|
||||
- 命令、状态、快照或恢复绑定损坏时保持保护锁,不把不确定结果标成成功。
|
||||
- 初始备份失败使用 `quick_run_backup`,不会误显示成“中断恢复失败”。
|
||||
- Python 3.11 实机测试发现 `Path.is_junction()` 兼容崩溃后,备份哈希改为基于 `lstat` 和 Windows reparse 属性;3.11 探针及 3.12 回归均通过。
|
||||
- 故障、恢复、执行安全和批量专项共 82 项通过。
|
||||
|
||||
## 长期留存
|
||||
|
||||
- `quick-part-replace.log`:单段上限 5 MiB,保留 3 个轮转备份。
|
||||
- 单任务 `events.jsonl`:单段上限 5 MiB,保留 5 个轮转备份,事件序号跨段连续。
|
||||
- `quick-run-history`:默认 30 天、100 份或 5 GiB 任一边界触发清理,同时至少保留最新 10 份。
|
||||
- 清理仅识别 `batch-*`、`recovery-*`、`sheet-discovery-*` 和 `obsolete-*`;未知人工目录、链接和重定向目录不删除。
|
||||
- 250 份合成历史经默认参数收敛为最新 100 份(`batch-150` 至 `batch-249`);人工目录保留,5 轮 6 MiB 日志最终仅保留 3 个备份。
|
||||
- 留存与日志专项 10 项通过。
|
||||
|
||||
## 自动化回归
|
||||
|
||||
由于单个超长 pytest 会话在分组边界被外部执行器终止,最终按文件和目录拆分运行全部收集项;各组均独立返回退出码 0:
|
||||
|
||||
| 分组 | 结果 |
|
||||
| --- | --- |
|
||||
| Integration | 424 passed |
|
||||
| Part replacement core | 454 passed |
|
||||
| Trial task center | 254 passed |
|
||||
| UI(Qt offscreen) | 40 passed |
|
||||
| Packaging | 2 passed |
|
||||
| 合计 | 1174 passed |
|
||||
|
||||
`pip check` 返回 `No broken requirements found`,`compileall -q src` 通过。
|
||||
|
||||
## 构建结果
|
||||
|
||||
- 构建前应用与打包检查:8 项通过。
|
||||
- 候选程序:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\dist\DxPartReplace\DxPartReplace.exe`
|
||||
- EXE SHA256:`C560BA6A65A37CC29F2F2D80FFD9283E3871E601376FFEC000E75A35570E2DCF`
|
||||
- 冻结目录:218 个文件,105.54 MiB。
|
||||
- 源码及包内 `QuickPartReplace.vbs` SHA256:`B4FDD1C47B379D5E1541423DF8FF2CB29815B534D9E0998BB2DB0D3305FA11BA`。
|
||||
- 独立冒烟:退出码 0;日志包含 `application_start version=2026.09.08-R15` 和 `application_clean_shutdown exit_code=0`。
|
||||
|
||||
## 已知边界
|
||||
|
||||
- 未执行用户排除的干净电脑安装、杀毒软件、不同权限账户和缺少开发环境时的外发验收。
|
||||
- 20 工程实机压力场景验证的是大批量未命中继续;批量连续多次真实写入仍只由自动化测试和单工程实机命中覆盖。
|
||||
- 32 位 WSH/ADODB 对超长控制文件路径仍有传统限制:273 字符的人工验收数据根无法读取监督授权文件,247 字符路径可正常运行。正式应用默认 `%LOCALAPPDATA%` 数据根不触发该问题;自定义超长 `--data-root` 不在支持范围内。
|
||||
- 本轮只生成仓库 `dist` 候选包,没有覆盖工作区外的 `DxPartReplace-Test` 正式目录,也没有创建新的外发 ZIP。
|
||||
@@ -0,0 +1,51 @@
|
||||
# R16 便携数据与批量性能验收
|
||||
|
||||
## 本轮结果
|
||||
|
||||
- 发布版默认数据根改为 `DxPartReplace.exe` 同目录的 `data`;数据库、日志、任务证据和工程备份均位于该目录下。源码开发运行仍使用 `%LOCALAPPDATA%`,命令行和环境变量覆盖保持不变。
|
||||
- 构建脚本重建 `dist` 前会暂存并恢复已有 `data`,避免更新程序时删除本机备份。正式安装目录的镜像更新同样排除 `data`。
|
||||
- 扫描工程时排除当前数据根,选择安装目录或其上级目录时不会把 `data\quick-run-history\batch-*\project-*` 中的备份重新识别成待处理工程。
|
||||
- 图页枚举同时建立规则旧料号命中索引。已确认未命中的队列项直接记录为 `no_match/batch_closed`,不再为同一结论第二次打开工程。
|
||||
- 真实命中完成后清理 `current-state.tsv`;未命中项不执行无意义的删除系统调用,1000 项合成队列性能门槛重新通过。
|
||||
- 替换日志优先使用替换前快照中的位号;原工程未标注位号时使用 `UID=...`,不输出无法追踪的空白条目。
|
||||
|
||||
## 实测性能
|
||||
|
||||
| 场景 | 总耗时 | 每工程 | 真实结果 |
|
||||
| --- | ---: | ---: | --- |
|
||||
| R15,20 工程未命中 | 653.431 秒 | 32.672 秒 | 20/20 `no_match`,仍启动 20 次替换 worker |
|
||||
| R16,20 工程未命中 | 218.472 秒 | 10.924 秒 | 20/20 `no_match`,替换 worker 为 0 |
|
||||
| R16,最初标作命中的 3 工程 | 33.424 秒 | 11.141 秒 | 实际 3/3 未命中,不能作为命中性能数据 |
|
||||
| R16,3 个双图页真实命中工程 | 595.727 秒 | 198.576 秒 | 3 个 `saved_ok`、3 个第二页预筛 `no_match`;每工程替换 20 个器件 |
|
||||
| R16,单工程状态清理回归 | 193.098 秒 | 193.098 秒 | 1 个 `saved_ok`、1 个预筛 `no_match`;无 `current-state.tsv`、无 `uncertain.flag` |
|
||||
| R16,单工程日志诊断回归 | 219.090 秒 | 219.090 秒 | 1 个 `saved_ok`、1 个预筛 `no_match`;样本本身未标注位号 |
|
||||
|
||||
因此不能把当前性能概括为“平均一个工程 1 分钟”。未命中工程约 11 秒;包含 20 个真实器件替换、保存、关闭和重新打开回读的工程约 3.2 至 3.7 分钟。若批次约四分之一工程真实命中,混合平均值才可能接近 1 分钟;实际耗时还取决于图页数、规则数、命中器件数、中央库和 DxDesigner 数据库响应。
|
||||
|
||||
R16 的未命中路径比 R15 快约 66.6%。真实命中日志显示主要耗时位于 DxDesigner 原生替换、数据库处理和保存后回读,而不是 Python 队列遍历。保存后回读是确认落盘的安全门禁,不能直接删除。
|
||||
|
||||
## 测试覆盖边界
|
||||
|
||||
- 本轮前的完整自动化回归为 `1182 passed`。最终便携目录、状态清理、监控、扫描、VBS 契约和构建相关回归为 `112 passed`;最终两个性能与状态清理专项为 `3 passed`。
|
||||
- 20 工程实机压力测试确实全部未命中;最初选取的 3 工程“命中样本”也实际未命中。之后已改用替换前备份,完成 3 工程连续真实写入和两次单工程真实写入。
|
||||
- 当前仍缺少 10 至 20 个工程连续真实命中的长时间压力测试,以及不同工程规模、不同命中数量的分层样本。现有结果能证明逻辑和未命中批量性能,不能证明所有真实生产批次都按同一平均耗时运行。
|
||||
- 32 位 WSH/ADODB 对超长控制文件路径存在传统限制。人工测试的长数据根出现授权文件不可见,短路径立即通过。正式安装目录应避免过深;后续应增加启动前路径长度诊断,而不是等待 20 秒后显示握手失败。
|
||||
|
||||
## 后续优化优先级
|
||||
|
||||
1. 同一工程同一图页有多条命中规则时,将多条规则合并为一次受控打开、替换、保存和回读。这是最大潜在收益,但需要重做事务边界、逐规则状态和恢复协议,必须先用可丢弃工程专项验证。
|
||||
2. 增加备份、枚举、原生替换、恢复、保存和回读的分阶段耗时事件,UI 按命中与未命中历史分别估算剩余时间,避免使用失真的单一平均值。
|
||||
3. 将工程备份的三次完整哈希遍历改成受控复制时同步计算摘要,并保留源目录前后变化检查,降低大工程在替换前的磁盘扫描成本。
|
||||
4. 对发布目录和控制文件做 32 位 WSH 路径长度预检,必要时提示移动到更短安装目录;不能通过静默改回 AppData 绕开用户指定的数据位置。
|
||||
|
||||
## 发布结果
|
||||
|
||||
- 候选目录:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\dist\DxPartReplace`
|
||||
- 实际测试安装目录:`F:\Sync Tool Skyworth\Work Maps\DxPartReplace-Test`
|
||||
- 版本:`2026.09.08-R16`
|
||||
- 文件数:218
|
||||
- 体积:105.55 MiB
|
||||
- EXE SHA256:`5062DE8580DBA0A244C5ABA21FFC260E292863C64F089645C3C8E9EAD14EF93E`
|
||||
- 源码与包内 `QuickPartReplace.vbs` SHA256:`B5A31D1ACED6BEFAFCEE351F9A794A4F3D0B18C66E9DD68F59E8C2383D892C04`
|
||||
- 候选包和实际安装目录冒烟均退出码 0;实际安装目录已生成并保留 EXE 旁的 `data\task-center.db` 与 `data\logs\application.log`。
|
||||
- PyInstaller 缺失模块告警均来自非 Windows 平台分支、可选 Pillow/Numpy/Xlib、兼容层内部类型或测试模块;当前包内功能与独立冒烟未发现缺失运行依赖。
|
||||
@@ -0,0 +1,40 @@
|
||||
# DxPartReplace 1.0.0 正式发布记录
|
||||
|
||||
发布日期:2026-09-08
|
||||
|
||||
## 发布范围
|
||||
|
||||
- 桌面版版本号固定为 `1.0.0`。
|
||||
- 多个已选工程按“工程 -> 图页 -> 规则”严格串行执行,不并发打开或同时修改多个工程。
|
||||
- 正式桌面界面和当前用户指南已移除试用阶段的工程副本文案。
|
||||
- 正式包包含 `DxPartReplace 1.0.0 使用说明.docx`,提供逐步截图、点击位置标注和常见报错处理。
|
||||
- 工程扫描只接收带有 DxDesigner 原理图数据库标记的 `.prj`;纯 PCB 工程及其他软件的同后缀文件不进入任务列表。
|
||||
- 项目表超过可视区域后,勾选或取消勾选会保持当前垂直和水平滚动位置及当前行。
|
||||
- 修复后台 worker 完成时窗口已销毁仍访问按钮的 Qt 生命周期竞态。
|
||||
- 数据、日志和工程备份继续写入程序目录旁的 `data`;正式包不携带本机数据。
|
||||
|
||||
## 验证结果
|
||||
|
||||
- Scanner、Service、Batch 和 UI 直接回归:`80 passed`。
|
||||
- 其余扫描调用链回归:`93 passed`。
|
||||
- 最终界面一致性回归:`13 passed`。
|
||||
- 构建前置测试:`10 passed`。
|
||||
- `compileall`:通过。
|
||||
- `pip check`:`No broken requirements found.`
|
||||
- PyInstaller 构建:通过。
|
||||
- 独立 EXE 冒烟:记录 `application_start version=1.0.0` 和 `application_clean_shutdown exit_code=0`。
|
||||
- 打包后的 `QuickPartReplace.vbs` 与源码 SHA-256 一致。
|
||||
|
||||
## 正式产物
|
||||
|
||||
- 便携目录:`F:\Sync Tool Skyworth\Work Maps\DxPartReplace`
|
||||
- 文件数:219
|
||||
- 未压缩体积:106.27 MiB
|
||||
- EXE SHA-256:`85885602EDB103530C6BD5A8784E440CDB2DCC285A8919BE31377F7889090223`
|
||||
- 使用说明 SHA-256:`0CB91973EF88F091EE65DE1A9897A1C265BC4C57952B43F44B3C895C98964BE7`
|
||||
- ZIP:`F:\Sync Tool Skyworth\Work Maps\DxPartReplace-1.0.0.zip`
|
||||
- ZIP 体积:43.14 MiB
|
||||
- ZIP SHA-256:`B92023CA88B9B7BD8FE0ADB751F872781500AFF92E6C023CB32149CCE743079A`
|
||||
- VBS SHA-256:`B5A31D1ACED6BEFAFCEE351F9A794A4F3D0B18C66E9DD68F59E8C2383D892C04`
|
||||
|
||||
ZIP 包含一个顶层 `DxPartReplace` 目录、一个 EXE、使用说明和完整运行依赖;不包含 `data`、旧测试目录、阶段构建目录或历史发布副本。
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+456
@@ -0,0 +1,456 @@
|
||||
# DxDesigner Part Replacement Trial Task Center Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Deliver a packaged Windows `DxPartReplace.exe` that manages replacement tasks, scans and selects `.prj` projects, edits Part Number mappings, guides one-project-at-a-time native replacement, compares fresh before/after probe evidence, advances verified projects to Completed, and records complete operational and crash logs.
|
||||
|
||||
**Architecture:** A PySide6 desktop shell calls a Qt-free service layer. SQLite stores mutable task drafts and project state, append-only JSONL plus rotating text logs preserve diagnostics, and a pure comparison module validates before/after probe profiles. The first release never automates or writes DxDesigner; it waits for operator-created read-only profiles and verifies them before advancing the queue.
|
||||
|
||||
**Tech Stack:** Python 3.12, PySide6 6.x, SQLite, pytest 8.x, pytest-qt 4.x, PyInstaller 6.x, JSON/JSONL, PowerShell 5.1-compatible packaging script.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-09-04-dxdesigner-part-replacement-trial-task-center-design.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Release classification remains `evaluation-only`.
|
||||
- Operate only on complete disposable project copies.
|
||||
- Match replacement rules exclusively by `Part Number`; do not impose a material-number regular expression.
|
||||
- Do not invoke `SendKeys`, UI coordinates, blind delays, automatic save, rewiring, or any DxDesigner design setter.
|
||||
- Do not bypass the production certification or compatibility-profile gates.
|
||||
- Task deletion is soft deletion and never deletes engineering files or evidence trees.
|
||||
- A project reaches `completed` only after a fresh, exact-project before/after comparison has no hard failures.
|
||||
- Application logging starts before the main window is constructed and captures uncaught main-thread and worker-thread exceptions.
|
||||
- Preserve all pre-existing dirty-worktree changes outside the files named by a task.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Task Records, SQLite CRUD, and Diagnostic Logging
|
||||
|
||||
**Files:**
|
||||
- Create: `src/dx_productivity/trial_task_center/__init__.py`
|
||||
- Create: `src/dx_productivity/trial_task_center/models.py`
|
||||
- Create: `src/dx_productivity/trial_task_center/errors.py`
|
||||
- Create: `src/dx_productivity/trial_task_center/store.py`
|
||||
- Create: `src/dx_productivity/trial_task_center/logging_setup.py`
|
||||
- Create: `tests/trial_task_center/test_store.py`
|
||||
- Create: `tests/trial_task_center/test_logging_setup.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `TaskStatus`, `ProjectStatus`, `TaskRecord`, `RuleRecord`, `ProjectRecord`, `TaskCenterError`.
|
||||
- Produces: `TaskStore(path: Path)` with task/rule/project CRUD and transactional state changes.
|
||||
- Produces: `configure_logging(root: Path) -> LoggingContext`, `install_exception_hooks(context)`, and `append_task_event(...)`.
|
||||
- Consumes: no Qt and no DxDesigner API.
|
||||
|
||||
- [ ] **Step 1: Write failing model and CRUD tests**
|
||||
|
||||
Define tests that require these exact public records and methods:
|
||||
|
||||
```python
|
||||
class TaskStatus(str, Enum):
|
||||
DRAFT = "draft"
|
||||
READY = "ready"
|
||||
RUNNING = "running"
|
||||
PAUSED = "paused"
|
||||
COMPLETED = "completed"
|
||||
FAILED = "failed"
|
||||
DELETED = "deleted"
|
||||
|
||||
class ProjectStatus(str, Enum):
|
||||
PENDING = "pending"
|
||||
CAPTURING_BEFORE = "capturing_before"
|
||||
AWAITING_OPERATOR = "awaiting_operator"
|
||||
CAPTURING_AFTER = "capturing_after"
|
||||
VERIFYING = "verifying"
|
||||
COMPLETED = "completed"
|
||||
FAILED = "failed"
|
||||
SKIPPED = "skipped"
|
||||
```
|
||||
|
||||
```python
|
||||
store = TaskStore(tmp_path / "task-center.db")
|
||||
task = store.create_task("试验任务", note="first")
|
||||
assert store.get_task(task.task_id).name == "试验任务"
|
||||
renamed = store.update_task(task.task_id, name="单项目替换", note="updated")
|
||||
assert renamed.updated_utc > task.updated_utc
|
||||
store.soft_delete_task(task.task_id)
|
||||
assert store.list_tasks(TaskStatus.DELETED)[0].task_id == task.task_id
|
||||
store.restore_task(task.task_id)
|
||||
```
|
||||
|
||||
Add tests for unique nonblank names, running-task deletion rejection, rule add/edit/delete/reorder/enable, project upsert with selection preservation, unavailable rescan records, state transitions, transaction rollback, schema reopening, and crash recovery of `capturing_*`/`verifying` to a paused task plus failed project with an interruption error.
|
||||
|
||||
- [ ] **Step 2: Run the focused tests and verify RED**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
$env:PYTHONPATH=(Resolve-Path 'src').Path
|
||||
py -3.12 -m pytest tests/trial_task_center/test_store.py -q
|
||||
```
|
||||
|
||||
Expected: collection/import failure because the package does not exist.
|
||||
|
||||
- [ ] **Step 3: Implement immutable records and stable errors**
|
||||
|
||||
Use frozen slotted dataclasses. `TaskCenterError` contains `code`, `message`, and a generated `error_id` with the format `DXT-YYYYMMDD-<8 uppercase hex characters>`. Keep user text separate from traceback detail.
|
||||
|
||||
- [ ] **Step 4: Implement SQLite schema version 1 and CRUD**
|
||||
|
||||
Create `tasks`, `rules`, `projects`, and `metadata` tables with foreign keys enabled, explicit ordered rule positions, canonical unique project paths per task, UTC ISO timestamps, and transaction-scoped writes. Public methods return records rather than SQLite rows. Provide at least:
|
||||
|
||||
```python
|
||||
create_task(name: str, note: str = "") -> TaskRecord
|
||||
get_task(task_id: str) -> TaskRecord
|
||||
list_tasks(status: TaskStatus | None = None) -> tuple[TaskRecord, ...]
|
||||
update_task(task_id: str, *, name: str, note: str) -> TaskRecord
|
||||
soft_delete_task(task_id: str) -> TaskRecord
|
||||
restore_task(task_id: str) -> TaskRecord
|
||||
add_rule(task_id: str, old_part_number: str, new_part_number: str) -> RuleRecord
|
||||
update_rule(rule_id: str, *, old_part_number: str, new_part_number: str, enabled: bool) -> RuleRecord
|
||||
delete_rule(rule_id: str) -> None
|
||||
move_rule(rule_id: str, offset: int) -> tuple[RuleRecord, ...]
|
||||
list_rules(task_id: str) -> tuple[RuleRecord, ...]
|
||||
sync_projects(task_id: str, discovery_root: Path, paths: Sequence[Path]) -> tuple[ProjectRecord, ...]
|
||||
set_project_selected(project_id: str, selected: bool) -> ProjectRecord
|
||||
set_project_status(project_id: str, status: ProjectStatus, *, error_id: str | None = None, summary: str = "") -> ProjectRecord
|
||||
list_projects(task_id: str) -> tuple[ProjectRecord, ...]
|
||||
recover_interrupted_work() -> tuple[str, ...]
|
||||
```
|
||||
|
||||
Validate the complete enabled rule set after each rule mutation by adapting `parse_mapping_bytes`; roll back a mutation that creates a duplicate source, self-map, chain, or cycle.
|
||||
|
||||
- [ ] **Step 5: Write logging tests and verify RED**
|
||||
|
||||
Tests must assert a 5 MiB rotating UTF-8 application log with five backups, structured task-event keys, flush-before-return, traceback capture, stdout/stderr capture helper behavior, and a thread exception reaching `application.log` with its error ID.
|
||||
|
||||
- [ ] **Step 6: Implement logging before UI construction**
|
||||
|
||||
`configure_logging` creates paths and handlers without importing Qt. `install_exception_hooks` installs `sys.excepthook` and `threading.excepthook`. `append_task_event` appends canonical one-line JSON using `os.fsync` and keys:
|
||||
|
||||
```text
|
||||
sequence,timestamp_utc,level,task_id,project_id,operation,
|
||||
state_before,state_after,error_id,message,details
|
||||
```
|
||||
|
||||
- [ ] **Step 7: Run focused tests**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
$env:PYTHONPATH=(Resolve-Path 'src').Path
|
||||
py -3.12 -m pytest tests/trial_task_center/test_store.py tests/trial_task_center/test_logging_setup.py -q
|
||||
```
|
||||
|
||||
Expected: all pass.
|
||||
|
||||
- [ ] **Step 8: Commit Task 1**
|
||||
|
||||
```powershell
|
||||
git add src/dx_productivity/trial_task_center tests/trial_task_center/test_store.py tests/trial_task_center/test_logging_setup.py
|
||||
git commit -m "feat: add trial task storage and diagnostics"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Project Scanning, Probe Evidence, and Replacement Comparison
|
||||
|
||||
**Files:**
|
||||
- Create: `src/dx_productivity/trial_task_center/scanner.py`
|
||||
- Create: `src/dx_productivity/trial_task_center/evidence.py`
|
||||
- Create: `src/dx_productivity/trial_task_center/comparison.py`
|
||||
- Create: `tests/trial_task_center/test_scanner.py`
|
||||
- Create: `tests/trial_task_center/test_evidence.py`
|
||||
- Create: `tests/trial_task_center/test_comparison.py`
|
||||
- Create: `tests/fixtures/trial_task_center/profile-before.json`
|
||||
- Create: `tests/fixtures/trial_task_center/profile-after-valid.json`
|
||||
- Create: `tests/fixtures/trial_task_center/profile-after-invalid.json`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `MappingRule` from `dx_productivity.part_replace.models` and project identity rules from existing input helpers.
|
||||
- Produces: `scan_projects(root: Path) -> tuple[Path, ...]`.
|
||||
- Produces: `ProbeStamp`, `CapturedProfile`, `profile_stamp`, and `capture_profile`.
|
||||
- Produces: `ComparisonIssue`, `ProjectComparison`, `compare_profiles`.
|
||||
- No Qt, SQLite, or design mutation.
|
||||
|
||||
- [ ] **Step 1: Write scanner tests and verify RED**
|
||||
|
||||
Tests cover recursive case-insensitive `.prj` discovery, canonical deterministic ordering, duplicate path identities, nonexistent/not-directory roots, inaccessible subtrees as explicit errors, and no filesystem writes.
|
||||
|
||||
- [ ] **Step 2: Implement the scanner adapter**
|
||||
|
||||
Reuse `discover_projects(root, (".prj",))`. Convert `InputError` into `TaskCenterError` without discarding its stable code. Never select newly discovered projects automatically.
|
||||
|
||||
- [ ] **Step 3: Write evidence tests and verify RED**
|
||||
|
||||
Require these signatures:
|
||||
|
||||
```python
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ProbeStamp:
|
||||
size: int
|
||||
modified_ns: int
|
||||
sha256: str
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CapturedProfile:
|
||||
source: Path
|
||||
destination: Path
|
||||
stamp: ProbeStamp
|
||||
project_identity: str
|
||||
data: Mapping[str, object]
|
||||
|
||||
def profile_stamp(path: Path) -> ProbeStamp | None: ...
|
||||
def capture_profile(source: Path, destination: Path, expected_project: Path,
|
||||
previous: ProbeStamp | None) -> CapturedProfile: ...
|
||||
```
|
||||
|
||||
Tests reject missing, unchanged, corrupt, duplicate-key, wrong-version, and wrong-project profiles. Accept only a profile whose bytes or timestamp changed and whose canonical identity matches. Assert atomic destination publication and exact SHA-256.
|
||||
|
||||
- [ ] **Step 4: Implement evidence capture**
|
||||
|
||||
Open and hash one stable byte snapshot, parse JSON with duplicate-key rejection, require `format_version == 1`, require `project.identity` string equality after Windows canonicalization, and write the accepted bytes atomically. Do not delete or rename the source menu-probe file.
|
||||
|
||||
- [ ] **Step 5: Write comparison tests and verify RED**
|
||||
|
||||
Require:
|
||||
|
||||
```python
|
||||
def compare_profiles(
|
||||
before: Mapping[str, object],
|
||||
after: Mapping[str, object],
|
||||
rules: Sequence[MappingRule],
|
||||
) -> ProjectComparison: ...
|
||||
```
|
||||
|
||||
`ProjectComparison` includes `passed`, matched logical identities per rule, warnings, hard issues, and canonical JSON serialization. Tests cover representative material numbers, no-match warnings, two rules, existing target parts, target mismatch, missing/duplicate logical identity, changed RefDes/hierarchy/unit count/origin/position/rotation/mirror/pins/nets, unrelated changes, and unsupported parameter-presentation capability warnings.
|
||||
|
||||
- [ ] **Step 6: Implement strict profile comparison**
|
||||
|
||||
Build unique maps by `logical_identity`. Match before Part Numbers with trimmed case-insensitive comparison while preserving exact display strings. For each matched identity, require the after Part Number to match the rule target and compare all trusted protected fields. Compare unrelated components after removing expected Part Number changes. Record `Part Label`, `Value`, and `parameter_probe` differences only as evidence/warnings in this release; never write them.
|
||||
|
||||
- [ ] **Step 7: Run Task 2 tests**
|
||||
|
||||
```powershell
|
||||
$env:PYTHONPATH=(Resolve-Path 'src').Path
|
||||
py -3.12 -m pytest tests/trial_task_center/test_scanner.py tests/trial_task_center/test_evidence.py tests/trial_task_center/test_comparison.py -q
|
||||
```
|
||||
|
||||
Expected: all pass.
|
||||
|
||||
- [ ] **Step 8: Commit Task 2**
|
||||
|
||||
```powershell
|
||||
git add src/dx_productivity/trial_task_center tests/trial_task_center tests/fixtures/trial_task_center
|
||||
git commit -m "feat: compare trial replacement evidence"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Trial Runner and Application Service
|
||||
|
||||
**Files:**
|
||||
- Create: `src/dx_productivity/trial_task_center/runner.py`
|
||||
- Create: `src/dx_productivity/trial_task_center/service.py`
|
||||
- Create: `tests/trial_task_center/test_runner.py`
|
||||
- Create: `tests/trial_task_center/test_service.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 1 store/logging and Task 2 scanner/evidence/comparison.
|
||||
- Produces: `OperatorInstruction`, `RunnerSnapshot`, `TrialRunner`, and `TaskCenterService`.
|
||||
- Produces synchronous methods designed to be called from a Qt worker; no Qt import.
|
||||
|
||||
- [ ] **Step 1: Write runner state-machine tests and verify RED**
|
||||
|
||||
Require the exact action methods:
|
||||
|
||||
```python
|
||||
start_task(task_id: str, *, disposable_copy_confirmed: bool) -> RunnerSnapshot
|
||||
capture_before(task_id: str, project_id: str, probe_path: Path) -> RunnerSnapshot
|
||||
confirm_native_attempt(task_id: str, project_id: str) -> RunnerSnapshot
|
||||
capture_after(task_id: str, project_id: str, probe_path: Path) -> RunnerSnapshot
|
||||
pause_task(task_id: str) -> RunnerSnapshot
|
||||
resume_task(task_id: str) -> RunnerSnapshot
|
||||
retry_project(task_id: str, project_id: str) -> RunnerSnapshot
|
||||
skip_project(task_id: str, project_id: str) -> RunnerSnapshot
|
||||
snapshot(task_id: str) -> RunnerSnapshot
|
||||
```
|
||||
|
||||
Tests cover start gates, exact first selected project, before capture, operator instructions containing project and every matching old/new rule, after capture, verifying transition, passed project completion, automatic next-project selection, task completion, hard comparison failure, pause-before-next behavior, resume, retry with new attempt evidence paths, skip, and process-restart recovery.
|
||||
|
||||
- [ ] **Step 2: Implement the runner**
|
||||
|
||||
The runner writes a task event before and after every durable state change. It uses per-attempt evidence directories and never overwrites prior profiles. `confirm_native_attempt` records an operator assertion but cannot mark success. `capture_after` is the only route to comparison and project completion.
|
||||
|
||||
- [ ] **Step 3: Write service tests and verify RED**
|
||||
|
||||
Test task CRUD delegation, directory scan preserving prior selection, project select-all/clear, rule validation errors, current instruction, log tailing, and opening evidence paths without actually launching Explorer in tests.
|
||||
|
||||
- [ ] **Step 4: Implement `TaskCenterService`**
|
||||
|
||||
The service is the only interface the UI uses. It converts domain exceptions into `TaskCenterError`, logs every operation, and exposes tuple snapshots safe for worker-to-UI transfer. Inject path opener and clock dependencies for tests.
|
||||
|
||||
- [ ] **Step 5: Run Tasks 1-3 tests and existing input/profile tests**
|
||||
|
||||
```powershell
|
||||
$env:PYTHONPATH=(Resolve-Path 'src').Path
|
||||
py -3.12 -m pytest tests/trial_task_center tests/part_replace/test_inputs.py tests/integration/test_part_replace_probe.py -q
|
||||
```
|
||||
|
||||
Expected: all pass.
|
||||
|
||||
- [ ] **Step 6: Commit Task 3**
|
||||
|
||||
```powershell
|
||||
git add src/dx_productivity/trial_task_center/runner.py src/dx_productivity/trial_task_center/service.py tests/trial_task_center
|
||||
git commit -m "feat: orchestrate trial replacement tasks"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: PySide6 Task Center UI
|
||||
|
||||
**Files:**
|
||||
- Modify: `pyproject.toml`
|
||||
- Create: `src/dx_productivity/trial_task_center/ui/__init__.py`
|
||||
- Create: `src/dx_productivity/trial_task_center/ui/styles.py`
|
||||
- Create: `src/dx_productivity/trial_task_center/ui/workers.py`
|
||||
- Create: `src/dx_productivity/trial_task_center/ui/task_list.py`
|
||||
- Create: `src/dx_productivity/trial_task_center/ui/project_table.py`
|
||||
- Create: `src/dx_productivity/trial_task_center/ui/mapping_table.py`
|
||||
- Create: `src/dx_productivity/trial_task_center/ui/run_panel.py`
|
||||
- Create: `src/dx_productivity/trial_task_center/ui/main_window.py`
|
||||
- Create: `tests/ui/test_trial_task_center_window.py`
|
||||
- Create: `tests/ui/test_trial_task_center_workflow.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `TaskCenterService` only; widgets do not import SQLite, profile JSON, or DxDesigner modules.
|
||||
- Produces: `TrialTaskCenterWindow(service: TaskCenterService)`.
|
||||
- All filesystem scans and evidence operations execute through `QThreadPool`; no UI-thread blocking.
|
||||
|
||||
- [ ] **Step 1: Add runtime and development dependencies**
|
||||
|
||||
Set project dependencies and extras without loosening Python 3.12:
|
||||
|
||||
```toml
|
||||
dependencies = ["PySide6>=6.7,<7"]
|
||||
dev = [
|
||||
"pytest>=8,<9", "pytest-cov>=5,<7", "coverage>=7,<8",
|
||||
"build>=1.2,<2", "pytest-qt>=4.4,<5", "PyInstaller>=6.10,<7"
|
||||
]
|
||||
```
|
||||
|
||||
Add script:
|
||||
|
||||
```toml
|
||||
dx-part-replace-gui = "dx_productivity.trial_task_center.application:main"
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Write shell and CRUD interaction tests and verify RED**
|
||||
|
||||
With `QT_QPA_PLATFORM=offscreen`, assert minimum size 1100x700, Active/Completed/Deleted task filters, task create/edit/delete/restore, native directory-picker injection, scan button busy state, project Select All/Clear, mapping add/edit/delete/reorder, disabled Start gates, and stable object names for UI automation.
|
||||
|
||||
- [ ] **Step 3: Implement restrained styles and reusable async workers**
|
||||
|
||||
Use semantic colors for canvas, surface, border, primary/secondary text, accent, success, warning, danger, and focus. Use 6 px or smaller control radii, 13 px default text, fixed 30-34 px command heights, native/Qt standard icons where available, and tooltips for icon-only actions. Do not use gradients, decorative cards, animation, or viewport-scaled fonts.
|
||||
|
||||
`workers.py` wraps callables in `QRunnable` and emits success/error/finished signals. Every error reaches logging and restores disabled controls.
|
||||
|
||||
- [ ] **Step 4: Implement task navigation and workspace tables**
|
||||
|
||||
The left pane is a task list, not cards. The main pane uses a directory toolbar, `QTableView` project model, mapping table, operator instruction band, action toolbar, and read-only log dock. Use stable column widths plus stretch for paths so text does not overlap. Completed projects disappear from the Pending filter and remain visible through All/Completed.
|
||||
|
||||
- [ ] **Step 5: Implement dialogs and run actions**
|
||||
|
||||
Task and rule edits use focused modal dialogs with validation messages. Start requires a disposable-copy confirmation dialog naming the selected project count. Capture Before/After shows the expected menu-probe path and calls the service in a worker. Errors show Chinese summary plus stable error ID and buttons to open log/evidence locations.
|
||||
|
||||
- [ ] **Step 6: Run UI tests**
|
||||
|
||||
```powershell
|
||||
$env:PYTHONPATH=(Resolve-Path 'src').Path
|
||||
$env:QT_QPA_PLATFORM='offscreen'
|
||||
py -3.12 -m pytest tests/ui/test_trial_task_center_window.py tests/ui/test_trial_task_center_workflow.py -q
|
||||
```
|
||||
|
||||
Expected: all pass without Qt warnings or worker leaks.
|
||||
|
||||
- [ ] **Step 7: Capture visual QA screenshots**
|
||||
|
||||
Render populated Active and Completed states at 1100x700 and 1440x900 into `.superpowers/visual-qa/trial-task-center/`. Inspect for clipping, overlapping controls, unreadable paths, broken icons, hidden required actions, and one-note color use. Iterate until all four images pass.
|
||||
|
||||
- [ ] **Step 8: Commit Task 4**
|
||||
|
||||
```powershell
|
||||
git add pyproject.toml src/dx_productivity/trial_task_center/ui tests/ui
|
||||
git commit -m "feat: add replacement task center UI"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Application Bootstrap, PyInstaller EXE, and Trial Guide
|
||||
|
||||
**Files:**
|
||||
- Create: `src/dx_productivity/trial_task_center/application.py`
|
||||
- Create: `packaging/DxPartReplace.spec`
|
||||
- Create: `packaging/Build-DxPartReplace.ps1`
|
||||
- Create: `tests/trial_task_center/test_application.py`
|
||||
- Create: `tests/packaging/test_dx_part_replace_build.py`
|
||||
- Create: `docs/user/trial-task-center.md`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: logging, store, service, and `TrialTaskCenterWindow`.
|
||||
- Produces: `main(argv: Sequence[str] | None = None) -> int` and `dist/DxPartReplace/DxPartReplace.exe`.
|
||||
- Supports `DX_TASK_CENTER_HOME` only as an explicit test/deployment override; default is `%LOCALAPPDATA%\DxProductivity\trial-task-center`.
|
||||
|
||||
- [ ] **Step 1: Write bootstrap tests and verify RED**
|
||||
|
||||
Tests assert logging is configured before constructing `QApplication`, interrupted work recovery is logged, a second-instance database open remains safe, `--smoke-test` opens and closes through a zero-delay Qt timer, and fatal startup exceptions write a traceback and return a nonzero exit code.
|
||||
|
||||
- [ ] **Step 2: Implement application bootstrap**
|
||||
|
||||
Parse only `--smoke-test` and `--data-root`. Resolve application paths, configure logging and exception hooks, recover interrupted records, construct store/service/window, and run Qt. Log process version, executable, OS, data root, database, and log paths before window construction.
|
||||
|
||||
- [ ] **Step 3: Write the packaging spec and build script**
|
||||
|
||||
The spec names the executable `DxPartReplace`, uses windowed mode, collects PySide6 plugins, and bundles no user task database or live evidence. `Build-DxPartReplace.ps1` resolves the repository root, runs focused tests, removes only the explicit repository-local `build\DxPartReplace` and `dist\DxPartReplace` targets after verifying their resolved paths, invokes PyInstaller, and prints the absolute EXE and log locations.
|
||||
|
||||
- [ ] **Step 4: Add packaging smoke tests**
|
||||
|
||||
Static tests validate spec/script paths and safety guards. The built-artifact smoke test launches:
|
||||
|
||||
```powershell
|
||||
$env:DX_TASK_CENTER_HOME=<temporary absolute directory>
|
||||
dist\DxPartReplace\DxPartReplace.exe --smoke-test
|
||||
```
|
||||
|
||||
Assert exit code 0, `logs\application.log` exists and contains startup and clean shutdown, and no files are written outside the temporary data root except normal OS/Qt runtime activity.
|
||||
|
||||
- [ ] **Step 5: Write the Chinese trial guide**
|
||||
|
||||
Document EXE launch, data/log paths, creating one task, scanning/selecting one disposable `.prj`, adding `4300-CA2260-A300`-style mappings, Capture Before, the exact manual DxDesigner Find/Replace Part/Library Wins steps, Capture After, Completed/Failed behavior, retry, and which files to return for diagnosis. State clearly that no automatic `Value`/style write or save occurs.
|
||||
|
||||
- [ ] **Step 6: Run the complete test suite**
|
||||
|
||||
```powershell
|
||||
$env:PYTHONPATH=(Resolve-Path 'src').Path
|
||||
$env:QT_QPA_PLATFORM='offscreen'
|
||||
py -3.12 -m pytest -q
|
||||
```
|
||||
|
||||
Expected: all tests pass.
|
||||
|
||||
- [ ] **Step 7: Build and smoke-test the EXE**
|
||||
|
||||
```powershell
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File packaging\Build-DxPartReplace.ps1
|
||||
```
|
||||
|
||||
Expected: exit code 0 and a working `dist\DxPartReplace\DxPartReplace.exe`.
|
||||
|
||||
- [ ] **Step 8: Perform final review and commit**
|
||||
|
||||
Review the full diff against the spec, resolve all blocking findings, then:
|
||||
|
||||
```powershell
|
||||
git add src/dx_productivity/trial_task_center packaging tests docs/user/trial-task-center.md pyproject.toml
|
||||
git commit -m "build: package replacement trial task center"
|
||||
```
|
||||
@@ -0,0 +1,11 @@
|
||||
# Value options and serial execution implementation
|
||||
|
||||
Approved semantics: unchecked preserves the native target Value without creating a missing attribute; checked copies the verified target Part Number into Value. Existing Value display styling is inherited in both modes. Old in-flight queues must not silently adopt a different policy.
|
||||
|
||||
Work only in the isolated candidate. Do not commit, rebuild, attach to CAD, or write to the concurrently edited original project.
|
||||
|
||||
1. Add failing tests for default-off task settings, SQLite persistence, explicit queue policy, and rejection of a different completed job. Implement models/store/service and quick_run, using a versioned value_mode column and a pinned job argument.
|
||||
2. Add real VBS routine tests with fake components: preserve content and style, missing Value remains missing, checked content plus style, bad readback, and changed policy on resume. Implement metadata policy binding, restoration and final verification. Native snapshot parsing accepts validated new metadata while retaining read-only legacy parsing.
|
||||
3. Wire a task-scoped checkbox and confirmation text. Freeze settings once a queue has evidence. Keep one worker/one queue item and require the expected job before writing and on receipt; do not add automatic open/save/close.
|
||||
4. Add mouse-drag, settings persistence, and checkbox UI tests. Widen splitter handles, make logs collapsible, reduce table minima, persist layout/header state to the task-center data root, and add layout reset.
|
||||
5. Run targeted tests, then UI/task-center/integration regression suites using external temp paths and no bytecode/cache. Create a unified patch and a baseline hash manifest for review, not an automatic overwrite script. Document remaining real CAD acceptance and concurrent merge boundaries.
|
||||
@@ -0,0 +1,525 @@
|
||||
# DxDesigner 7.9.5 Multi-Project Part Replacement Tool
|
||||
|
||||
Date: 2026-09-01
|
||||
|
||||
## 1. Purpose
|
||||
|
||||
Build the part-replacement module of the Dx Productivity suite for
|
||||
DxDesigner/Expedition Enterprise 7.9.5. The module applies one set of
|
||||
old-Part-Number to new-Part-Number rules across an explicit list of projects,
|
||||
uses the native Replace Part workflow to obtain all new part data from the
|
||||
central library, and verifies every changed project before it can be saved.
|
||||
|
||||
This is a true library part replacement. It is not a Part Number property edit,
|
||||
an attribute annotation workflow, an ASCII design-file rewrite, or automatic
|
||||
schematic rewiring.
|
||||
|
||||
Version 1 is intentionally semi-automatic. The tool prepares each replacement
|
||||
group and verifies it, while an operator confirms the native Replace Part dialog
|
||||
once for every project/mapping pair that has matches and confirms each project
|
||||
once before save.
|
||||
|
||||
## 2. Compatibility Baseline
|
||||
|
||||
DxDesigner/Expedition Enterprise 7.9.5 is the only supported schematic
|
||||
integration baseline. Compatibility with newer Siemens releases is not implied.
|
||||
|
||||
The module reuses the architecture approved for the Dx Productivity suite:
|
||||
|
||||
- one startup-imported `MenuAdd.vbs` entry point;
|
||||
- all DxDesigner API access inside the internal VBScript host;
|
||||
- UTF-8 snapshot, command, result, and status files between VBScript and Python;
|
||||
- Python 3.12 for orchestration, validation, state, and reports;
|
||||
- user-level path resolution through `DXTOOLS_HOME`;
|
||||
- ASCII-only VBScript source; and
|
||||
- preview, backup, stale-state checks, post-change verification, and recovery.
|
||||
|
||||
Python must not instantiate or attach to `ViewDraw.Application`. UI-coordinate
|
||||
automation, `SendKeys`, and blind timing delays are prohibited.
|
||||
|
||||
The current repository contains the approved suite design but not an implemented
|
||||
shared runtime. This module therefore creates only the minimum shared bridge and
|
||||
run-storage foundations it needs. It does not implement the automatic reference
|
||||
designator UI or other planned productivity modules.
|
||||
|
||||
## 3. Evidence and Route Choice
|
||||
|
||||
DxDesigner 7.9.x exposes the native `Edit -> Replace Symbol` workflow with
|
||||
`Replace part`, a target selected through DxDataBook, and a library-precedence
|
||||
choice. Community examples also show the automation method
|
||||
`Block.ChangeComponentPreserveRefdes` and the command-line operation
|
||||
`ccomp :component_name`.
|
||||
|
||||
The public evidence does not establish that either scripted operation is
|
||||
equivalent to native Replace Part with Library Wins. Users have reported symbol
|
||||
origin problems and Packager failures with `ChangeComponentPreserveRefdes`, and
|
||||
a Siemens employee recommended `ccomp` as a manual workaround for that class of
|
||||
failure. Therefore:
|
||||
|
||||
- native Replace Part with Library Wins is the version-1 production write path;
|
||||
- `ccomp` is a compatibility-probe candidate for a later automation level;
|
||||
- `ChangeComponentPreserveRefdes` is not a production write path in version 1;
|
||||
- Databook annotation may help locate parts but is not a replacement mechanism;
|
||||
and
|
||||
- exported design files are never edited directly.
|
||||
|
||||
Research references:
|
||||
|
||||
- <https://community.sw.siemens.com/s/question/0D5Vb00001Tb2wMKAR/how-to-implement-part-replace-by-script-in-dxdesigner>
|
||||
- <https://community.sw.siemens.com/s/question/0D5Vb00000ojyRYKAY/i-want-to-rearrange-the-selected-symbol-in-its-original-position-while-retaining-the-old-refdes-however-using-the-method-of-blockchangecomponentpreserverefdes-the-package-fails>
|
||||
|
||||
No maintained, downloadable open-source tool implementing this full 7.9.5
|
||||
workflow was found during the design research. A live target-system probe remains
|
||||
mandatory because community examples do not define a stable automation contract.
|
||||
|
||||
## 4. Version-1 Scope
|
||||
|
||||
### 4.1 Included
|
||||
|
||||
- Import a UTF-8 CSV mapping containing old and new Part Numbers.
|
||||
- Import an explicit project list and optionally discover candidate projects
|
||||
beneath a selected root using the extension allowlist in the verified 7.9.5
|
||||
compatibility profile.
|
||||
- Inventory every selected project before any project is modified.
|
||||
- Show a project-by-mapping impact matrix and blocking issues.
|
||||
- Apply the same enabled mapping set to every enabled project.
|
||||
- Replace all matching logical components in a multi-project job.
|
||||
- Support full-project, current-sheet, and selected-component scope for a
|
||||
single-project job. Multi-project jobs use full-project scope only.
|
||||
- Obtain the target part, symbol, pins, and library-controlled properties from
|
||||
the central library through native Replace Part with Library Wins.
|
||||
- Preserve and verify protected instance state.
|
||||
- Back up, verify, save, report, resume, and recover at project granularity.
|
||||
- Produce versioned JSON data plus operator-oriented CSV and static HTML reports.
|
||||
|
||||
### 4.2 Excluded
|
||||
|
||||
- Automatic rerouting or creation of schematic wires.
|
||||
- Automatic acceptance of pin-count, pin-number, gate, origin, or pin-coordinate
|
||||
incompatibility.
|
||||
- Fully unattended dialog control.
|
||||
- Direct SQL or file-level mutation of the central library.
|
||||
- Inferring a target part from description, value, manufacturer, or AI output.
|
||||
- Replacing a part by independently copying individual properties.
|
||||
- Automatic correction of Packager, ERC, or netlist errors.
|
||||
- AI approval of a save operation.
|
||||
- A full PySide graphical application.
|
||||
|
||||
## 5. Inputs and Identity Rules
|
||||
|
||||
### 5.1 Replacement Mapping
|
||||
|
||||
The input file has exactly these required columns:
|
||||
|
||||
```csv
|
||||
old_part_number,new_part_number
|
||||
OLD-001,NEW-001
|
||||
OLD-002,NEW-002
|
||||
```
|
||||
|
||||
Part Number is the unique central-library key supplied by the user. The tool
|
||||
trims surrounding whitespace, preserves the displayed spelling, and performs
|
||||
case-insensitive identity comparisons. It rejects:
|
||||
|
||||
- blank old or new values;
|
||||
- duplicate old values, including case-only duplicates;
|
||||
- a rule whose old and new values are equal;
|
||||
- chains such as `A -> B` and `B -> C`; and
|
||||
- cycles such as `A -> B` and `B -> A`.
|
||||
|
||||
Rejecting chains and cycles prevents a newly replaced part from becoming input
|
||||
to a later rule in the same job. Version 1 does not accept component names,
|
||||
symbol names, attributes, or pin data in the replacement mapping. Those values
|
||||
come from the project and the central library.
|
||||
|
||||
### 5.2 Project List
|
||||
|
||||
`projects.txt` contains one absolute project-definition path per line. Paths are
|
||||
canonicalized without changing their on-disk case. Duplicate paths, missing
|
||||
paths, nested duplicate discoveries, and unsupported project markers are
|
||||
reported before inventory.
|
||||
|
||||
Root discovery is a convenience that produces a candidate `projects.txt`; it
|
||||
does not silently add projects to a job. The operator reviews and confirms the
|
||||
discovered list before inventory.
|
||||
|
||||
Each project receives a stable job-local ID derived from its canonical path and
|
||||
an explicit display name. Reports never rely on a short project name as a unique
|
||||
identifier.
|
||||
|
||||
## 6. Architecture
|
||||
|
||||
### 6.1 Batch Controller
|
||||
|
||||
The Python batch controller owns immutable job configuration, project queue
|
||||
state, mapping validation, snapshot comparison, compatibility certifications,
|
||||
status transitions, and report generation. It communicates only through the
|
||||
versioned file protocol and never calls DxDesigner COM.
|
||||
|
||||
The first release exposes a command-line interface and a PowerShell launcher.
|
||||
It may use standard file/folder pickers for input selection, but the underlying
|
||||
job is fully reproducible from mapping, project-list, and job-directory paths.
|
||||
|
||||
### 6.2 Internal VBScript Bridge
|
||||
|
||||
The bridge runs inside the active DxDesigner 7.9.5 process. It owns:
|
||||
|
||||
- active-project identity and dirty-state checks;
|
||||
- component enumeration and snapshot export;
|
||||
- logical-component selection;
|
||||
- the verified route for opening native Replace Part when available;
|
||||
- monitoring for completion by observing design state rather than window text;
|
||||
- Undo, save, close, and project-open operations only when separately verified;
|
||||
and
|
||||
- result and diagnostic publication back to the job directory.
|
||||
|
||||
The bridge never interprets replacement policy. It executes explicit commands
|
||||
whose expected current state is included in the command file.
|
||||
|
||||
### 6.3 Native Replace Part Adapter
|
||||
|
||||
For each enabled mapping with matches, the adapter selects every matching
|
||||
logical component in the approved scope and displays the exact target Part
|
||||
Number and expected instance count.
|
||||
|
||||
If the compatibility probe proves a stable internal route, the bridge opens the
|
||||
native Replace Part dialog. Otherwise it pauses after selection and instructs
|
||||
the operator to invoke `Edit -> Replace Symbol`, choose `Replace part`, locate
|
||||
the exact new Part Number through DxDataBook, and select Library Wins. This
|
||||
manual-menu fallback is a supported version-1 route.
|
||||
|
||||
The tool does not automate target selection inside the dialog. When the dialog
|
||||
closes, the bridge exports a new snapshot; Python determines whether the correct
|
||||
target and count were applied.
|
||||
|
||||
### 6.4 Project Navigation Adapter
|
||||
|
||||
If the probe proves reliable project open/close APIs or commands, the bridge may
|
||||
advance the queue automatically. Otherwise the baseline route displays the
|
||||
canonical path of the next project and waits for the operator to open it.
|
||||
|
||||
In both routes, processing starts only after the active-project identity exactly
|
||||
matches the queued project. Automatic project navigation is an optimization,
|
||||
not a release requirement.
|
||||
|
||||
### 6.5 Run Store and Reports
|
||||
|
||||
Every batch receives a new run directory under the configured user-local run
|
||||
root. It contains:
|
||||
|
||||
- an immutable copy of the accepted mapping and project list;
|
||||
- `job.json` with schema version and configuration;
|
||||
- per-project inventory and before/after snapshots;
|
||||
- atomic command, result, and status mailboxes;
|
||||
- backup manifests and content hashes;
|
||||
- an append-only event log;
|
||||
- a project-by-mapping impact CSV;
|
||||
- detailed component and attribute difference CSV/JSON; and
|
||||
- a static local HTML summary with no executable remote content.
|
||||
|
||||
Files use UTF-8 and atomic same-directory publication. VBScript uses
|
||||
`ADODB.Stream` for encoding and never assumes an ANSI code page.
|
||||
|
||||
## 7. Inventory Phase
|
||||
|
||||
Inventory is a separate, read-only pass over all enabled projects. No Apply
|
||||
action is available until every enabled project is inventoried or explicitly
|
||||
excluded.
|
||||
|
||||
For each project, the bridge requires a saved, non-dirty active design and
|
||||
exports:
|
||||
|
||||
- canonical project identity and design hierarchy;
|
||||
- logical-component identity and every placed unit;
|
||||
- Part Number and RefDes;
|
||||
- sheet path, symbol identity, gate/slot identity;
|
||||
- origin, position, rotation, and mirror state;
|
||||
- visible and hidden instance attributes;
|
||||
- pin numbers, pin names, pin positions, and pin-to-net identity; and
|
||||
- a hashable project-state fingerprint.
|
||||
|
||||
The exact API names are supplied by the compatibility profile produced by the
|
||||
probe. If the bridge cannot obtain unambiguous logical-component identity,
|
||||
protected placement state, or pin/network state, that component is blocking and
|
||||
cannot be replaced.
|
||||
|
||||
The batch controller then produces the complete impact matrix. Each cell records
|
||||
the number of logical components and placed units matching a rule. It separately
|
||||
reports no-match rules, stale or missing Part Numbers, duplicate RefDes values,
|
||||
multi-unit parts, and data that cannot be verified.
|
||||
|
||||
## 8. Compatibility Certification
|
||||
|
||||
Automatic eligibility is limited to old/new pairs that have been certified as
|
||||
interface compatible against the current central-library state.
|
||||
|
||||
Because the 7.9.5 public automation interface may not expose complete target
|
||||
library geometry before placement, the baseline certification route is a trial
|
||||
replacement in a disposable full project copy:
|
||||
|
||||
1. Copy a representative closed project containing the old part.
|
||||
2. Record its complete pre-change snapshot.
|
||||
3. Perform one native Replace Part operation with Library Wins.
|
||||
4. Record the post-change snapshot.
|
||||
5. Verify the compatibility invariants in Section 10.
|
||||
6. Run Packager and the available ERC/netlist checks.
|
||||
7. Store a certification keyed by old Part Number, new Part Number, target
|
||||
library identity/revision when exposed, and observed interface fingerprint.
|
||||
|
||||
If no stable library revision is exposed, the certification records the target
|
||||
part fingerprint observed during the trial. Every production replacement must
|
||||
match that fingerprint. A changed fingerprint invalidates the certification and
|
||||
requires another trial.
|
||||
|
||||
An uncertified pair is never silently treated as compatible. The operator may
|
||||
run the disposable certification flow or exclude the mapping; there is no
|
||||
"continue anyway" override in version 1.
|
||||
|
||||
## 9. Apply Workflow
|
||||
|
||||
The production workflow for one project is:
|
||||
|
||||
1. Require the project to be saved and closed before backup.
|
||||
2. Copy the complete project tree to the run backup area and create a file-size
|
||||
and content-hash manifest.
|
||||
3. Open or ask the operator to open the queued project.
|
||||
4. Verify canonical identity and compare the current fingerprint with inventory.
|
||||
5. Re-inventory and require review if the project is stale.
|
||||
6. For each enabled mapping with matches, select the exact baseline objects and
|
||||
show the target Part Number and expected count.
|
||||
7. Open or ask the operator to open native Replace Part.
|
||||
8. The operator chooses the exact new Part Number and Library Wins, then confirms
|
||||
once for the selected group.
|
||||
9. Export the post-operation snapshot and run immediate verification.
|
||||
10. Continue only after the mapping is verified.
|
||||
11. After all mappings pass, present the complete project difference summary.
|
||||
12. Save only after the operator selects `Save and continue`.
|
||||
13. Re-open or re-enumerate the saved project, verify the persisted result, and
|
||||
mark the project complete before advancing the queue.
|
||||
|
||||
No individual component requires confirmation. The manual workload is one
|
||||
native confirmation per project/mapping pair that has at least one match, plus
|
||||
one project-level save confirmation.
|
||||
|
||||
## 10. Verification Rules
|
||||
|
||||
### 10.1 Hard Success Conditions
|
||||
|
||||
For every replaced logical component:
|
||||
|
||||
- the resulting Part Number equals the requested new Part Number;
|
||||
- the number of matched and replaced logical components is exact;
|
||||
- RefDes is unchanged;
|
||||
- sheet and hierarchical ownership are unchanged;
|
||||
- every placed unit remains present;
|
||||
- origin, position, rotation, and mirror state are unchanged;
|
||||
- gate/slot structure and pin-number set are unchanged;
|
||||
- every pin position is unchanged in schematic coordinates;
|
||||
- every `RefDes + pin number` resolves to the same net identity; and
|
||||
- no unrelated logical component changed.
|
||||
|
||||
Comparison uses invariant numeric serialization and probe-established coordinate
|
||||
tolerance. The tolerance accounts only for API serialization precision; it must
|
||||
not conceal a visible or grid-significant movement.
|
||||
|
||||
Any added, removed, renamed, or reconnected pin is a failure. The tool never
|
||||
creates, deletes, moves, or redraws wires to make a replacement pass.
|
||||
|
||||
### 10.2 Library and Attribute Semantics
|
||||
|
||||
The target symbol, part definition, pins, and library-controlled properties must
|
||||
come from native Replace Part with Library Wins. Version 1 does not independently
|
||||
write those fields.
|
||||
|
||||
Protected instance fields include RefDes, hierarchy, placement, rotation,
|
||||
mirroring, unit assignment, and connectivity. A change to a protected field is
|
||||
blocking.
|
||||
|
||||
All other attribute changes are recorded in the difference report. The live
|
||||
probe documents how the site's 7.9.5 build and central library treat custom
|
||||
instance attributes. Conflicting library-controlled attributes follow native
|
||||
Library Wins behavior; the tool neither reconstructs old values nor overrides
|
||||
the native result. The operator reviews these non-protected differences at the
|
||||
project save gate.
|
||||
|
||||
### 10.3 Project-Level Checks
|
||||
|
||||
After component checks pass, the release workflow requires:
|
||||
|
||||
- Packager produces no new error attributable to the replacement;
|
||||
- ERC produces no new relevant error;
|
||||
- generated net connectivity is unchanged for protected pins; and
|
||||
- the saved-project re-read matches the verified in-memory result.
|
||||
|
||||
When Packager, ERC, or netlist execution cannot be automated through a verified
|
||||
7.9.5 route, the tool emits exact pending checks and keeps the project in
|
||||
`awaiting_external_checks` rather than marking it complete.
|
||||
|
||||
## 11. Failure Handling and Recovery
|
||||
|
||||
### 11.1 State Machine
|
||||
|
||||
Each project moves through these durable states:
|
||||
|
||||
- `inventory_pending`
|
||||
- `inventory_complete`
|
||||
- `apply_pending`
|
||||
- `applying`
|
||||
- `awaiting_save_confirmation`
|
||||
- `awaiting_external_checks`
|
||||
- `verified_saved`
|
||||
- `blocked`
|
||||
|
||||
Transitions are append-only events. A status file is a projection of the event
|
||||
log, not the sole record of progress.
|
||||
|
||||
### 11.2 Wrong Target or Verification Failure
|
||||
|
||||
If the operator chooses the wrong target or any hard invariant fails, the bridge
|
||||
stops the current project immediately. It attempts one native Undo only through
|
||||
the verified route and then compares the complete restored snapshot with the
|
||||
pre-operation snapshot.
|
||||
|
||||
If Undo is unavailable or restoration does not verify exactly, the project must
|
||||
be closed without saving. The tool then verifies that the on-disk files still
|
||||
match the pre-apply fingerprint. It does not continue using uncertain in-memory
|
||||
state.
|
||||
|
||||
### 11.3 Backup Restore
|
||||
|
||||
Restore is explicit and project-granular. The target project must be closed, the
|
||||
canonical target path must match the job record, and the backup manifest must
|
||||
verify before any restore begins. The restore process first preserves the failed
|
||||
on-disk tree in a recovery location, then copies the verified backup. It never
|
||||
overwrites an open project or an unrelated directory.
|
||||
|
||||
### 11.4 Interruption and Resume
|
||||
|
||||
After cancellation, process failure, application crash, or reboot, the
|
||||
controller resumes only from durable states. `verified_saved` projects are not
|
||||
reprocessed. A project left in `applying`, `awaiting_save_confirmation`, or an
|
||||
unknown state is re-inventoried and reconciled against its backup before any
|
||||
further action.
|
||||
|
||||
One blocked project does not prevent the operator from continuing with other
|
||||
projects. The final report preserves all blocked reasons and never represents a
|
||||
partially completed batch as fully successful.
|
||||
|
||||
## 12. Operator Experience
|
||||
|
||||
The command-line flow uses concise numbered prompts and writes richer detail to
|
||||
the HTML report. At all times it shows:
|
||||
|
||||
- current job and project;
|
||||
- project position in the queue;
|
||||
- current old and new Part Numbers;
|
||||
- expected component count;
|
||||
- whether native-dialog and project-navigation routes are automatic or manual;
|
||||
- current verification state; and
|
||||
- the next permitted action.
|
||||
|
||||
The target Part Number remains visible while the native dialog is open. Cancel
|
||||
before a verified save leaves the current project unsaved and records the job as
|
||||
interrupted.
|
||||
|
||||
## 13. AI Review Boundary
|
||||
|
||||
The JSON schemas are versioned so a future AI agent or independent review tool
|
||||
can consume inventory, before/after differences, Packager/ERC results, and
|
||||
operator decisions.
|
||||
|
||||
AI review is advisory. It writes a separate review artifact and cannot alter
|
||||
the source snapshots, event log, hard verification result, save permission, or
|
||||
backup. No AI recommendation can approve changed connectivity or an uncertified
|
||||
part pair.
|
||||
|
||||
## 14. Compatibility Probe
|
||||
|
||||
Implementation begins with a read-mostly probe on a disposable project. The
|
||||
probe records the exact 7.9.5 build and establishes one explicit route or the
|
||||
documented manual fallback for:
|
||||
|
||||
- application version and active-project identity;
|
||||
- full-design logical-component enumeration;
|
||||
- Part Number, RefDes, hierarchy, unit, symbol, placement, attribute, pin, and
|
||||
net access;
|
||||
- selecting an exact set of logical components;
|
||||
- opening native Replace Part;
|
||||
- detecting that the dialog operation completed;
|
||||
- native Undo and save;
|
||||
- dirty-state detection;
|
||||
- project open and close; and
|
||||
- Packager, ERC, and netlist invocation or result capture.
|
||||
|
||||
Probe output is a machine-readable compatibility profile plus a human-readable
|
||||
report. A missing optional automation route selects its manual fallback. Missing
|
||||
unambiguous identity, snapshot, selection, or post-change verification routes is
|
||||
a release blocker because those capabilities have no safe fallback.
|
||||
|
||||
## 15. Testing Strategy
|
||||
|
||||
### 15.1 Python Tests
|
||||
|
||||
Unit tests cover:
|
||||
|
||||
- UTF-8 CSV parsing and path handling, including spaces and Chinese characters;
|
||||
- duplicate, equal, chained, and cyclic mappings;
|
||||
- project discovery confirmation and canonical identity;
|
||||
- impact-matrix counts;
|
||||
- immutable snapshots and schema versioning;
|
||||
- coordinate, attribute, pin, and network comparison;
|
||||
- certification creation and invalidation;
|
||||
- stale-state rejection;
|
||||
- every valid and invalid state transition;
|
||||
- interruption reconciliation and resume; and
|
||||
- report generation from complete and partial batches.
|
||||
|
||||
### 15.2 Bridge and Integration Tests
|
||||
|
||||
VBScript helper tests run under `cscript`. Static tests prohibit direct Python
|
||||
COM attachment, fixed drive paths, operation-wide error suppression, ANSI file
|
||||
exchange, `SendKeys`, and write operations before backup and stale-state checks.
|
||||
|
||||
A mocked DxDesigner bridge exercises inventory, group selection, correct target,
|
||||
wrong target, changed RefDes, changed placement, pin-count change, pin-position
|
||||
change, net change, unrelated-object change, Undo success, Undo failure, save,
|
||||
crash, and resume.
|
||||
|
||||
### 15.3 Live 7.9.5 Acceptance
|
||||
|
||||
Release acceptance uses a disposable copy of representative site projects and
|
||||
at least:
|
||||
|
||||
- one compatible single-unit replacement;
|
||||
- one compatible multi-unit replacement if multi-unit parts are in site scope;
|
||||
- one different-origin replacement that must be rejected unless coordinates are
|
||||
demonstrably unchanged;
|
||||
- one pin-number or pin-count mismatch that must be blocked;
|
||||
- one deliberately wrong target selection;
|
||||
- one stale project changed after inventory;
|
||||
- one successful Undo and one close-without-save recovery;
|
||||
- a multi-project resume after interruption; and
|
||||
- Packager, ERC, and netlist comparison on a saved successful project.
|
||||
|
||||
The acceptance record captures build number, Windows version, central-library
|
||||
identity/revision or fingerprint, project fixtures, mappings, route profile,
|
||||
date, tester, and evidence files. Compatibility is not claimed until every
|
||||
required item passes with no unresolved blocker.
|
||||
|
||||
## 16. Release Criteria
|
||||
|
||||
Version 1 is ready for production use only when:
|
||||
|
||||
- all automated tests pass;
|
||||
- the live 7.9.5 probe has produced a valid compatibility profile;
|
||||
- all required live acceptance cases pass;
|
||||
- every successful replacement preserves protected instance state and
|
||||
connectivity;
|
||||
- Packager, ERC, and netlist checks introduce no relevant regression;
|
||||
- backup restore has been demonstrated on a disposable project;
|
||||
- interruption resume has been demonstrated across multiple projects; and
|
||||
- operator documentation states the exact manual steps for every selected
|
||||
fallback route.
|
||||
|
||||
Until then, generated scripts and reports are evaluation artifacts and must be
|
||||
used only on disposable project copies.
|
||||
@@ -0,0 +1,306 @@
|
||||
# DxDesigner 7.9.5 Automatic Reference Designator Tool
|
||||
|
||||
Date: 2026-09-01
|
||||
|
||||
## 1. Purpose
|
||||
|
||||
Build the first module of a maintainable DxDesigner 7.9.5 productivity suite: automatic reference designator assignment with preview, validation, safe write-back, and recovery.
|
||||
|
||||
The tool replaces the legacy workflow that copies selected reference designators to Excel, generates values manually, and pastes them back. Excel is not part of the new annotation workflow.
|
||||
|
||||
## 2. Compatibility Baseline
|
||||
|
||||
DxDesigner/Expedition Enterprise 7.9.5 is the only supported schematic integration baseline for this phase.
|
||||
|
||||
The installation and import flow must remain compatible with the method demonstrated by the supplied legacy tool:
|
||||
|
||||
1. The user opens DxDesigner 7.9.5.
|
||||
2. The user opens `Settings -> Run at Startup`.
|
||||
3. The user adds one `MenuAdd.vbs` file to the Scripts list.
|
||||
4. After DxDesigner restarts, one `Dx Productivity` menu appears on the Sheet Menu Bar.
|
||||
|
||||
The integration must not require a newer Xpedition add-in framework, a copied DLL from another release, COM re-registration, or a project-format upgrade.
|
||||
|
||||
`MenuAdd.vbs` uses only interfaces already demonstrated in the legacy package:
|
||||
|
||||
- `Scripting.GetEnvVariable`
|
||||
- `CommandBars("Sheet Menu Bar").Controls.Add`
|
||||
- menu control captions and `OnAction`
|
||||
- the 7.9.5 internal scripting host
|
||||
|
||||
The installer sets a user-level `DXTOOLS_HOME` environment variable. `MenuAdd.vbs` resolves every tool path through `Scripting.GetEnvVariable("DXTOOLS_HOME")`; it contains no `D:\NET_CHECK` or other fixed installation path. DxDesigner must be restarted after installation so its script host sees the new environment value.
|
||||
|
||||
## 3. Compatibility Probe
|
||||
|
||||
The first implementation milestone is a read-only 7.9.5 probe imported through the exact startup-script flow above. It must not change a schematic.
|
||||
|
||||
The probe verifies:
|
||||
|
||||
- the imported script can add and remove its own menu entries without duplication;
|
||||
- a menu item can enter the internal VBS bridge and launch the configured Python executable;
|
||||
- `ActiveView.Query(VDM_COMP, VD_SELECTED)` returns selected components;
|
||||
- `Application.DesignComponents` enumerates the full design;
|
||||
- component reference designator, sheet number, X/Y position, attributes, full path, and stable identity are readable;
|
||||
- the bridge can hold component object references while the Python process is open;
|
||||
- UTF-8 snapshot and result files can be exchanged through the user-local run directory.
|
||||
|
||||
The release menu action uses the first 7.9.5-native route proven by the probe. The permitted routes, in order, are:
|
||||
|
||||
1. a named bridge procedure in the imported startup VBS;
|
||||
2. the 7.9.5 `Run` script action;
|
||||
3. the proven `Form` action with a minimal 7.9.5 EFM launcher.
|
||||
|
||||
No unverified route is shipped. If the first two routes are unavailable, the launcher EFM is created or adapted using the 7.9.5 form format; it is not copied from a newer release.
|
||||
|
||||
## 4. Architecture
|
||||
|
||||
```text
|
||||
DxDesigner 7.9.5
|
||||
-> imported MenuAdd.vbs
|
||||
-> internal VBS bridge
|
||||
-> UTF-8 snapshot + in-memory component map
|
||||
-> Python/PySide6 application
|
||||
-> validated bridge_id/new_refdes result
|
||||
-> VBS write-back and full-design verification
|
||||
```
|
||||
|
||||
### 4.1 VBS integration layer
|
||||
|
||||
The VBS layer owns every DxDesigner COM/API call. It reads the current design, launches Python, waits for the result, revalidates the snapshot, applies changes, verifies the design, and rolls back on failure.
|
||||
|
||||
Python does not attach directly to `ViewDraw.Application`. This avoids 32-bit versus 64-bit COM registration and licensing incompatibilities between DxDesigner 7.9.5 and modern Python.
|
||||
|
||||
### 4.2 Python domain layer
|
||||
|
||||
The Python domain layer is independent of DxDesigner. It parses snapshots, groups components, computes deterministic annotation plans, validates collisions, and produces an immutable change set.
|
||||
|
||||
This layer has no GUI imports and can be exhaustively unit tested with fixtures.
|
||||
|
||||
### 4.3 Python UI layer
|
||||
|
||||
The desktop UI uses PySide6 and a local style sheet. It implements the approved three-column workbench:
|
||||
|
||||
- suite navigation on the left;
|
||||
- annotation rules in the center;
|
||||
- live old-to-new preview on the right.
|
||||
|
||||
The source remains runnable with the installed Python 3.12 environment. A later packaging step may produce a standalone executable, but packaging does not change the VBS bridge protocol.
|
||||
|
||||
## 5. Bridge Protocol
|
||||
|
||||
Each run uses a unique directory:
|
||||
|
||||
```text
|
||||
%LOCALAPPDATA%\DxProductivity\runs\<run_id>\
|
||||
request.json
|
||||
result.tsv
|
||||
apply-status.json
|
||||
```
|
||||
|
||||
VBS writes `request.json` as UTF-8 using a deterministic JSON escaping helper. Python writes an ordered `result.tsv` apply schedule with five constrained fields: `sequence`, `bridge_id`, `expected_refdes`, `new_refdes`, and `final_refdes`. Tabs and line breaks are illegal in every result field.
|
||||
|
||||
Each sequence number is unique and contiguous from 1. A bridge ID normally appears once. It may appear twice only when a validated reannotation cycle requires a temporary placeholder step followed by the final assignment. VBS verifies `expected_refdes` immediately before every step and verifies `final_refdes` after the complete schedule.
|
||||
|
||||
Each snapshot component contains:
|
||||
|
||||
- ephemeral `bridge_id` assigned by the current VBS run;
|
||||
- stable UID when exposed by 7.9.5;
|
||||
- hierarchical full path as an identity fallback;
|
||||
- sheet number and current-view membership;
|
||||
- X and Y schematic coordinates;
|
||||
- current reference designator;
|
||||
- symbol-level default reference designator or prefix when available;
|
||||
- selection state;
|
||||
- part number and Value for preview;
|
||||
- lock or protection state when exposed by 7.9.5.
|
||||
|
||||
VBS retains an in-memory `bridge_id -> component object` map while Python is open. Result rows never rely on COM enumeration order.
|
||||
|
||||
Before write-back, VBS confirms that the active design, component identity, component count in scope, and original reference designators still match the snapshot. A mismatch invalidates the plan and requires a refresh.
|
||||
|
||||
## 6. Annotation Behavior
|
||||
|
||||
### 6.1 Scope
|
||||
|
||||
The UI supports three explicit scopes:
|
||||
|
||||
- selected components, which is the default;
|
||||
- current sheet;
|
||||
- full design.
|
||||
|
||||
If the selected scope is empty, Apply remains disabled. The tool does not silently fall back to another scope.
|
||||
|
||||
### 6.2 Processing mode
|
||||
|
||||
The default mode fills only unannotated components:
|
||||
|
||||
- blank reference designators;
|
||||
- placeholders matching a leading alphabetic prefix followed by one or more question marks, such as `R?`, `C??`, or `TP?`.
|
||||
|
||||
Existing formal reference designators are preserved. A separate, explicit mode reannotates every eligible component in scope.
|
||||
|
||||
### 6.3 Prefix resolution
|
||||
|
||||
Prefix resolution is deterministic:
|
||||
|
||||
1. use the alphabetic prefix in the current placeholder;
|
||||
2. otherwise use the symbol-level default reference designator/prefix exposed by 7.9.5;
|
||||
3. otherwise require an explicit prefix in the preview table.
|
||||
|
||||
An unresolved prefix is a blocking validation error. Prefix comparison is case-insensitive and output is normalized to uppercase.
|
||||
|
||||
### 6.4 Multi-unit components
|
||||
|
||||
All symbols that represent the same logical component are grouped by stable component identity. They receive one base reference designator. Symbol units or gates do not consume additional sequence numbers.
|
||||
|
||||
If 7.9.5 does not expose a stable UID, the compatibility adapter derives a stable grouping key from the hierarchical component path and validated component metadata. Ambiguous groups are blocked rather than guessed.
|
||||
|
||||
### 6.5 Sorting
|
||||
|
||||
The default order is:
|
||||
|
||||
1. numeric sheet number ascending;
|
||||
2. schematic Y coordinate from top to bottom;
|
||||
3. X coordinate from left to right within the same visual row;
|
||||
4. stable identity as the final deterministic tie-breaker.
|
||||
|
||||
Because schematic Y-axis direction is API-dependent, the compatibility adapter normalizes coordinates so larger visual height always sorts first. Components are grouped into visual rows using a default 5 mm tolerance. The user can change the tolerance.
|
||||
|
||||
Alternative orders are available for left-to-right column scanning and reverse directions.
|
||||
|
||||
### 6.6 Numbering modes
|
||||
|
||||
Continuous mode is the default. Each prefix owns an independent sequence beginning at 1 unless the user changes the start value. Numbers already used anywhere outside the target set are skipped.
|
||||
|
||||
Page mode uses:
|
||||
|
||||
```text
|
||||
number = numeric_sheet_number * page_step + page_start
|
||||
```
|
||||
|
||||
The defaults are `page_step = 100` and `page_start = 1`, so sheet 3 starts at 301. Each prefix has an independent page sequence. Non-numeric sheet identifiers require an explicit numeric mapping before Apply.
|
||||
|
||||
### 6.7 Collision rules
|
||||
|
||||
Validation is case-insensitive and covers:
|
||||
|
||||
- duplicates inside the proposed change set;
|
||||
- collisions with components outside the target set;
|
||||
- illegal or empty prefixes;
|
||||
- invalid numeric ranges;
|
||||
- duplicate existing formal reference designators in the source design;
|
||||
- multiple proposed values for one logical component.
|
||||
|
||||
Blocking issues disable Apply. Warnings remain selectable and can locate the affected schematic component.
|
||||
|
||||
## 7. Safe Apply and Recovery
|
||||
|
||||
Every Apply operation follows this sequence:
|
||||
|
||||
1. revalidate the snapshot against the active design;
|
||||
2. run all collision and format checks again;
|
||||
3. write a timestamped backup mapping under `%LOCALAPPDATA%\DxProductivity\backups`;
|
||||
4. apply changes using the in-memory component map;
|
||||
5. re-enumerate the full design and verify every expected reference designator;
|
||||
6. write a machine-readable apply status and append an operation-history entry.
|
||||
|
||||
Fill-only plans normally write directly because they cannot swap existing formal identifiers.
|
||||
|
||||
Full reannotation plans are ordered as a dependency graph. Acyclic moves are applied first. Cycles use the component prefix placeholder, such as `R?`, as a temporary value, then complete the cycle. This uses a placeholder format already accepted by DxDesigner 7.9.5 instead of inventing a new temporary reference-designator syntax.
|
||||
|
||||
If any assignment or verification fails, VBS restores every component from the backup mapping and verifies the restoration. A rollback failure is reported prominently with the backup path and the exact remaining mismatch.
|
||||
|
||||
The operation-history view exposes Restore Last Annotation. Restore performs the same preflight, backup, apply, and verification sequence; it is not a blind file replay.
|
||||
|
||||
## 8. User Interface and Visual Acceptance
|
||||
|
||||
The approved mockup is the visual baseline. The release implementation follows these measurable requirements derived from Apple Human Interface Guidelines while remaining a Windows desktop application:
|
||||
|
||||
- 13 pt default content text and no essential text below 10 pt;
|
||||
- approximately 28 by 28 pt default desktop controls and no interactive target below 20 by 20 pt;
|
||||
- 16 px simplified line icons with consistent weight and optical alignment;
|
||||
- tooltips and accessible names for icon-only controls;
|
||||
- one semantic use per status color;
|
||||
- text contrast of at least 4.5:1 for normal text;
|
||||
- icons or text in addition to color for every status;
|
||||
- light, dark, and increased-contrast-compatible palettes;
|
||||
- complete keyboard navigation with visible focus;
|
||||
- no clipping or overlap at 100%, 125%, and 150% Windows display scaling;
|
||||
- a resizable window with a minimum supported content area of 1100 by 700 logical pixels;
|
||||
- no required command placed only at the bottom edge of the window;
|
||||
- no automatic, blinking, bouncing, or decorative motion.
|
||||
|
||||
Interface icons use a cross-platform icon set with Apple-like semantic consistency. Apple SF Symbols are a design reference only and are not redistributed in the Windows application.
|
||||
|
||||
Official design references:
|
||||
|
||||
- [Designing for macOS](https://developer.apple.com/design/human-interface-guidelines/designing-for-macos)
|
||||
- [Layout](https://developer.apple.com/design/human-interface-guidelines/layout)
|
||||
- [Typography](https://developer.apple.com/design/human-interface-guidelines/typography)
|
||||
- [Color](https://developer.apple.com/design/human-interface-guidelines/color)
|
||||
- [Accessibility](https://developer.apple.com/design/human-interface-guidelines/accessibility)
|
||||
- [Icons](https://developer.apple.com/design/human-interface-guidelines/icons)
|
||||
|
||||
## 9. Error Handling
|
||||
|
||||
Errors are divided into three levels:
|
||||
|
||||
- blocking: Apply is disabled, for example duplicate output or missing prefix;
|
||||
- warning: the plan remains applicable after review, for example a nonstandard existing designator outside scope;
|
||||
- informational: no action required, for example a locked component preserved by policy.
|
||||
|
||||
The UI shows an icon, short message, affected component count, and location action. Technical details and bridge logs are available in a diagnostics view and retained per run. Normal users do not need to inspect raw JSON, TSV, COM error codes, or Python tracebacks.
|
||||
|
||||
If Python is missing or cannot start, the VBS bridge shows a concise message with the configured executable path and exits without changing the design.
|
||||
|
||||
## 10. Testing Strategy
|
||||
|
||||
### 10.1 Automated domain tests
|
||||
|
||||
Tests cover:
|
||||
|
||||
- placeholder recognition and prefix normalization;
|
||||
- continuous and page numbering;
|
||||
- occupied-number skipping;
|
||||
- row tolerance and every sort direction;
|
||||
- numeric and non-numeric sheet identifiers;
|
||||
- multi-unit grouping;
|
||||
- duplicate and collision detection;
|
||||
- deterministic output for equal coordinates;
|
||||
- reannotation dependency graphs and cycles;
|
||||
- backup and restore plan generation.
|
||||
|
||||
### 10.2 Bridge contract tests
|
||||
|
||||
Pure VBS helpers are tested with `cscript` where possible. Tests cover UTF-8, JSON escaping, result parsing, invalid rows, duplicate or noncontiguous sequence numbers, unknown bridge IDs, illegal repeated bridge steps, stale snapshots, and simulated assignment failures.
|
||||
|
||||
Python contract tests use captured 7.9.5-compatible fixtures and never require a live DxDesigner instance.
|
||||
|
||||
### 10.3 UI tests
|
||||
|
||||
Qt tests cover default selections, scope changes, preview filtering, blocking-error behavior, keyboard tab order, light/dark themes, and Apply confirmation for full reannotation.
|
||||
|
||||
Screenshots are checked at representative 1100 by 700 and 1440 by 900 window sizes under 100%, 125%, and 150% scaling. Text, controls, and tables must not overlap or clip.
|
||||
|
||||
### 10.4 Live 7.9.5 acceptance
|
||||
|
||||
The user runs the compatibility probe and a sample-project acceptance checklist on the target DxDesigner 7.9.5 installation. Live acceptance covers startup-script import, menu creation, selected/current/full scopes, coordinate order, write-back, duplicate prevention, rollback, restoration, Chinese installation paths, and paths containing spaces.
|
||||
|
||||
No release is marked 7.9.5-compatible solely from mocked COM tests.
|
||||
|
||||
## 11. Deliverables for Phase One
|
||||
|
||||
- 7.9.5 compatibility probe;
|
||||
- installer and uninstall instructions using startup-script import;
|
||||
- `MenuAdd.vbs` and the verified 7.9.5 bridge adapter;
|
||||
- Python source and dependency metadata;
|
||||
- automatic reference designator GUI;
|
||||
- annotation domain tests and bridge contract tests;
|
||||
- live 7.9.5 acceptance checklist;
|
||||
- user guide for installation, annotation, preview, Apply, and Restore.
|
||||
|
||||
## 12. Non-Goals
|
||||
|
||||
This phase does not implement Value/Value1/Part Number editing, attribute visibility, design audits, network navigation, BOM generation, BOM-to-schematic navigation, or Expedition PCB assembly text placement. Those modules reuse the verified bridge and shared application shell in later phase-specific designs.
|
||||
|
||||
This phase does not import code or binaries from newer Xpedition releases and does not modify the DxDesigner project format.
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
# DxDesigner 7.9.5 Parameter Presentation Transfer Design
|
||||
|
||||
## 1. Purpose
|
||||
|
||||
This document extends the existing DxDesigner 7.9.5 multi-project part
|
||||
replacement design. The replacement remains a native `Replace Part` operation
|
||||
with `Library Wins`, but it now has one controlled post-replacement step:
|
||||
|
||||
- copy the new symbol's exact `Part Label` value into the instance `Value`;
|
||||
- preserve presentation metadata for parameters that existed on the old
|
||||
instance and have an unambiguous same-name parameter on the new instance;
|
||||
- never copy an old ordinary parameter value into the new instance.
|
||||
|
||||
The material identifier remains the `Part Number` attribute. Values such as
|
||||
`4300-CA2260-A300` are examples, not a syntax restriction. Identity comparison
|
||||
trims surrounding whitespace and is case-insensitive, while reports preserve
|
||||
the original spelling.
|
||||
|
||||
This document supersedes only the attribute semantics, snapshot fields, Apply
|
||||
steps, and verification rules described below. All existing requirements for
|
||||
backup, native replacement, RefDes, placement, origin, units, pins,
|
||||
connectivity, unrelated objects, recovery, evidence correlation, and
|
||||
evaluation-only release status continue to apply.
|
||||
|
||||
## 2. Non-Goals
|
||||
|
||||
- Rebuilding a symbol or its pins through scripts.
|
||||
- Copying old ordinary parameter values over new library values.
|
||||
- Creating parameters that existed only on the old symbol.
|
||||
- Reconnecting, moving, creating, or deleting wires.
|
||||
- Using UI coordinates, `SendKeys`, or timing delays.
|
||||
- Claiming an unsupported 7.9.5 property API without probe and live evidence.
|
||||
|
||||
## 3. Parameter Identity
|
||||
|
||||
Parameter names are normalized by trimming surrounding whitespace and applying
|
||||
a case-insensitive comparison. The original name remains in evidence and
|
||||
reports.
|
||||
|
||||
For each component and owner scope:
|
||||
|
||||
- one old and one new parameter with the same normalized name form an
|
||||
unambiguous match;
|
||||
- an old-only parameter is not recreated and is reported as removed;
|
||||
- a new-only parameter keeps its new-library value and presentation defaults;
|
||||
- duplicate normalized names on either side are ambiguous and receive no
|
||||
automatic presentation transfer.
|
||||
|
||||
An ambiguous ordinary parameter creates a warning. An ambiguous `Part Label`
|
||||
or `Value` prevents the mandatory `Value` operation and is therefore a hard
|
||||
failure.
|
||||
|
||||
## 4. Trusted Pre-Replacement Capture
|
||||
|
||||
The bridge must capture and durably publish a complete trusted snapshot before
|
||||
it selects components or opens native Replace Part. Capture occurs separately
|
||||
for every matched logical component, every placed unit, and every existing
|
||||
parameter instance. It may not be reconstructed from post-replacement state.
|
||||
|
||||
The controller must correlate this snapshot with the job, project, mapping,
|
||||
command identifier, active-project identity, expected component count, and
|
||||
current project fingerprint. If any matched component, unit, parameter value,
|
||||
or required presentation field cannot be read unambiguously, the bridge stops
|
||||
before replacement and reports the exact object and field.
|
||||
|
||||
Each parameter snapshot contains:
|
||||
|
||||
- original and normalized parameter name;
|
||||
- current value, for reporting and rollback comparison only;
|
||||
- logical component key and RefDes;
|
||||
- owner scope and placed-unit identity, when the parameter is unit-owned;
|
||||
- visible state;
|
||||
- schematic text origin or position in invariant coordinates;
|
||||
- rotation or orientation;
|
||||
- horizontal and vertical justification or the equivalent alignment values;
|
||||
- color;
|
||||
- font family or style identifier when exposed;
|
||||
- text size or height/width fields exposed by the certified route; and
|
||||
- any additional stable presentation field explicitly named by the
|
||||
compatibility profile.
|
||||
|
||||
The schema distinguishes component/unit placement coordinates from parameter
|
||||
text coordinates. A parameter coordinate must never substitute for component
|
||||
origin or component position evidence.
|
||||
|
||||
## 5. Apply Sequence
|
||||
|
||||
For one mapping group in one project, the bridge performs these ordered steps:
|
||||
|
||||
1. Validate the correlated command, active project, saved state, inventory
|
||||
fingerprint, certification, and expected count.
|
||||
2. Capture and durably publish the trusted pre-replacement component, unit,
|
||||
pin, network, ordinary parameter, `Part Label`, and `Value` evidence.
|
||||
3. Select exactly the logical components identified by the controller.
|
||||
4. Invoke or request the native `Replace Part` dialog.
|
||||
5. Require the exact target `Part Number` and `Library Wins`.
|
||||
6. Observe native completion through the certified route or explicit manual
|
||||
continuation; no blind delay is allowed.
|
||||
7. Re-enumerate the replaced objects and verify their target identity.
|
||||
8. Read the new symbol's exact `Part Label` value.
|
||||
9. Write that exact value to the instance `Value` and read it back.
|
||||
10. Transfer presentation metadata for unambiguous same-name parameters.
|
||||
11. Export the post-transfer snapshot and a field-level transfer result.
|
||||
12. Let Python run hard verification and produce warnings/differences.
|
||||
|
||||
No ordinary parameter value assignment is permitted in step 10. `Library
|
||||
Wins` remains authoritative for ordinary parameter values.
|
||||
|
||||
## 6. Value Rule
|
||||
|
||||
`Value` is the only parameter whose value is written by the post-replacement
|
||||
step.
|
||||
|
||||
- Source: the exact new-symbol `Part Label` value.
|
||||
- Destination: the replaced instance's `Value` parameter.
|
||||
- Comparison: exact string equality after the write; no case folding or
|
||||
whitespace normalization changes the stored value.
|
||||
- Presentation: inherit all certified presentation fields from the old
|
||||
instance's `Value` when it existed unambiguously.
|
||||
- Default presentation: when the old instance had no `Value`, retain the new
|
||||
symbol's default `Value` presentation.
|
||||
|
||||
Missing, empty, ambiguous, unreadable, or unwritable `Part Label`; missing,
|
||||
ambiguous, or unwritable `Value`; a write error; or a read-back mismatch is a
|
||||
hard failure. The project cannot be saved and the existing verified Undo or
|
||||
close-without-save recovery path is required.
|
||||
|
||||
Failure to copy only a `Value` presentation field is a warning, not a hard
|
||||
failure, provided the exact `Value` content was written and read back.
|
||||
|
||||
## 7. Ordinary Parameter Presentation Transfer
|
||||
|
||||
For every unambiguous same-name ordinary parameter, the bridge attempts to
|
||||
copy each presentation field from the trusted old snapshot to the new
|
||||
parameter. Values remain those supplied by the new library.
|
||||
|
||||
Each failed field produces a `parameter_style_inheritance_failed` warning with
|
||||
job, project, mapping, logical key, RefDes, unit or owner scope, parameter name,
|
||||
field name, old presentation value, observed new value, API route, and error.
|
||||
The warning does not trigger Undo and does not by itself block save.
|
||||
|
||||
The reports also distinguish:
|
||||
|
||||
- `parameter_removed_by_new_symbol`;
|
||||
- `parameter_added_by_new_symbol`;
|
||||
- `parameter_value_changed_by_library`;
|
||||
- `parameter_name_ambiguous`; and
|
||||
- successfully inherited presentation fields.
|
||||
|
||||
## 8. Verification and Recovery
|
||||
|
||||
Hard verification still requires the exact target `Part Number`, component
|
||||
count, RefDes, hierarchy, unit set, component origin and position, rotation,
|
||||
mirror state, pin-number set, pin coordinates, pin-to-net identity, and no
|
||||
unrelated component changes.
|
||||
|
||||
It additionally requires:
|
||||
|
||||
- one nonempty, unambiguous new `Part Label` per replaced instance;
|
||||
- exact `Value == Part Label` after the write and in the persisted reread; and
|
||||
- no ordinary parameter value assignment performed by the transfer adapter.
|
||||
|
||||
Presentation warnings remain visible at the project save gate and in CSV, JSON,
|
||||
and HTML reports. They do not override a hard verification result.
|
||||
|
||||
If any hard condition fails, Undo must be verified against the complete trusted
|
||||
pre-replacement snapshot, including component/unit geometry, connectivity,
|
||||
parameter values, and parameter presentation. If exact Undo cannot be proven,
|
||||
the project must be closed without saving or restored from the verified backup.
|
||||
|
||||
## 9. Compatibility Profile
|
||||
|
||||
The read-mostly probe records the actual 7.9.5 routes and types for:
|
||||
|
||||
- enumerating parameter instances and their owner scope;
|
||||
- reading `Part Label` and `Value`;
|
||||
- writing and reading back `Value`;
|
||||
- reading and writing each supported presentation field; and
|
||||
- distinguishing component placement coordinates from parameter text
|
||||
coordinates.
|
||||
|
||||
Production Apply is blocked unless the `Part Label` read route and `Value`
|
||||
write/read-back routes are live-certified. An unavailable ordinary
|
||||
presentation field disables only that field's automatic transfer and produces
|
||||
an explicit warning/capability result.
|
||||
|
||||
The profile promotion evidence must identify the exact DxDesigner 7.9.5 build,
|
||||
central-library identity or fingerprint, disposable fixture, mapping, route,
|
||||
field type, observed before/after values, tester, date, and evidence hashes.
|
||||
|
||||
## 10. Protocol and Modules
|
||||
|
||||
The snapshot protocol advances to format version 3. Version 3 adds structured
|
||||
parameter instances and presentation metadata. Version 1 lacks independent
|
||||
component origin evidence and remains unsafe. Version 2 lacks parameter
|
||||
presentation evidence and cannot authorize the new Apply workflow. Existing
|
||||
version 1 or 2 jobs must be rejected with a stable re-inventory-required error;
|
||||
they are never silently upgraded.
|
||||
|
||||
Responsibilities remain separated:
|
||||
|
||||
- Python domain/protocol modules define immutable parameter and presentation
|
||||
evidence.
|
||||
- A dedicated Python parameter-transfer policy module matches names, classifies
|
||||
differences, and verifies results without accessing DxDesigner.
|
||||
- A dedicated ASCII-only VBScript parameter-transfer adapter performs the
|
||||
certified `Part Label`, `Value`, and presentation operations.
|
||||
- The bridge coordinates selection, native replacement, adapter invocation,
|
||||
and evidence publication, but does not decide warning or save policy.
|
||||
- Controller/operator modules consume correlated results and preserve the
|
||||
existing save and recovery gates.
|
||||
|
||||
## 11. Tests and Acceptance
|
||||
|
||||
Automated tests cover:
|
||||
|
||||
- representative material numbers such as `4300-CA2260-A300` without imposing
|
||||
a fixed syntax;
|
||||
- capture before selection or dialog invocation;
|
||||
- multiple logical components, units, and parameter coordinate sets;
|
||||
- case-insensitive trimmed name matching and ambiguous duplicates;
|
||||
- old-only, new-only, hidden, and visible parameters;
|
||||
- ordinary values remaining from the new library;
|
||||
- each presentation field copied independently;
|
||||
- field-level warning behavior and report contents;
|
||||
- exact `Part Label -> Value` write/read-back;
|
||||
- missing/empty/ambiguous fields and forced write failure causing Undo;
|
||||
- persisted `Value` verification after save;
|
||||
- exact Undo restoration of values and presentation; and
|
||||
- real `cscript` execution through a fake object host without source-text-only
|
||||
claims.
|
||||
|
||||
Live 7.9.5 acceptance uses disposable projects and records screenshots or
|
||||
machine evidence for parameter positions, colors, sizes, orientation,
|
||||
visibility, ordinary new-library values, exact `Value`, Undo, save, and
|
||||
persisted reread. Until every required route and case passes, the package
|
||||
remains evaluation-only.
|
||||
+340
@@ -0,0 +1,340 @@
|
||||
# DxDesigner Part Replacement Trial Task Center Design
|
||||
|
||||
## 1. Purpose
|
||||
|
||||
Build a Windows desktop EXE that makes the current DxDesigner 7.9.5
|
||||
replacement investigation usable on one disposable project first, while using
|
||||
the same task, project, mapping, status, and evidence model needed for later
|
||||
multi-project execution.
|
||||
|
||||
The application is a trial task center. It manages work, collects before/after
|
||||
probe evidence, guides the operator through the native DxDesigner replacement,
|
||||
verifies the observed result, advances successful projects to Completed, and
|
||||
records every application and task error. It does not claim that the
|
||||
uncertified production replacement path is ready.
|
||||
|
||||
## 2. Release Boundary
|
||||
|
||||
The first release is `evaluation-only` and may be used only with complete,
|
||||
disposable project copies.
|
||||
|
||||
It does not:
|
||||
|
||||
- automate DxDesigner controls with window coordinates, `SendKeys`, or delays;
|
||||
- bypass the existing production certification or compatibility-profile gates;
|
||||
- save, reconnect, move, add, or delete schematic objects;
|
||||
- write `Value` or parameter presentation fields;
|
||||
- delete source projects when a task is deleted; or
|
||||
- present a manually confirmed replacement as machine-verified success.
|
||||
|
||||
The operator still performs native `Replace Part` with `Library Wins` in
|
||||
DxDesigner. The EXE makes that process repeatable, correlated, reviewable, and
|
||||
ready for later replacement-adapter integration.
|
||||
|
||||
## 3. Technology and Packaging
|
||||
|
||||
- Python 3.12.
|
||||
- PySide6 for the native Windows UI.
|
||||
- SQLite from the Python standard library for mutable task drafts and status.
|
||||
- Existing `dx_productivity.part_replace` discovery, validation, identity, and
|
||||
verification helpers where their contracts fit the trial flow.
|
||||
- Existing ASCII-only DxDesigner 7.9.5 menu probe for live evidence.
|
||||
- Python logging plus append-only JSON Lines task events.
|
||||
- PyInstaller `onedir` output containing `DxPartReplace.exe` and its runtime
|
||||
files. A single-file build is deferred until the installed-machine behavior
|
||||
is proven.
|
||||
|
||||
The executable must not require a separate Python installation. The DxDesigner
|
||||
menu integration remains a separately installed site integration because it is
|
||||
loaded by DxDesigner itself.
|
||||
|
||||
## 4. Storage
|
||||
|
||||
Mutable task-center data lives outside engineering projects:
|
||||
|
||||
```text
|
||||
%LOCALAPPDATA%\DxProductivity\trial-task-center\
|
||||
task-center.db
|
||||
logs\application.log
|
||||
tasks\<task-id>\
|
||||
task.json
|
||||
events.jsonl
|
||||
logs\task.log
|
||||
evidence\
|
||||
<project-id>\before-profile.json
|
||||
<project-id>\after-profile.json
|
||||
<project-id>\comparison.json
|
||||
```
|
||||
|
||||
`task-center.db` uses schema version 1 and stores tasks, mapping rules, scanned
|
||||
projects, project selection, project state, timestamps, and the last error
|
||||
identifier. All database writes use transactions. Evidence JSON is written
|
||||
atomically and referenced by SHA-256 from `events.jsonl`.
|
||||
|
||||
Task deletion is a soft delete recorded by `deleted_at`. It hides the task from
|
||||
the normal task list but keeps logs and evidence. A future retention tool may
|
||||
purge archived records; the MVP never recursively deletes task or project
|
||||
directories.
|
||||
|
||||
## 5. Domain Records
|
||||
|
||||
### Task
|
||||
|
||||
- immutable UUID task ID;
|
||||
- editable unique nonblank name;
|
||||
- optional note;
|
||||
- selected discovery root;
|
||||
- status: `draft`, `ready`, `running`, `paused`, `completed`, `failed`, or
|
||||
`deleted`;
|
||||
- created, updated, started, and completed UTC timestamps; and
|
||||
- last error ID and summary.
|
||||
|
||||
The application supports task create, read/list, rename/edit, soft delete, and
|
||||
restore. A running task cannot be deleted; it must be paused first.
|
||||
|
||||
### Mapping Rule
|
||||
|
||||
- immutable rule UUID;
|
||||
- task ID;
|
||||
- ordered position;
|
||||
- old `Part Number`;
|
||||
- new `Part Number`; and
|
||||
- enabled flag.
|
||||
|
||||
Rules support create, read, edit, delete, and reorder. Validation reuses the
|
||||
existing mapping semantics: trim surrounding whitespace, compare identities
|
||||
case-insensitively, reject blanks, self-maps, duplicate sources, chains, and
|
||||
cycles. Material numbers such as `4300-CA2260-A300` remain ordinary strings and
|
||||
are not constrained by a format regular expression.
|
||||
|
||||
### Project
|
||||
|
||||
- stable project ID derived from the canonical project-definition path;
|
||||
- task ID, display name, path, and discovery root;
|
||||
- selected flag;
|
||||
- state: `pending`, `capturing_before`, `awaiting_operator`,
|
||||
`capturing_after`, `verifying`, `completed`, `failed`, or `skipped`;
|
||||
- retry count; and
|
||||
- last error ID and summary.
|
||||
|
||||
Rescanning updates candidates without silently selecting new projects or
|
||||
removing prior evidence. Missing projects are visibly marked unavailable.
|
||||
|
||||
## 6. User Interface
|
||||
|
||||
The application opens directly into the task center, not a landing page.
|
||||
|
||||
### Task List
|
||||
|
||||
The left navigation contains Active, Completed, and Deleted views. It supports
|
||||
create, rename/edit, open, soft delete, and restore. Active-task rows show a
|
||||
compact progress count and the last updated time.
|
||||
|
||||
### Task Workspace
|
||||
|
||||
The main workspace contains:
|
||||
|
||||
- a directory path field and native directory picker;
|
||||
- Scan and Rescan commands;
|
||||
- a project table with selection checkboxes, Select All, Clear Selection,
|
||||
project name, canonical path, state, last result, and retry command;
|
||||
- an editable mapping table with Add, Edit, Delete, and reorder commands;
|
||||
- Start, Pause, Resume, and Open Evidence Folder commands;
|
||||
- a current-operator-action band containing the exact project, old/new part
|
||||
number, expected count when known, and the next DxDesigner instruction; and
|
||||
- a docked log view showing timestamp, level, project, operation, and message.
|
||||
|
||||
The UI remains work-focused: dense tables, restrained color, no decorative
|
||||
cards, no nested cards, and no required control below the fold. Completed
|
||||
projects leave the active queue immediately and remain accessible through the
|
||||
Completed filter.
|
||||
|
||||
## 7. Trial Execution Flow
|
||||
|
||||
### 7.1 Validation
|
||||
|
||||
Start is enabled only when the task has at least one enabled valid mapping and
|
||||
one selected available `.prj` project. The operator must confirm that every
|
||||
selected project is a complete disposable copy. The confirmation is recorded
|
||||
with timestamp and task ID; it does not waive any verification rule.
|
||||
|
||||
Only one project is active at a time. Remaining selected projects stay queued.
|
||||
Pause prevents the next project from starting but does not interrupt a probe or
|
||||
verification that is already being committed.
|
||||
|
||||
### 7.2 Before Capture
|
||||
|
||||
For the active project, the EXE records the current menu-probe file hash and
|
||||
timestamp, then instructs the operator to:
|
||||
|
||||
1. open the exact project in DxDesigner 7.9.5;
|
||||
2. save any unrelated edits;
|
||||
3. run `Dx Productivity -> Part replacement probe`; and
|
||||
4. return to the EXE and choose Capture Result.
|
||||
|
||||
The EXE accepts the profile only when it is newer or byte-different from the
|
||||
recorded predecessor, parses as the expected profile version, and its canonical
|
||||
`project.identity` exactly matches the selected project. It atomically copies
|
||||
the bytes into task evidence before advancing.
|
||||
|
||||
The before profile is searched exclusively by the `Part Number` attribute. For
|
||||
each enabled rule it records all matching logical identities and counts. A rule
|
||||
with no matches is reported and skipped for that project; ambiguous or
|
||||
unreadable identity/parameter evidence fails the project before replacement.
|
||||
|
||||
### 7.3 Native Replacement
|
||||
|
||||
The project moves to `awaiting_operator`. The UI shows one mapping at a time and
|
||||
the exact identities/count found in the trusted before profile. The operator
|
||||
uses DxDesigner Find, selects those components, invokes native Replace Part,
|
||||
chooses the requested new part, and selects `Library Wins`.
|
||||
|
||||
The EXE does not click the dialog, infer completion from elapsed time, or alter
|
||||
the schematic. The operator confirms only that the native action was attempted;
|
||||
this confirmation is not success evidence.
|
||||
|
||||
After all matching rules have been attempted, the EXE instructs the operator to
|
||||
run the read-only menu probe again and capture the result.
|
||||
|
||||
### 7.4 Verification
|
||||
|
||||
The after profile must pass the same freshness, schema, and project-identity
|
||||
checks. For every logical identity matched before replacement:
|
||||
|
||||
- the after `Part Number` must equal the rule's new value using the normal
|
||||
trimmed, case-insensitive identity comparison;
|
||||
- no matched logical identity may disappear or become ambiguous;
|
||||
- RefDes, hierarchy, placed-unit count, component origin/position, rotation,
|
||||
mirror state, pin numbers, pin coordinates, and pin-to-net identity must be
|
||||
unchanged wherever the probe supplied trusted evidence; and
|
||||
- unrelated logical components must retain their observed identity and
|
||||
protected fields.
|
||||
|
||||
The comparison records `Part Label`, `Value`, and parameter-presentation
|
||||
capability differences but does not write them in this release. Missing or
|
||||
unsupported presentation fields produce explicit capability warnings. A target
|
||||
part mismatch or protected-invariant change is a failed project.
|
||||
|
||||
Only a machine comparison with no hard failures moves the project to
|
||||
`completed`. The runner then automatically selects the next pending project.
|
||||
When every selected project is completed or skipped, the task moves to
|
||||
`completed`; any failed project keeps the task in `failed` until it is retried,
|
||||
skipped explicitly, or removed from selection while paused.
|
||||
|
||||
## 8. Logging and Diagnostics
|
||||
|
||||
Logging starts before the main window is constructed.
|
||||
|
||||
### Application Log
|
||||
|
||||
`application.log` is UTF-8, rotated at 5 MiB, and keeps five backups. It records:
|
||||
|
||||
- process start, version, executable path, OS, and storage paths;
|
||||
- database migration and recovery;
|
||||
- UI command start/completion;
|
||||
- scan roots and candidate counts;
|
||||
- task/project/rule IDs and state transitions;
|
||||
- probe source/destination hashes and validation outcomes;
|
||||
- subprocess command, exit code, stdout, and stderr when a subprocess is used;
|
||||
- handled exceptions with stable error IDs; and
|
||||
- uncaught main-thread, worker-thread, Qt callback, and shutdown exceptions with
|
||||
complete Python tracebacks.
|
||||
|
||||
### Task Evidence Log
|
||||
|
||||
Every meaningful task action appends one canonical JSON object to
|
||||
`events.jsonl` containing sequence, UTC timestamp, level, task ID, project ID,
|
||||
operation, state before/after, error ID, message, and structured details. The
|
||||
append is flushed before the UI reports completion.
|
||||
|
||||
The visible error dialog contains a concise Chinese explanation, the stable
|
||||
error ID, and actions to open the task log or evidence folder. Raw tracebacks
|
||||
remain in logs rather than being shown as the primary UI message.
|
||||
|
||||
## 9. Failure and Recovery
|
||||
|
||||
- A scan failure leaves the previous project list intact and records the error.
|
||||
- A database transaction failure does not update in-memory UI state as if it
|
||||
succeeded.
|
||||
- An invalid or stale probe file is rejected without consuming it.
|
||||
- A crash during execution is reconstructed from SQLite state and append-only
|
||||
events on the next start. `capturing_*` and `verifying` projects become
|
||||
paused with an interruption error; the operator chooses retry.
|
||||
- Retrying creates a new attempt number and never overwrites prior evidence.
|
||||
- A failed comparison never marks a project completed and never automatically
|
||||
saves or modifies the source project.
|
||||
|
||||
## 10. Module Boundaries
|
||||
|
||||
```text
|
||||
src/dx_productivity/trial_task_center/
|
||||
models.py immutable task/project/rule records and enums
|
||||
store.py SQLite schema, transactions, CRUD, and recovery
|
||||
scanner.py directory discovery adapter
|
||||
evidence.py probe freshness, identity, hashing, and atomic copies
|
||||
comparison.py before/after rule and invariant comparison
|
||||
runner.py one-project-at-a-time state machine
|
||||
logging_setup.py rotating logs, JSONL events, and exception hooks
|
||||
application.py application bootstrap and resource paths
|
||||
ui/
|
||||
main_window.py task navigation and workspace shell
|
||||
task_list.py task filters and CRUD actions
|
||||
project_table.py scan results, selection, states, and retry
|
||||
mapping_table.py mapping CRUD and validation display
|
||||
run_panel.py operator instruction and live log surfaces
|
||||
```
|
||||
|
||||
The UI depends on service interfaces, not SQLite or profile JSON directly.
|
||||
Comparison code has no Qt imports and is testable with fixture profiles. The
|
||||
runner changes task/project state only through the store transaction API.
|
||||
|
||||
## 11. Tests
|
||||
|
||||
Automated tests cover:
|
||||
|
||||
- task, mapping, and project CRUD plus soft-delete/restore;
|
||||
- mapping validation, including representative material numbers;
|
||||
- recursive `.prj` scanning, deterministic ordering, rescan, duplicates,
|
||||
missing paths, and selection preservation;
|
||||
- application and per-task logs, rotation configuration, exception hooks, and
|
||||
subprocess stdout/stderr capture;
|
||||
- probe freshness, exact project identity, atomic evidence copies, SHA-256, and
|
||||
rejection of stale/corrupt/wrong-project profiles;
|
||||
- before-match extraction, no-match handling, exact logical-identity
|
||||
correlation, target replacement, unrelated-object checks, and every protected
|
||||
invariant;
|
||||
- runner pause, resume, retry, crash recovery, automatic next-project advance,
|
||||
and completed-task transition;
|
||||
- PySide6 task/mapping/project CRUD interactions and disabled/enabled run gates;
|
||||
- responsive worker execution without blocking the Qt UI thread;
|
||||
- visual screenshots at 1100x700 and 1440x900 logical pixels with no clipped or
|
||||
overlapping text; and
|
||||
- a PyInstaller smoke test that starts the built EXE with an isolated temporary
|
||||
application-data root, opens the main window, writes a startup log, and exits
|
||||
cleanly.
|
||||
|
||||
No mock or automated test is accepted as proof that a DxDesigner 7.9.5 live
|
||||
route works. Live acceptance requires one complete disposable project copy, a
|
||||
before profile, a native replacement, an after profile, the comparison file,
|
||||
and the corresponding logs.
|
||||
|
||||
## 12. MVP Acceptance
|
||||
|
||||
The first executable is acceptable for user testing when it can:
|
||||
|
||||
1. start without a separate Python installation and write its startup log;
|
||||
2. create, edit, list, soft-delete, and restore tasks;
|
||||
3. scan a selected directory, select one or more `.prj` projects, and preserve
|
||||
the selection after rescan;
|
||||
4. create, edit, reorder, enable, and delete mapping rules;
|
||||
5. capture and correlate fresh before/after profiles for one selected project;
|
||||
6. guide the operator through the native replacement without UI automation;
|
||||
7. compare the selected project's before/after evidence and move it to
|
||||
Completed only when hard verification passes;
|
||||
8. retain failed projects with a visible error ID and retry action;
|
||||
9. automatically advance to the next selected project; and
|
||||
10. preserve complete application, task-event, evidence, and crash logs.
|
||||
|
||||
Parameter-style restoration and exact `Part Label -> Value` writes are the next
|
||||
phase. The trial task center records the evidence needed to implement and
|
||||
certify them without redesigning task storage or the UI.
|
||||
@@ -0,0 +1,254 @@
|
||||
# DxDesigner 7.9.5 现场验收记录
|
||||
|
||||
> **发布级别:仅评估(evaluation-only)。** 本清单只接受在可丢弃的真实 DxDesigner 7.9.5 项目副本和站点中央库映射上取得的人工现场证据。自动化、mock、静态检查或文档审阅都不得勾选任何项目。所有条目当前未执行。
|
||||
|
||||
## 批次元数据
|
||||
|
||||
- DxDesigner build:
|
||||
- Windows version:
|
||||
- Active project identity:
|
||||
- Central library identity or fingerprint:
|
||||
- Route profile:
|
||||
- Probe profile path / SHA-256:
|
||||
- Acceptance manifest path / SHA-256:
|
||||
- Tester:
|
||||
- Date:
|
||||
- Run/job directory:
|
||||
- Job ID:
|
||||
- Runtime manifest v2 path:
|
||||
- Evidence root:
|
||||
|
||||
每个条目都必须保留其自身的 fixture、mapping、observation(观察到的 API route/value/error)、唯一 evidence path、evidence file SHA-256、status、tester 和 ISO 日期;缺一项即不能勾选。记录错误时包括 API error number、source、description 和操作名。用于 `promote-profile` 的 `acceptance.json` 必须逐项对应这些记录,绑定原始 probe profile 字节、精确 version/build、操作员和中央库身份;不得直接编辑运行配置的 `live_acceptance`。
|
||||
|
||||
执行操作循环时,每一轮保留 `operator-step` JSON、`current-part-replacement.json` v2、`command.json`、返回的 `status.json`/`snapshot.json` 和相关事件。manifest 必须只有 `complete`、`current_action`、`current_command_id`、`current_project_id`、`format_version`、`projects` 六个字段;非完成状态的三项 current 绑定必须与唯一项目记录和 command 精确一致,完成状态必须为 `complete=true` 且三项均为 null。
|
||||
|
||||
## 执行前能力探测
|
||||
|
||||
本节是方案 A 的现场认证前置条件,必须按阶段顺序执行并保留原始证据。静态类型库、mock 和自动化测试只能帮助定位候选 API,均不构成 DxDesigner 7.9.5 现场认证;当前发布级别仍为 `evaluation-only`。
|
||||
|
||||
### 阶段 1:只读探针
|
||||
|
||||
1. 在真实 DxDesigner 7.9.5、可识别的测试项目和已映射的中央库上运行 `integration/dxdesigner795/PartReplaceProbe.vbs`;探针不得写入任何元件、参数、显示属性或连线字段。
|
||||
2. 保存探针产生的 `components[].parameter_probe` 原始输出及其 SHA-256。确认每个替换候选的每个参数均可记录 `Name`、`Value`、`TextString`、参数文字 `X`/`Y`、`Color`、`Font`、`Size`、`Orientation`、`Origin`、`Visible` 和 owner。
|
||||
3. 对每个候选元件,独立记录探针对 `Value`、`Value1`、`Part Number` 和 `Part Label` 的查询结果;不得用其中任一字段的推断结果替代实际查询。
|
||||
4. 每次查询都记录精确 API route、返回 type、value(或缺失状态)、error number/source/description、证据路径和证据文件 SHA-256。探针失败时记录失败的字段和 route,不得把未验证字段标为可用。
|
||||
|
||||
### 阶段 2:可丢弃副本上的 setter 认证(未来动作)
|
||||
|
||||
仅在阶段 1 完成后,才可在完整、可丢弃的项目副本上逐一认证 setter。本阶段是未来的人工现场动作;当前脚本尚未实现这些写入、回读和恢复步骤,不能将阶段 1 输出解释为写入能力已获认证。
|
||||
|
||||
1. 一次只动一个字段。仅对专用测试参数单独认证 `Value` 的哨兵值写入、独立回读和原值恢复;普通参数的 `Value` 绝不写入。除该哨兵试验和阶段 3 最终 `Part Label` 到 `Value` 的验证外,不允许写值。
|
||||
2. 再逐字段认证 `SetLocation(X,Y)`、`Color`、`Font`、`Size`、`Orientation`、`Origin` 和 `Visible` 的写入、独立回读和原值恢复。对于只读、不可写或类型不匹配的成员,记录实际拒绝结果,不得绕过或猜测。
|
||||
3. `TextString` 当前仅是读取和报告候选,除非实机和规格另行认证,不得作为必写 setter。owner 仅是参数实例归属/关联证据,不得作为 setter 测试或写入目标。
|
||||
4. 每个 setter 试验均记录目标对象身份、写前值和 type、写入值和 type、回读值和 type、恢复后值和 type、精确 route、error(如有)、证据路径及 SHA-256。恢复失败即停止该副本上的后续认证并保留该副本供调查。
|
||||
|
||||
### 阶段 3:人工原生替换验收
|
||||
|
||||
在已完成阶段 1 和适用阶段 2 认证的完整可丢弃副本上,人工执行 DxDesigner 原生 **Replace Part**,选择 **Library Wins**。不自动重连,且不以自定义字段写入替代原生替换。
|
||||
|
||||
1. 替换前快照每个参数的 `Name`、`Value`、`TextString`、文字 `X`/`Y`、`Color`、`Font`、`Size`、`Orientation`、`Origin`、`Visible` 和 owner;owner 只用于替换前后参数匹配和防止参数串位,不得写入。
|
||||
2. 原生替换后,仅为同名参数恢复阶段 2 已认证可写的显示属性;普通参数的值必须保留新库值,绝不从快照回写旧值。
|
||||
3. 独立查询替换后 `Part Label` 与 `Value`,验收 `Value` 精确等于新的 `Part Label`。同时验证同名参数的显示属性已恢复、普通参数值未被覆盖,以及原有连线、网络和引脚连接均未改变。
|
||||
4. 为替换、每次显示属性恢复和每项验收保存精确 route、type、value、error number/source/description、前后快照、证据路径和证据文件 SHA-256。普通参数显示字段继承失败仅记录 `parameter_style_inheritance_failed` 警告,不触发 Undo,也不单独阻止保存;未认证或不可用的字段必须禁用其自动恢复并显式报告。仅 `Part Label`/`Value` 缺失、歧义、不可写或回读不一致,以及硬不变量失败或连线变化,构成 hard failure。
|
||||
|
||||
## 环境、身份与库存
|
||||
|
||||
- [ ] **精确 7.9.5 build(exact 7.9.5 build)**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
- [ ] **活动项目身份(active-project identity)**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
现场步骤:分别验证错误活动项目、已完成 manifest、陈旧 project ID、command ID、action 和 command project ID 均在 bridge 调用前被拒绝;初始 `open_project` 仅允许无活动项目,其他动作要求规范路径精确匹配。
|
||||
|
||||
- [ ] **脏项目拒绝(dirty-state rejection)**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
- [ ] **完整库存(full inventory)**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
- [ ] **精确组选择(exact group selection)**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
## 原生替换路线与目标
|
||||
|
||||
- [ ] **原生对话框路线或人工回退(native dialog route or manual fallback)**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
- [ ] **正确目标(correct target)**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
- [ ] **错误目标(wrong target)**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
- [ ] **兼容单单元替换(compatible single-unit)**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
- [ ] **兼容多单元替换(compatible multi-unit,站点相关时必需)**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
## 不变量与拒绝路径
|
||||
|
||||
- [ ] **原点不匹配(origin mismatch)**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
- [ ] **引脚号/数量不匹配(pin-number/count mismatch)**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
- [ ] **网络改变(changed net)**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
- [ ] **无关对象保护(unrelated-object protection)**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
- [ ] **陈旧库存(stale inventory)**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
## 恢复、保存与继续
|
||||
|
||||
- [ ] **备份/恢复(backup/restore)**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
- [ ] **Undo**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
- [ ] **关闭且不保存(close without save)**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
- [ ] **持久化保存验证(persisted-save verification)**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
- [ ] **多项目恢复继续(multi-project resume)**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
现场步骤:在待处理命令处输入 `Q`,记录 manifest v2 与 command ID;以 `-ResumeJob` 指向同一绝对作业目录恢复,确认没有新建作业或重读原 Mapping/Projects/Certifications,同一待处理命令 ID 不变,已 `verified_saved` 项目不重跑,后续命令每次只推进一个项目/动作,最终 manifest 原子变为完成状态。
|
||||
|
||||
## 保存后的外部检查
|
||||
|
||||
- [ ] **Packager**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
- [ ] **ERC**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
- [ ] **网表比较(netlist comparison)**
|
||||
- Fixture: `________`
|
||||
- Mapping: `________`
|
||||
- Observed API route/value/error: `________`
|
||||
- Evidence path: `________`
|
||||
- Tester: `________`
|
||||
- Date: `________`
|
||||
|
||||
## 结论
|
||||
|
||||
所有必需项目均须以真实现场证据逐项勾选;若站点不使用多单元元件,记录该适用性判断及证据,但不要把自动或 mock 证据当作通过。任何未勾选项、未解决阻断项或缺失证据都使发布保持 `evaluation-only`。
|
||||
@@ -0,0 +1,30 @@
|
||||
# 自动启动 DxDesigner(2026.09.06-R7)
|
||||
|
||||
> 连续队列会在原理图精简备份后自动枚举多图页工程,并逐页打开明确绑定的原理图名和页号。精简备份排除 PCB、CES、历史工程备份和运行日志。下文“只处理单页”的内容是 R7 历史边界,不再适用于当前连续队列;人工单步流程仍只操作当前活动页。
|
||||
|
||||
点击“开始自动替换”后,工具先从已确认的队列项读取工程路径,再执行以下准备流程:
|
||||
|
||||
1. 检查工程文件存在且为 `.prj`,拒绝不存在或重复的确认项,不启动 CAD。
|
||||
2. 已有一个 DxDesigner 实例时复用;进程存在但 COM 尚未注册时最多等待 30 秒,不再启动第二个实例。
|
||||
3. 未运行时,通过 32 位 COM 注册自动启动 `Viewdraw.Application` 并显示窗口。仍需要本机安装、正确注册和可用许可证,不是脱离 CAD 的无界面替换。
|
||||
4. 未打开工程时调用 `Application.OpenProject`,并回读路径确认。已有其他工程时停止,不擅自关闭、切换或保存它。
|
||||
5. 使用已有活动图页;没有活动图页且工程只有一张可用图页时自动打开并校验页名。有多页但未选页时提示选择,绝不任取一页并假报整工程完成。
|
||||
6. 准备成功后才进入原有当前页替换、Value 策略和连接校验。
|
||||
|
||||
启动或打开工程失败发生在替换前,不写入该项的替换失败状态,可在排除原因后重试;真实执行超时或变更结果不确定仍保留保护锁,不自动清理。
|
||||
|
||||
日志包含 `session_startup`、`launch_designer`、`wait_designer`、`check_project`、`open_project`、`open_sheet`、`session_ready`,以及组件和引脚查询阶段。提示保留原始错误,不再把启动失败与替换失败混成一句“软件没打开”。
|
||||
|
||||
## 本轮边界
|
||||
|
||||
- 本轮修复自动启动、打开目标工程及单图页准备,不等于已实现整工程逐页自动批处理。
|
||||
- 仍然是每次点击处理一条当前页规则;不自动遍历所有页,不自动保存或关闭工程。
|
||||
- 不同时打开多个工程。已有其他工程时,由用户先保存并关闭,避免丢失未保存内容。
|
||||
- 执行期间不要编辑、切换或关闭正在处理的图页;工具不控制系统鼠标。
|
||||
- 自动化回归测试使用替身接口,不能替代本机真实 CAD 与许可证环境下的验收。
|
||||
|
||||
## R7 图页校验脚本修复(2026-09-06)
|
||||
|
||||
修复自动打开单图页后报错 438“对象不支持此属性或方法”:页码校验改为本机 7.9.5 类型库支持的 `View.Block.SheetNum`,不再访问不存在的 `View.SheetNumber`。校验仍会拒绝错误图页,不跳过身份检查。
|
||||
|
||||
这是 R7 外置脚本修复,主程序标题仍显示 R7。下次执行会重新复制部署目录中的脚本;无需清空任务或手动修改执行队列。测试替身同步按真实接口修正,并补充类型库契约及错误页码回归测试。
|
||||
@@ -0,0 +1,39 @@
|
||||
# 连续队列(1.0.0)
|
||||
|
||||
## 执行与提示
|
||||
|
||||
点击“连续执行队列”,确认剩余工程、规则和 Value 策略后,程序先只读枚举全部原理图页并固定清单,再按“工程 → 图页 → 规则”串行处理,不再每执行一项就等待再次点击。
|
||||
|
||||
- 旧 Part Number 未命中:黄色提示“未命中跳过”,不作替换,自动继续。未命中不等于替换成功。
|
||||
- 旧器件命中:执行原生替换,恢复实例信息,保存并关闭工程,再重新打开核验;核验和关闭完成后才处理下一项。
|
||||
- 目标器件不可用、Part Label 回读失败、保存或核验失败:记录工程、图页、位号和原因,关闭且不保存该失败工程,再继续后续项。结果状态不确定时才停止并要求核验。
|
||||
- 勾选“替换后将 Part Label 写入 Value”才额外改写 Value;未勾选不读取 Part Label,也不额外改写或创建 Value。旧 Value 已存在时,两种模式都继承其位置和显示样式。
|
||||
- 旧 Value 含独立的 `/NC` 段时,两种模式都会把 `/NC` 同步到替换后的 Value 且不重复追加;目标没有 Value 时创建 `/NC` 并继承旧 Value 样式。日志按位号记录替换与同步;工程中的位号本来为空时改用稳定的 `UID=...`,不会输出无法追踪的空白标识。
|
||||
|
||||
## 安全边界
|
||||
|
||||
连续模式支持多图页工程。每张图页都是独立、可恢复的队列项,快照、状态、暂停位置和错误均绑定到明确的原理图名及页号。图页清单在替换前固定;执行期间若新增、删除或重命名图页,程序会在下一次写入前停止,避免遗漏或处理错页。
|
||||
|
||||
程序不会接管已经手动打开的工程;请先自行保存需要保留的编辑并关闭工程。可以连接没有打开工程的 DxDesigner 会话,未运行时会自动启动。
|
||||
|
||||
每个工程只在其第一项实际替换前建立一次并校验原理图精简备份;已确认未命中的工程不会创建备份。同一工程的多个图页、多个规则,以及暂停后继续执行,均复用当前队列证据中的同一份备份,不重复复制。精简备份保留 `.prj`、`.dxp`、原理图数据库 `database/icdb.dat`、HDL、符号和相关配置,排除 `PCB`、`CES`、`ProjectBackup`、工程内 `backups`、日志目录及 `database/cdbsvr` 等运行生成内容。每份备份包含 `.dxpartreplace-backup.json`,记录文件范围、大小和 SHA-256。只读枚举完成后,程序会确认工程仍可安全处理,再在首次写入前备份命中工程;若工程在枚举期间发生变化,则停止而不猜测继续。发布版备份位于 EXE 同目录的 `data/quick-run/batch-backups/project-*`,当前队列完成或归档后随队列证据保留。
|
||||
|
||||
精简备份失败时默认停止,且尚未打开工程或执行替换。界面此时显示“忽略备份失败并继续”;只有再次确认工程已保存且另有独立副本后,才能对当前一次队列授权继续。程序仍会尝试备份其余工程,并把每个无备份继续的工程、原错误编号和“不可保证回滚”写入任务事件。该授权不保存为默认选项,下次执行仍恢复为备份失败即停止。备份不是自动回滚;不要通过删除保护文件绕过结果不确定状态。
|
||||
|
||||
同一时刻只打开一个工程,不同时堆积多个工程。为确认落盘,命中项有保存、关闭、回读核验的额外耗时。执行时不要手动切换或修改 CAD 工程;发现工程上下文变化时程序停止,而不是猜测继续。
|
||||
|
||||
“完成当前项后暂停”不会强行打断 CAD 写入;当前图页规则项完成后不启动下一项。再次确认可从记录的工程、图页和规则继续,不重复已完成页面。执行中关闭任务中心同样先请求安全暂停,需要等当前项结束后再关闭。
|
||||
|
||||
已经处理过步骤的队列在安全暂停或执行报错后会持久保存“已暂停”状态,不再留在“运行中”阻止正常管理。暂停任务可移至“已删除”并恢复;恢复后重新确认,从下一项继续。任务进入“已删除”后也可直接彻底删除任务记录,不受队列执行锁限制;工程文件、诊断日志和执行证据仍保留。
|
||||
|
||||
自动队列不允许混用人工流程的采集、跳过、重试或继续操作。执行期间锁定队列输入;本轮结束且存在失败项时,任务保留在“进行中”,可修改规则、Value/NC 选项和工程勾选后点击“重试失败项”。重试队列不重复处理已成功工程。
|
||||
|
||||
历史结果会区分“已保存”和“尚未确认保存”,全未命中的工程显示“未命中跳过”。日志中的 WARNING 是提示级别,不再作为自动停止条件;是否停止由实际执行状态决定。
|
||||
|
||||
进度展示文件被短暂占用时,不会中断实际执行;监控仍在内存中检查相关联的有效进度。控制握手或实际监控故障仍会停止并保留待核验保护,错误提示不再将这些故障一律伪装成超时。
|
||||
|
||||
## 长期运行保留策略
|
||||
|
||||
`quick-run\quick-part-replace.log` 超过 5 MiB 后保留 3 个轮转备份,单个任务的 `events.jsonl` 超过 5 MiB 后保留 5 个轮转备份。`quick-run-history` 只清理由程序生成且名称可验证的 `batch-*`、`recovery-*`、`sheet-discovery-*` 和 `obsolete-*` 目录;未知目录、链接目录和当前活动的 `quick-run` 证据不会删除。
|
||||
|
||||
历史清理在新的准备、批量或恢复操作进入互斥执行区后运行。默认至少保留最新 10 份历史;其余记录在超过 30 天、总数超过 100 份或总容量超过 5 GiB 时从最旧开始删除。由于最近 10 份始终保留,单个超大工程可能使实际容量暂时高于 5 GiB,此时应人工转存需要长期留档的证据。
|
||||
@@ -0,0 +1,22 @@
|
||||
# R9:核验并恢复中断任务
|
||||
|
||||
“核验并恢复中断任务”不是删除保护锁后重跑。存在当前任务的 `uncertain.flag` 时显示恢复按钮,并禁用普通替换按钮;恢复需要单独确认。
|
||||
|
||||
## 恢复条件
|
||||
|
||||
- 任务、工程、规则、Value 策略必须与中断队列一致。
|
||||
- 必须有可读取的替换前快照和与其 SHA-256、工程、图页、器件 UID、料号绑定的原生执行证据。
|
||||
- 多个未确认步骤、缺失证据、混合新旧器件、器件 UID 变化或连接异常均拒绝自动恢复。
|
||||
- 恢复要求新的 CAD 会话,以避免接管状态不明的旧撤销事务。用户先处理需要保留的未保存修改并关闭 DxDesigner,工具再自动启动并打开目标工程,不替用户选择保存或丢弃。
|
||||
- 恢复只核验中断时绑定的那一张图页,不扫描或改写其他页;恢复完成后,正常连续队列会从下一条未完成的工程、图页和规则继续。
|
||||
|
||||
## 处理结果
|
||||
|
||||
1. 全部为目标器件且属性、位置和连接通过核验:只补记本项完成,不写 CAD,也不再次原生替换。
|
||||
2. 全部为旧器件,位置、属性集合、原始属性值和连接均与快照一致:生成新执行编号,保留旧快照证据,等待用户确认后重新执行,不自动替换。
|
||||
3. 全部为正确的目标器件,连接通过,但有明确的属性或位置恢复差异:只补做快照恢复及回读校验,使用新的独立撤销事务;遵循原 Value 策略,不再次原生替换。完成后仍需用户保存。
|
||||
4. 读取异常或无法证明安全:保留保护状态,不把 COM 读取失败当成属性差异来触发写入。
|
||||
|
||||
恢复前将原理图精简备份及执行证据复制到 `quick-run-history/recovery-随机编号` 并校验哈希。精简备份排除 PCB、CES、历史工程备份和运行日志,并写入文件清单;恢复执行器使用独立目录。结果必须匹配当前步骤、退出码正常,且原始证据未变化,才能提交状态。保护文件被归档为 `resolved-uncertain.flag`,不是无证据删除。提交异常保留或重建保护状态。
|
||||
|
||||
此功能不自动保存、不自动跳过失败工程,不意味着多工程批量验收已完成。工程中的外部库仍使用原配置路径,不由恢复流程修改。
|
||||
@@ -0,0 +1,169 @@
|
||||
# DxDesigner 7.9.5 元件替换操作指南
|
||||
|
||||
> **发布级别:仅评估(evaluation-only)。** 在现场 7.9.5 验收清单全部取得人工证据前,脚本、运行目录和报告均为评估产物。只能对可丢弃的完整项目副本操作,绝不用于唯一副本、生产库或生产发布。
|
||||
|
||||
本工具执行的是 DxDesigner 原生的库元件替换,不是修改 `Part Number` 属性、复制属性、改写设计文件或自动重新连线。生产写入路径固定为原生 Replace Part;目标元件、符号、引脚和库控制属性必须来自中央库的 `Library Wins` 选择。`ccomp`、`ChangeComponentPreserveRefdes`、直接文件编辑和键盘/坐标自动化均不是允许的操作路径。
|
||||
|
||||
## 1. 上线前边界
|
||||
|
||||
- 支持基线仅为 DxDesigner/Expedition Enterprise `7.9.5`。新版本不因本指南而获得支持。
|
||||
- 每次操作使用一个完整、可恢复的项目副本和该副本对应的中央库映射。先完成 [现场验收清单](../testing/dxdesigner-795-part-replacement-live.md)。
|
||||
- 不要绕开拒绝条件。缺少项目身份、完整库存、精确选择、保护字段、引脚或网络证据时,必须停在 `blocked`。
|
||||
- AI 只能阅读库存、差异、Packager/ERC/网表和人工记录并给出建议;AI 不能改变快照、事件日志、硬校验、保存权限、认证或备份,也不能批准连通性改变或未认证的映射。
|
||||
|
||||
## 2. 安装、配置文件和卸载
|
||||
|
||||
安装根目录必须包含完整交付包,包括 `integration\dxdesigner795\PathSafety.ps1`、`PartReplacementContract.ps1`、`MenuAdd.vbs`、`MenuRuntime.vbs`、`PartReplaceMenuRuntime.vbs`、`BridgeCommon.vbs`、`PartReplaceProbe.vbs` 和 `PartReplaceBridge.vbs`。Python 可执行文件必须恰好为 Python `3.12`,并且能导入 `dx_productivity`。兼容性配置文件是现场 probe 产生并审阅过的 JSON,不要手工改写。未经现场验收的 probe 配置可以用于本指南限定的评估和人工回退,但不能授权自动写路线。
|
||||
|
||||
以普通用户 PowerShell 运行(参数名和路径必须准确):
|
||||
|
||||
```powershell
|
||||
& "C:\DxProductivity\integration\dxdesigner795\Install.ps1" `
|
||||
-InstallRoot "C:\DxProductivity" `
|
||||
-PythonExecutable "C:\Python312\python.exe" `
|
||||
-CompatibilityProfile "C:\Qualification\compatibility-profile.json"
|
||||
```
|
||||
|
||||
`Install.ps1` 会验证 Python 版本和导入、验证并原子部署配置文件到 `C:\DxProductivity\runs\compatibility-profile.json`、写入 `%LOCALAPPDATA%\DxProductivity\settings.json`,并在当前用户范围设置 `DXTOOLS_HOME=C:\DxProductivity`。先使用同一命令加 `-WhatIf` 核对 `InstallRoot`、`PythonExecutable`、`CompatibilityProfile`、`SettingsPath`、`RunRoot` 和 `DXTOOLS_HOME`;`-WhatIf` 不写入配置或环境变量。
|
||||
|
||||
在 DxDesigner 启动导入 `C:\DxProductivity\integration\dxdesigner795\MenuAdd.vbs`。该入口会加载 `MenuRuntime.vbs`,并且只维护一个带标签的 `Dx Productivity` 菜单。确认可见的菜单项为:
|
||||
|
||||
- `Part replacement probe`
|
||||
- `Inventory current project`
|
||||
- `Continue part replacement`
|
||||
|
||||
### 配置文件部署与发现审阅
|
||||
|
||||
安装只接受部署后的 `runs\compatibility-profile.json`;`Start-PartReplacement.ps1` 不接受另一份运行配置文件或另一个运行根目录。审阅 probe JSON 中的 `dxdesigner.version`、`dxdesigner.build`、`project.identity`、`project.dirty`、`interfaces`、`routes`、`api_errors`、`safety` 和 `live_acceptance`。只有 `production_replace_route` 为 `native_replace_part`,并且所需的接口和路线有可追溯现场证据时,才可继续评估。
|
||||
|
||||
现场清单全部完成后,由站点负责人生成 `acceptance.json`。它必须逐项绑定 fixture、mapping、observation、tester、日期、唯一 evidence path 和对应文件的 SHA-256,并绑定原始 probe 配置的 SHA-256、精确 `7.9.5` version/build、操作员和中央库身份。用公开晋级命令验证并原子部署,不能直接把 `live_acceptance.checked` 改为 `true`:
|
||||
|
||||
```powershell
|
||||
& "C:\Python312\python.exe" -m dx_productivity --json promote-profile `
|
||||
"C:\Qualification\probe-profile.json" `
|
||||
"C:\Qualification\acceptance.json" `
|
||||
"C:\DxProductivity\runs\compatibility-profile.json"
|
||||
```
|
||||
|
||||
当前清单仍全部未勾选,因此当前交付不得执行或声称已经通过这一步,发布分类仍为 `evaluation-only`。
|
||||
|
||||
使用发现功能时,生成的候选列表不自动加入作业:
|
||||
|
||||
```powershell
|
||||
& "C:\DxProductivity\integration\dxdesigner795\Start-PartReplacement.ps1" `
|
||||
-DiscoveryRoot "D:\Disposable\Projects"
|
||||
```
|
||||
|
||||
它写入 `C:\DxProductivity\runs\discovered-projects.txt`。逐行审阅、删除不属于本次批次的候选项目并确认中央库映射后,另存为本次的 `projects.txt`。发现只是便利功能;不得把未审阅发现结果直接用于替换。
|
||||
|
||||
### 卸载
|
||||
|
||||
没有交付 `Uninstall.ps1`,因此不存在可宣称的公开卸载命令。完成或放弃所有评估作业后:在 DxDesigner 中移除启动导入的 `MenuAdd.vbs`;删除当前用户环境变量 `DXTOOLS_HOME`;仅在按保留制度导出/保存 `runs` 中的作业证据、备份清单和报告之后,再由桌面软件管理员移除安装根目录及 `%LOCALAPPDATA%\DxProductivity\settings.json`。不要删除仍可能用于恢复的作业备份;没有受控恢复或保留批准时,交接给站点管理员。
|
||||
|
||||
## 3. 输入和不可变作业
|
||||
|
||||
`replacement.csv` 必须是 UTF-8 CSV,且仅有这两个列名:
|
||||
|
||||
```csv
|
||||
old_part_number,new_part_number
|
||||
OLD-001,NEW-001
|
||||
OLD-002,NEW-002
|
||||
```
|
||||
|
||||
工具会去除前后空白、保留展示拼写、按大小写不敏感方式比较。它拒绝空值、重复旧值(包括只差大小写)、旧新相同、链式映射和循环映射。不要写元件名、符号名、属性、引脚或描述;替换目标的唯一键是中央库 `Part Number`。
|
||||
|
||||
`projects.txt` 是 UTF-8 文本,每行一个**绝对**项目定义路径,例如:
|
||||
|
||||
```text
|
||||
D:\Disposable\Board-A\Board-A.prj
|
||||
D:\Disposable\Board-B\Board-B.prj
|
||||
```
|
||||
|
||||
路径会规范化但不改变磁盘大小写。重复、缺失、嵌套发现重复或不支持的项目标记会在库存前报告。短项目名不构成身份;报告中的项目 ID 来自规范化路径。
|
||||
|
||||
每一个 old/new 对必须先在代表性的、关闭的、可丢弃完整项目副本上完成认证:记录替换前后完整快照,使用原生 Replace Part + `Library Wins`,检查第 6 节硬不变量,并运行 Packager、ERC 和网表检查。认证应由站点流程生成/保管 `certifications.json`,其证据必须绑定 old/new `Part Number`、中央库身份/版本或目标指纹。当前交付**没有**公开“创建认证”CLI;不要伪造 JSON 或把内部 Python API 当作生产步骤。无认证映射只能排除或交由站点认证负责人完成可丢弃试验。
|
||||
|
||||
创建评估作业:
|
||||
|
||||
```powershell
|
||||
& "C:\DxProductivity\integration\dxdesigner795\Start-PartReplacement.ps1" `
|
||||
-Mapping "D:\Qualification\replacement.csv" `
|
||||
-Projects "D:\Qualification\projects.txt" `
|
||||
-Certifications "D:\Qualification\certifications.json"
|
||||
```
|
||||
|
||||
脚本在 `C:\DxProductivity\runs\part-replace-<GUID>` 创建新作业,把本次输入复制为不可变记录,然后立即进入显式操作循环。每轮只调用一次 `operator-step`:至多消费一个已关联的 bridge 结果,再至多发布一个后续命令。当前命令以 manifest v2 写到 `C:\DxProductivity\runs\current-part-replacement.json`;其 `current_project_id`、`current_action` 和 `current_command_id` 必须同时与唯一项目记录及 `command.json` 精确一致。不要编辑 manifest、mailbox 或事件文件来推进作业。
|
||||
|
||||
控制台每轮显示 `CurrentProject` 和 `CurrentAction`;有人工步骤时还显示 `ManualRoute` 和 `Instruction`。`operator-step` 对未完成动作返回退出码 `4`,这是启动器已处理的正常“等待操作员”状态,不是成功或失败。完成整批后,manifest 会被原子改写为 `complete=true`,三个 current 绑定均为 `null`。记录输出的 `job_id`、作业目录和输入哈希,并让该控制台保持运行直到完成或明确暂停。
|
||||
|
||||
在提示处输入 `Q` 会保留当前作业、命令和 manifest,并打印准确的暂停作业路径。恢复时只传该绝对作业目录;不要再次传 Mapping、Projects、Certifications 或 DiscoveryRoot,也不要重新创建作业:
|
||||
|
||||
```powershell
|
||||
& "C:\DxProductivity\integration\dxdesigner795\Start-PartReplacement.ps1" `
|
||||
-ResumeJob "C:\DxProductivity\runs\part-replace-<GUID>"
|
||||
```
|
||||
|
||||
恢复入口只调用现有作业的只读 `status` 来重建项目 allowlist,然后复用同一个 `operator-step` 循环。它拒绝相对路径、部署 `runs` 以外或非直接子目录、reparse path、损坏/不匹配的 status、重复项目和相对项目路径。已经 `verified_saved` 的项目不会重跑;未完成的同一命令保持原 command ID。
|
||||
|
||||
## 4. 库存、影响审阅和项目队列
|
||||
|
||||
严格按控制台当前轮次操作,不要自行跳到另一个项目或动作:
|
||||
|
||||
1. 当 `CurrentAction=inventory` 时,打开 `CurrentProject` 指向的正确可丢弃副本,确认已保存且非脏,然后选择 `Dx Productivity` -> `Inventory current project`。
|
||||
2. 其他所有 `CurrentAction` 均选择 `Dx Productivity` -> `Continue part replacement`。初始 `open_project` 要求当前没有活动项目;其他初始动作要求活动项目规范路径精确等于 `CurrentProject`。
|
||||
3. 菜单返回后,在控制台按 Enter。启动器只消费与当前 project/action/command ID 完整关联的状态;若状态尚未完成,它会再次发布同一绑定而不会生成第二个命令。
|
||||
4. 若下一轮显示 `ManualRoute`/`Instruction`,先按指令完成原生人工动作,再选择 `Continue part replacement` 让 bridge 验证结果,然后回到控制台按 Enter。人工打开的项目必须成为精确的当前项目;人工关闭后可以没有活动项目。
|
||||
|
||||
菜单运行时拒绝已完成 manifest、零个或多个当前项目记录、命令 schema 错误、陈旧 project/action/command ID、越出 `DXTOOLS_HOME` 的 bridge 路径以及错误的活动项目。出现拒绝时不要改 JSON 绕过;保留文件并调查当前绑定。
|
||||
|
||||
必须为**每一个**已启用项目完成库存,才能进入 Apply。库存包括逻辑元件和所有已放置单元、`Part Number`、`RefDes`、层级/图纸、符号、门/槽、原点/位置/旋转/镜像、属性、引脚号/名/位置/网络以及项目指纹。无法取得唯一逻辑身份或任何受保护状态/引脚/网络证据,即为阻断问题。
|
||||
|
||||
审阅作业目录的 `reports\impact.csv` 和静态 `reports\summary.html`:影响矩阵的每一格给出项目、旧/新 Part Number、逻辑元件数、放置单元数和问题。审阅无匹配、过时/缺失 `Part Number`、重复 `RefDes`、多单元、未验证数据和所有硬问题。只启用通过认证且影响可接受的映射;没有“继续忽略”选项。
|
||||
|
||||
库存阶段覆盖 `projects.txt` 中每一个启用项目后,控制器才会进入 Apply。若某个项目没有任何映射命中,它会通过明确的 `no_changes_required` 事件完成,不会伪造 Apply 或 Save。活动项目身份不精确匹配时,停止,不要在当前项目上尝试。
|
||||
|
||||
## 5. Apply:每个项目/映射对
|
||||
|
||||
在开始每个项目之前,操作循环发布 `close_project`。bridge 先证明完整快照等于可信库存并证明项目非脏,再自动关闭或要求 `manual_close_project`;只有相关的关闭证据返回后,控制器才把完整项目树复制到作业 `backups` 区并验证文件大小和内容哈希清单。随后循环发布 `open_project`,自动打开或要求 `manual_project_open`,并重新核验项目身份和库存指纹。若项目在库存后发生变化,它是 stale,必须重新库存、重新审阅影响,不能继续旧选择。
|
||||
|
||||
对每个有命中的已启用映射,工具应显示旧/新 `Part Number` 和 `expected_count`,并且只选择该映射的准确逻辑元件组。操作员必须在任何原生对话框中再次核对显示的目标 `Part Number` 与预期数量。
|
||||
|
||||
1. 在可用并经 probe 与现场证据验证的路线中,bridge 精确选择命令中的逻辑组,写入 `native_dialog_opening` 状态,然后打开原生 Replace Part 对话框;仍由操作员选择精确目标、`Library Wins` 并确认。bridge 使用已验证的完成观察路线,确认对话框动作完成后才导出快照。
|
||||
2. 若精确选择路线未验证,状态为 `manual_exact_selection`。按 `Instruction` 只选择显示的完整逻辑组,再选择 `Continue part replacement`;bridge 会先复核选择集合,然后进入原生对话框路线或下一人工步骤。
|
||||
3. 若原生对话框路线未验证,状态为 `manual_native_dialog`。保留精确选择,不要改选其他对象。手动执行 `Edit -> Replace Symbol`,选择 `Replace part`,在 DxDataBook 中找到显示的精确新 `Part Number`,选择 `Library Wins`,只对当前选择组确认一次。
|
||||
4. 原生对话框关闭后,选择 `Dx Productivity` -> `Continue part replacement`。菜单只在先前状态与当前命令完整关联时继续 `continue_after_manual_dialog`,并导出新的完整快照;不要以等待窗口标题、固定延时或重复菜单点击取代该步骤。
|
||||
|
||||
每个项目/映射对只确认一次原生 Replace Part;不逐个元件确认。取消发生在已验证保存之前会让当前项目保持未保存,并将作业记录为中断。
|
||||
|
||||
## 6. 即时验证、失败和保存门
|
||||
|
||||
原生替换后,立即检查:新 `Part Number` 等于请求值;命中和替换的逻辑元件数准确;`RefDes`、层级、已放置单元、原点、位置、旋转、镜像、门/槽、引脚号集合、引脚坐标和每个 `RefDes + pin number` 的网络身份均未变化;并且没有无关逻辑元件变化。任何新增、删除、改名或重新连接的引脚均失败。库控制的符号、引脚名和属性可能按 `Library Wins` 变化,应在差异报告中审阅,但不得以此掩盖保护字段失败。
|
||||
|
||||
若选择了错误目标或任一硬不变量失败:立即停止该项目。操作循环会发布与失败 Apply 使用同一 command ID 的 `undo`;只在配置文件已验证的路线中执行一次原生 Undo,或按 `manual_native_undo` 指令手工 Undo 后再次选择 Continue。bridge 和控制器都要把恢复快照与替换前快照逐项比较。Undo 不可用或不能精确恢复时,循环发布 `close_without_save`(或 `manual_close_without_save`),再核对磁盘树仍匹配 Apply 前备份。不要在不确定的内存状态继续,也不要通过移动、重画导线或编辑属性来“修复”校验。
|
||||
|
||||
所有映射通过后,在项目差异摘要处审阅库控制和非阻断属性变化。操作循环发布 `save`;只有在该轮确认 `Save and continue` 才执行,自动路线不可用时按 `manual_native_save` 完成原生 Save 并再次选择 Continue。bridge 必须确认项目非脏并重新枚举,控制器再把持久化快照与已硬验证的内存快照比较。随后循环按固定顺序发布 `packager`、`erc`、`netlist`,每项都要求现场验收过的 API 路线返回明确成功、相关 bridge 快照完整且设计未变化;全部通过后项目才进入 `verified_saved`。这些外部检查的自动路线未经现场验收时,停止并保留同一作业及命令,先按现场清单取得证据并用 `promote-profile` 部署已验收配置,再恢复操作循环;人工布尔确认或“未运行”都不能作为通过证据。
|
||||
|
||||
## 7. 状态、恢复、报告和隔离
|
||||
|
||||
项目持久状态依次为 `inventory_pending`、`inventory_complete`、`apply_pending`、`applying`、`awaiting_save_confirmation`、`awaiting_external_checks`、`verified_saved` 或 `blocked`。事件日志是追加式记录,状态文件只是投影。`verified_saved` 不应重做;处在 `applying`、`awaiting_save_confirmation` 或未知状态的项目,在继续前必须重新库存,并相对备份进行 reconcile。一个 `blocked` 项目不阻止其他项目继续,但整批报告不得描述为完全成功。
|
||||
|
||||
可查看 `reports\impact.csv`、`reports\differences.json` 和 `reports\summary.html`。HTML 中的 `SUCCESS` 只表示所有项目都处于 `verified_saved`;有完成与阻断混合时为 `PARTIAL`,并非批次成功。`differences.json` 区分硬问题和非阻断属性差异。报告同时给出输入哈希、项目状态、认证身份/目标指纹、外部检查、备份路径、恢复动作以及 AI 建议附件。AI 附件仅供参考,不能覆盖状态或验证结论。
|
||||
|
||||
收到异常、损坏或陈旧 mailbox 证据时,运行存储会把不可信文件隔离到作业 `history` 下并写事件。隔离不是通过,也不是可手动删除的恢复信号;保留其路径和事件记录,交给操作负责人调查后再创建受控的新命令/重新库存。
|
||||
|
||||
规范要求的恢复前提为:目标项目已有相关 `close_without_save` 关闭证据;目标规范路径与作业记录精确匹配;备份清单验证通过。若关闭后的磁盘树仍匹配备份,控制器可以直接进入受约束的 reconcile;否则暂停启动器,由站点恢复负责人运行公开命令:
|
||||
|
||||
```powershell
|
||||
& "C:\Python312\python.exe" -m dx_productivity --json restore `
|
||||
"C:\DxProductivity\runs\part-replace-<GUID>" "<project_id>"
|
||||
```
|
||||
|
||||
`restore` 会先把失败磁盘树完整保留到返回的 `recovery_path`,再复制已验证备份并复核结果;任何前提缺失都会拒绝。只有 `restore_verified`、`close_without_save_verified` 或精确 `undo_verified` 等相关恢复证据才能授权无参数 `reconcile JOB PROJECT_ID`,reconcile 随后仍要求重新打开和重新库存。不要从 Python 内部 API、资源管理器覆盖或临时脚本拼凑恢复,也不要删除备份、失败树或隔离证据。
|
||||
|
||||
恢复/调查命令完成后,用上面的 `-ResumeJob` 重新进入同一操作循环;不得用原 Mapping/Projects/Certifications 创建一个外观相似的新作业来代替恢复。
|
||||
|
||||
## 8. 现场证据与支持交接
|
||||
|
||||
每次试验附上:确切 DxDesigner build、Windows 版本、活动项目规范路径、中央库身份/指纹、route profile、映射、备份清单、前后/保存后快照、状态/事件文件、差异报告、外部检查输出、操作员和日期。自动化或 mock 测试只能证明回归覆盖,不能把 [现场验收清单](../testing/dxdesigner-795-part-replacement-live.md) 的项目标为通过。
|
||||
|
||||
在所有未勾选项目取得可追溯现场证据前,保持评估分类,继续只使用可丢弃副本。
|
||||
@@ -0,0 +1,13 @@
|
||||
# 任务彻底删除(R13)
|
||||
|
||||
普通任务的“删除”仍然是移入“已删除”,可以恢复。要永久移除任务,请在左侧筛选“已删除”,选择任务,点击“彻底删除”,阅读确认框后再次点击“彻底删除”。确认框默认选中“取消”,Esc 也会取消。
|
||||
|
||||
彻底删除会在一个数据库事务中删除任务、工程关联、替换规则、尝试记录和迁移恢复记录。关联清理失败时整个事务回滚,不留下半删数据;成功后不能通过“恢复”找回,原任务名称可以重新使用。
|
||||
|
||||
**范围不是磁盘安全擦除。** 不删除实际工程/原理图文件,不回滚已经做过的 CAD 修改。诊断日志、执行证据、已有备份保留,确认框会明确说明。这些文件用于排查历史操作,不代表任务还留在“已删除”列表。
|
||||
|
||||
只有已经移入“已删除”的任务可以彻底删除。确认后不再受全局队列执行锁、未完成队列或结果未确认状态限制,任务记录会直接删除;其他任务不受影响。执行证据和保护文件仍保留用于排查,不会被此操作当作普通任务数据一并清除。
|
||||
|
||||
此功能不增加数据库版本,也不会在更新或启动时自动清空“已删除”。必须由用户逐个明确确认。若在确认期间其他窗口恢复了任务,后台会拒绝此次永久删除。
|
||||
|
||||
R6 同时修正了查看已删除且有已完成队列的任务时,错误地尝试更新任务状态的问题。
|
||||
@@ -0,0 +1,23 @@
|
||||
# R8:进度式超时与分阶段引脚索引
|
||||
|
||||
## 改变的行为
|
||||
|
||||
- 150 秒不再是整个任务的总时限,而是连续没有有效进度的观察窗口。有有效进度时可以继续执行超过 150 秒。
|
||||
- 进度包含每次启动生成的随机标识、队列项 ID、递增序号、阶段和数量;旧消息、其他任务消息、乱序消息及无效消息不会延长时限。
|
||||
- 连续 150 秒没有有效进度时,监控器先发出停止请求。尚未进入原生替换的脚本在下一个安全检查点退出;启动原生操作后或恢复事务中,不因普通停止请求打断写入,而是继续校验与事务收尾。
|
||||
- 停止请求发出后仍没有进度,累计连续无进展达到 300 秒时,进入异常处理。只清理当前监控任务中已确认路径的脚本和辅助执行器,不按进程名称批量结束程序,不结束 DxDesigner。COM 调用可能仍在 CAD 内处理,因此必须保留结果不确定保护锁,不能宣称回滚成功。
|
||||
- 发生监控异常也保守保留不确定状态。启动时有授权握手:执行器被纳入监控后才连接 CAD,防止监控建立失败却已开始替换。
|
||||
|
||||
## 扫描开销
|
||||
|
||||
引脚按所属器件建立索引,同一阶段内复用,不再每检查一个器件就重新枚举整页引脚。索引保存对象关联,不缓存连接校验结果:引脚号、网络、位置仍在检查时读取。
|
||||
|
||||
原生替换、恢复预检、恢复写入后的校验和撤销后均失效重建;切换工程或图页也会使索引失效。正常当前页路径预期三次整页引脚索引:替换前快照、原生替换后预检、参数恢复后校验。错误回滚可能增加扫描次数。
|
||||
|
||||
## 诊断与限制
|
||||
|
||||
`quick-run/worker-progress.json` 记录本次执行的阶段、进度序号、数量和停止请求。`monitor-<随机标识>.ready` / `.stop` 是仅供本次执行使用的控制文件,不要手动编辑。失败时继续保留快照、原生报告和 `uncertain.flag`。
|
||||
|
||||
旧任务已经存在 `uncertain.flag` 时仍然禁止自动重试。升级不会清除锁、结束当前 CAD 撤销事务、保存工程或把任务改成成功。此前只读核验通过的 18 个器件任务仍需单独安全收尾。
|
||||
|
||||
R8 需要同时更新主程序与 VBS,不能只将新脚本复制给旧版 EXE。此优化没有增加全工程逐页批处理、自动保存或自动关闭工程功能。
|
||||
@@ -0,0 +1,46 @@
|
||||
# R5 执行修订说明
|
||||
|
||||
本轮根据实际运行日志中的菜单超时、缺少 Value 选项和零命中硬失败进行修订。R5 是独立验收版本,不表示已经完成真实 CAD 批量验收。
|
||||
|
||||
## 启动与数据保护
|
||||
|
||||
- 从交付目录的 `Start-R5.cmd` 启动。窗口标题应包含 `2026.09.06-R5`。
|
||||
- 启动器会检查是否还有旧的替换工具或替换脚本运行,有则拒绝启动,不强制结束任何进程。
|
||||
- 启动器使用独立的 `%LOCALAPPDATA%\DxProductivity\trial-task-center-r5` 数据目录,不迁移、不覆盖旧任务和旧队列证据。首次打开需要新建任务。
|
||||
- 不要直接双击裸 EXE 绕过启动器;也不要用候选源码目录整体覆盖另一边正在修改的原项目。
|
||||
- 验收只使用完整、可丢弃的工程副本。R5 不自动打开、关闭或保存 CAD 工程。
|
||||
|
||||
## 系统鼠标不再作为替换菜单的输入设备
|
||||
|
||||
移除全局移动鼠标、模拟右键、模拟 Alt 键和抢前台的菜单打开路径,也不锁定用户输入。替换命令从已连接的 Viewdraw 进程对应 EXE 的菜单资源中解析,要求唯一匹配“替换符号 / Replace Symbol”,再向该窗口发送命令;未识别时明确失败,不回退到物理鼠标。
|
||||
|
||||
本机资源只读解析得到命令 33977;实现没有硬编码该数字。替换之前仍校验当前工程、图页、目标集合及库身份。移动鼠标与主动编辑 CAD 图纸不同:执行期间仍不应修改、切页或关闭正在处理的 CAD 图页。
|
||||
|
||||
资源解析和隔离测试不能证明真实 CAD 的所有对话框都已支持后台操作。本轮没有在用户正在运行的工程中触发真实替换;必须另做“鼠标移动到其他窗口时执行”的可丢弃工程验收。
|
||||
|
||||
## Value 选项
|
||||
|
||||
- 界面执行区有“替换后将 Part Label 写入 Value”复选框,默认不勾选。
|
||||
- 未勾选:不额外改写原生替换后的 Value 文本,也不创建缺失的 Value。
|
||||
- 勾选:把替换后目标器件的有效 Part Label 写入 Value,并精确校验回读。
|
||||
- 两种模式都继承已有旧 Value 的位置、字体、大小、颜色、方向、可见性,不把旧文本写回。
|
||||
- 队列生成后策略锁定;需要改策略时请创建新任务,不能重新解释已有替换证据。
|
||||
- 确认弹窗和下发执行参数使用同一份 Value 策略,提交后若计划已变化则拒绝执行并要求重新确认。
|
||||
|
||||
## 零命中不是替换失败,也不是替换成功
|
||||
|
||||
在当前图页没有找到旧 Part Number 时,脚本记录 `no_match`,写入工程、图页、旧料号信息;不创建器件快照、不调用原生替换、不修改选择、不执行撤销。此项作为“已处理但未命中”结束,队列允许继续下一项。
|
||||
|
||||
界面明确显示“未命中”及独立计数,不把它算成替换校验成功。最后一项或整个队列含未命中时显示提示状态,而不是笼统的全部替换成功。日志保存具体检查范围。
|
||||
|
||||
**当前仍是当前图页工具,不是全工程遍历。** 当前页无匹配不代表其他图页没有此器件;需要检查其他图页时应明确安排另外的图页操作,不能把此提示作为整个工程零命中的证明。
|
||||
|
||||
## 验收顺序
|
||||
|
||||
1. 无替换动作地确认 R5 标识、复选框、独立任务库和内部拖动分隔条。
|
||||
2. 用一个不存在的料号检查提示、未命中计数、日志以及下一项是否可继续;确认器件内容和选择未变。
|
||||
3. 在副本中分别测试选项关闭、打开、目标 Value 缺失和旧 Value 有自定义显示样式。
|
||||
4. 在正常移动鼠标至其他窗口的情况下测试一次实际替换,检查命令报告、结果、引脚连接和 Value 样式。
|
||||
5. 再测试多条规则、含零命中的多工程队列、中途退出恢复,最后评估真实大工程的内存和运行时长。
|
||||
|
||||
发现异常时保留证据目录和未保存副本,不自动重试或删除保护标记。本轮还移除了事务证据验证失败后继续调用非目标引脚提升的错误分支。
|
||||
@@ -0,0 +1,55 @@
|
||||
# DxPartReplace 器件批量替换
|
||||
|
||||
本工具用于 DxDesigner 7.9.5 工程的器件批量替换。正式桌面流程在任何写入前创建并校验原理图精简备份,按“工程 → 图页 → 规则”严格串行执行;不会并发打开或同时修改多个工程。精简备份不复制 PCB、CES 日志、历史工程备份和数据库运行日志。桌面程序、人工证据流程和原批处理 CLI 是三条不同路径,工作范围和安全保障不能混用。
|
||||
|
||||
## 启动与诊断位置
|
||||
|
||||
双击发布目录中的 `DxPartReplace.exe`。发布版默认把数据放在 EXE 同目录的 `data` 子目录:任务数据库是 `data\task-center.db`,应用日志是 `data\logs\application.log`,任务事件和证据位于 `data\tasks\<任务ID>`,桌面自动替换的共享交接文件位于 `data\quick-run`。更新程序时只替换 EXE 和 `_internal`,不要删除 `data`;向其他人分发时使用未运行过的干净发布包,不要把包含工程备份的本机 `data` 一起外发。源码开发运行仍默认使用 `%LOCALAPPDATA%\DxProductivity\trial-task-center`。
|
||||
|
||||
发生错误时保留目标工程和整个数据目录,至少提供 `application.log`、对应任务的 `events.jsonl`、`quick-run\quick-part-replace.log`、`command.tsv`、`status.tsv`、快照和原生 helper 报告。成功日志按替换前快照中的位号列出每个器件;原工程未标注位号时使用 `UID=...` 作为稳定标识。出现“结果无法确认”或已有待处理替换时,不要反复点击,也不要切换到其他工程后继续;先人工核对当前图页是否已被修改。
|
||||
|
||||
## 桌面一键自动替换
|
||||
|
||||
这是真正执行写操作的主界面路径。连续队列会先逐工程校验并备份,再只读枚举每个 `.prj` 的全部原理图页和待替换旧料号;全部清单固定后,将每个“工程 × 图页 × 规则”作为独立队列项串行处理。只读枚举已经确认未命中的项直接完成,不再为了同一结论第二次打开工程;命中的项仍进入完整替换、保存和回读流程。任务输入禁止链式映射,因此不会出现前序规则在执行中生成另一个规则源料号的歧义。
|
||||
|
||||
1. 新建任务,选择 DxDesigner 工程目录并扫描;勾选要进入队列的 `.prj`。
|
||||
2. 添加旧料号到新料号的映射。新料号必须能从当前 DxDesigner 所连接的中央库中查询到。
|
||||
3. 请先保存并关闭已有 DxDesigner 工程。程序可复用一个空会话或自动启动 DxDesigner,但不会接管用户已经打开的工程。
|
||||
4. 点击 **连续执行队列** 并确认。程序逐个创建和校验原理图精简备份并只读枚举图页;全部图页清单固定后,才逐页执行原生 Replace Part、Library Wins、实例参数恢复、连接校验、保存关闭和重新打开回读。
|
||||
5. 当前页未命中或普通替换失败时记录结果并继续。状态不确定、工程关闭失败或队列文件异常时停止。暂停发生在完整图页规则项收尾后,恢复时不重复已完成页面。
|
||||
6. “全工程图页队列完成”表示所有已枚举图页和规则都得到已保存通过或未命中结果;它仍不表示已通过 Packager、ERC、网表或其他外部工程检查。
|
||||
|
||||
如果精简备份失败,队列默认在写入前停止,并显示“忽略备份失败并继续”。该按钮仅授权当前一次队列;确认后,备份失败的工程无法保证从本工具备份回滚,程序会在任务日志中记录警告。只有已经保存工程且另有独立副本时才应使用。下次执行仍恢复为备份失败即停止。
|
||||
|
||||
目录输入发生变化时,工程表会立即清空并要求重新扫描。尚未开始执行的任务会用新目录扫描结果整体替换旧清单,不继承旧目录的勾选状态;同一目录重扫仍保留已有选择,并把本次缺失的项目标记为不可用。任务一旦存在执行状态、尝试记录、恢复记录或自动队列证据,就不能在同一任务中切换目录,应新建任务,避免把两个目录的执行证据混在一起。
|
||||
|
||||
执行时界面会锁定删除、工程选择、扫描和规则修改,并显示当前工程、图页、规则、已完成项数和运行时长。队列运行中不能修改输入。存在失败项时任务保留在“进行中”,用户可调整选项并只重试失败工程;全部选中工程成功或未命中后才进入“已完成”。
|
||||
|
||||
错误提示会显示具体原因、当前工程、规则和错误编号。需要排查时检查 `data\quick-run` 和对应任务目录;写入状态无法确认时先核对当前图页。
|
||||
|
||||
长期运行时,快速替换日志和任务事件日志会按 5 MiB 轮转;历史证据默认至少保留最新 10 份,并按 30 天、100 份和 5 GiB 上限清理最旧的程序生成目录。需要永久留档的批次应及时复制到任务数据目录之外;当前活动证据、未知目录和链接目录不会被自动清理。
|
||||
|
||||
自动替换要求目标中央库可用。没有中央库的机器可以运行单元测试、UI 测试、构建和 EXE 冒烟测试,但不能证明真实目标库元件替换成功,也不能完成现场联调验收。
|
||||
|
||||
## 参数继承边界
|
||||
|
||||
桌面流程在替换前记录实例状态,并在原生替换后恢复应由原实例保留的放置和显示参数;目标符号、库控制属性和库引脚名称仍以 Library Wins 为准。连接、引脚号、坐标或受保护实例状态发生不允许的变化时,流程必须失败,不能仅以新 `Part Number` 已出现判定成功。
|
||||
|
||||
连续队列的通过项会自动保存、关闭并重新打开回读;人工证据流程仍不自动保存。失败后的 Undo 只允许在作业记录的工程和图页上下文仍精确匹配时执行;上下文已变化时会阻断,而不会对当前未知工程强制撤销。
|
||||
|
||||
## 人工证据流程
|
||||
|
||||
界面中保留的 **启动任务 / Capture Before / Capture After / Retry** 属于 `TrialRunner` 人工证据流程,不是桌面一键自动替换的第二阶段。
|
||||
|
||||
1. 启动任务并对当前项目执行 Capture Before。
|
||||
2. 由操作员在 DxDesigner 中完成受控替换,不保存。
|
||||
3. 执行 Capture After;工具重新打开并校验已保存的 before 证据哈希,再比较前后完整证据。
|
||||
4. 通过时项目进入 Completed;失败时保留证据并从新的 Capture Before 重试。
|
||||
|
||||
该流程用于采集和比较证据,不继承桌面 quick-run 的自动写入承诺。
|
||||
|
||||
## 原批处理 CLI
|
||||
|
||||
`Start-PartReplacement.ps1` 和 `BatchController` 是面向完整项目批次的独立流程,包含不可变输入、全项目库存、映射认证、关闭后备份、逐规则替换、受控保存、恢复以及外部检查门禁。它要求现场验收过的兼容性配置和中央库,详细操作见 [DxDesigner 7.9.5 元件替换操作指南](part-replacement.md)。
|
||||
|
||||
不要把桌面 quick-run 的“当前队列已完成”当作批处理 CLI 的 `verified_saved`,也不要把人工 Capture Before/After 的比较结果当作已经备份、保存或通过外部检查。
|
||||
@@ -0,0 +1,31 @@
|
||||
# Value内容选项与布局调整
|
||||
|
||||
适用于当前候选版本。
|
||||
|
||||
## Value内容和样式是两件事
|
||||
|
||||
- 默认不勾选“替换后将 Part Label 写入 Value”:保留原生替换后的库 Value/实例覆盖值,不读取 Part Label,不额外赋值;目标没有 Value 时不主动创建。
|
||||
- 勾选后:从替换后的目标元件回读 Part Label,确认非空后写入 Value,再回读并做最终验证。
|
||||
- 每条替换规则可以勾选“替换后写入自定义 Value”并填写内容。勾选后,自定义内容优先于任务级 Part Label 选项;未勾选时不写入自定义内容。
|
||||
- 每条规则可以单独勾选“识别并同步原 Value 中的 /NC”。只有勾选时,替换前 Value 中以 `/` 分隔的独立 `NC` 段才会同步;未勾选时不识别、不追加 `/NC`。
|
||||
- `NCM`、`NC_OPTION` 或没有 `/` 的普通 `NC` 不会误判。已有 `/NC` 时不会重复追加。
|
||||
- 每个 NC 同步器件都会写入证据日志,界面日志显示“位号 R1 旧值 -> 新值,识别到 NC,已同步”。
|
||||
- 两种模式都恢复已有Value的X/Y、字体、字号、颜色、方向及显示/隐藏状态,不回填旧Value的文字内容。
|
||||
- 原来没有Value时不虚构旧样式;勾选且必须创建Value时沿用现有的隐藏样式回退策略。
|
||||
- 任务级 Part Label 选项和规则级自定义 Value、NC 选项都会持久化。队列生成后,工程目录、工程选择和全部规则选项冻结,直至队列完成或中断恢复结束。
|
||||
|
||||
命令记录 `value_mode`、`custom_value`、`sync_nc` 和基础 Value 策略,写前快照也绑定这些字段。重试和恢复不能按后来修改的界面选项重新解释旧任务。
|
||||
|
||||
数据库升级至 schema 5。旧规则的自定义 Value 默认关闭,NC 同步默认开启,以保持升级前行为。工程文件不会因为数据库迁移而被更改。
|
||||
|
||||
## 界面调整
|
||||
|
||||
拖动较宽的左右/上下分隔条可调整区域大小。小窗口下日志默认收起,可用“显示日志/收起日志”切换。关闭窗口时保存分隔状态、工程表/规则表列宽及日志展开状态到任务中心数据目录中的ui-layout.ini;“重置布局”恢复默认比例和列宽。
|
||||
|
||||
## 多项目执行边界
|
||||
|
||||
仍使用单执行通道、每次一条规则。确认的工程、规则、Value 与 NC 策略在派发时核验,脚本必须匹配本次 job_id;其他队列项的成功回执不能替代本项成功。
|
||||
|
||||
批量执行不会同时打开多个工程。程序先完成所有选中工程的备份,再逐个工程枚举原理图页,随后串行替换、保存、关闭和回读验证;未命中项记录后自动跳过。
|
||||
|
||||
自动测试覆盖命令冻结、数据库迁移、旧快照恢复、自定义 Value、NC 开关、批量备份顺序和回滚保护。真实 CAD 的库差异、异常工程及长期运行仍需继续做实机验收。
|
||||
@@ -0,0 +1,225 @@
|
||||
' Shared DxDesigner 7.9.5 bridge helpers. Keep this file ASCII-only.
|
||||
|
||||
Function DxReadUtf8(ByVal FilePath)
|
||||
Dim Stream
|
||||
Dim ErrorNumber
|
||||
Dim ErrorDescription
|
||||
Dim ErrorSource
|
||||
|
||||
Set Stream = CreateObject("ADODB.Stream")
|
||||
Stream.Type = 2
|
||||
Stream.Charset = "utf-8"
|
||||
Stream.Open
|
||||
|
||||
On Error Resume Next
|
||||
Stream.LoadFromFile CStr(FilePath)
|
||||
ErrorNumber = Err.Number
|
||||
ErrorDescription = Err.Description
|
||||
ErrorSource = Err.Source
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
If ErrorNumber <> 0 Then
|
||||
Stream.Close
|
||||
Err.Raise ErrorNumber, ErrorSource, ErrorDescription
|
||||
End If
|
||||
|
||||
DxReadUtf8 = Stream.ReadText
|
||||
Stream.Close
|
||||
End Function
|
||||
|
||||
Sub DxWriteUtf8Atomic(ByVal FilePath, ByVal Text)
|
||||
Dim Fso
|
||||
Dim Stream
|
||||
Dim Shell
|
||||
Dim ParentPath
|
||||
Dim TemporaryPath
|
||||
Dim CommandLine
|
||||
Dim ExitCode
|
||||
Dim ErrorNumber
|
||||
Dim ErrorDescription
|
||||
Dim ErrorSource
|
||||
|
||||
Set Fso = CreateObject("Scripting.FileSystemObject")
|
||||
ParentPath = Fso.GetParentFolderName(Fso.GetAbsolutePathName(CStr(FilePath)))
|
||||
If Not Fso.FolderExists(ParentPath) Then
|
||||
Err.Raise vbObjectError + 795, "DxWriteUtf8Atomic", _
|
||||
"Destination directory does not exist"
|
||||
End If
|
||||
TemporaryPath = Fso.BuildPath(ParentPath, Fso.GetTempName)
|
||||
|
||||
Set Stream = CreateObject("ADODB.Stream")
|
||||
Stream.Type = 2
|
||||
Stream.Charset = "utf-8"
|
||||
Stream.Open
|
||||
Stream.WriteText CStr(Text)
|
||||
|
||||
On Error Resume Next
|
||||
Stream.SaveToFile TemporaryPath, 2
|
||||
ErrorNumber = Err.Number
|
||||
ErrorDescription = Err.Description
|
||||
ErrorSource = Err.Source
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
Stream.Close
|
||||
If ErrorNumber <> 0 Then
|
||||
Err.Raise ErrorNumber, ErrorSource, ErrorDescription
|
||||
End If
|
||||
|
||||
Set Shell = CreateObject("WScript.Shell")
|
||||
CommandLine = DxCommandQuote( _
|
||||
Shell.ExpandEnvironmentStrings("%ComSpec%")) & _
|
||||
" /d /s /c " & Chr(34) & "move /y " & _
|
||||
DxCommandQuote(TemporaryPath) & " " & _
|
||||
DxCommandQuote(Fso.GetAbsolutePathName(CStr(FilePath))) & _
|
||||
" >nul" & Chr(34)
|
||||
ExitCode = Shell.Run(CommandLine, 0, True)
|
||||
If ExitCode <> 0 Then
|
||||
If Fso.FileExists(TemporaryPath) Then
|
||||
Fso.DeleteFile TemporaryPath, True
|
||||
End If
|
||||
Err.Raise vbObjectError + 796, "DxWriteUtf8Atomic", _
|
||||
"Cannot atomically replace destination file"
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Function DxJsonEscape(ByVal Value)
|
||||
Dim Text
|
||||
Dim Result
|
||||
Dim Index
|
||||
Dim Character
|
||||
Dim CodePoint
|
||||
|
||||
Text = CStr(Value)
|
||||
Result = ""
|
||||
For Index = 1 To Len(Text)
|
||||
Character = Mid(Text, Index, 1)
|
||||
CodePoint = AscW(Character)
|
||||
If CodePoint < 0 Then CodePoint = CodePoint + 65536
|
||||
Select Case CodePoint
|
||||
Case 8
|
||||
Result = Result & Chr(92) & "b"
|
||||
Case 9
|
||||
Result = Result & Chr(92) & "t"
|
||||
Case 10
|
||||
Result = Result & Chr(92) & "n"
|
||||
Case 12
|
||||
Result = Result & Chr(92) & "f"
|
||||
Case 13
|
||||
Result = Result & Chr(92) & "r"
|
||||
Case 34
|
||||
Result = Result & Chr(92) & Chr(34)
|
||||
Case 92
|
||||
Result = Result & Chr(92) & Chr(92)
|
||||
Case Else
|
||||
If CodePoint < 32 Then
|
||||
Result = Result & Chr(92) & "u00" & _
|
||||
Right("0" & Hex(CodePoint), 2)
|
||||
Else
|
||||
Result = Result & Character
|
||||
End If
|
||||
End Select
|
||||
Next
|
||||
DxJsonEscape = Result
|
||||
End Function
|
||||
|
||||
Function DxInvariantNumber(ByVal Value)
|
||||
Dim Text
|
||||
Dim DecimalSample
|
||||
Dim DecimalSeparator
|
||||
|
||||
If IsNull(Value) Or IsEmpty(Value) Or Not IsNumeric(Value) Then
|
||||
Err.Raise vbObjectError + 797, "DxInvariantNumber", _
|
||||
"Value is not numeric"
|
||||
End If
|
||||
Text = Trim(CStr(Value))
|
||||
DecimalSample = Trim(CStr(1.5))
|
||||
DecimalSeparator = Mid(DecimalSample, 2, Len(DecimalSample) - 2)
|
||||
If Len(DecimalSeparator) > 0 And DecimalSeparator <> "." Then
|
||||
Text = Replace(Text, DecimalSeparator, ".")
|
||||
End If
|
||||
DxInvariantNumber = Text
|
||||
End Function
|
||||
|
||||
Function DxResolveRunPath(ByVal RootPath, ByVal RunRelativePath)
|
||||
Dim Fso
|
||||
Dim RootAbsolute
|
||||
Dim Candidate
|
||||
Dim RelativeText
|
||||
Dim Prefix
|
||||
|
||||
Set Fso = CreateObject("Scripting.FileSystemObject")
|
||||
RootAbsolute = Fso.GetAbsolutePathName(CStr(RootPath))
|
||||
Do While Len(RootAbsolute) > 3 And Right(RootAbsolute, 1) = "\"
|
||||
RootAbsolute = Left(RootAbsolute, Len(RootAbsolute) - 1)
|
||||
Loop
|
||||
If Not Fso.FolderExists(RootAbsolute) Then
|
||||
Err.Raise vbObjectError + 798, "DxResolveRunPath", _
|
||||
"Run root does not exist"
|
||||
End If
|
||||
DxValidateNoReparse Fso, RootAbsolute
|
||||
|
||||
RelativeText = CStr(RunRelativePath)
|
||||
If Len(RelativeText) = 0 Or Left(RelativeText, 1) = "\" Or _
|
||||
InStr(RelativeText, ":") > 0 Or _
|
||||
InStr(RelativeText, "*") > 0 Or _
|
||||
InStr(RelativeText, "?") > 0 Then
|
||||
Err.Raise vbObjectError + 799, "DxResolveRunPath", _
|
||||
"Run path must be a non-empty relative path"
|
||||
End If
|
||||
|
||||
Candidate = Fso.GetAbsolutePathName( _
|
||||
Fso.BuildPath(RootAbsolute, RelativeText))
|
||||
Prefix = RootAbsolute
|
||||
If Right(Prefix, 1) <> "\" Then Prefix = Prefix & "\"
|
||||
If Len(Candidate) <= Len(Prefix) Or _
|
||||
StrComp(Left(Candidate, Len(Prefix)), Prefix, _
|
||||
vbTextCompare) <> 0 Then
|
||||
Err.Raise vbObjectError + 800, "DxResolveRunPath", _
|
||||
"Run path escapes the supplied root"
|
||||
End If
|
||||
DxValidateNoReparse Fso, Candidate
|
||||
DxResolveRunPath = Candidate
|
||||
End Function
|
||||
|
||||
Sub DxValidateNoReparse(ByRef Fso, ByVal FilePath)
|
||||
Dim AbsolutePath
|
||||
Dim DriveName
|
||||
Dim CurrentPath
|
||||
Dim Remaining
|
||||
Dim Parts
|
||||
Dim Part
|
||||
Dim Attributes
|
||||
|
||||
AbsolutePath = Fso.GetAbsolutePathName(CStr(FilePath))
|
||||
DriveName = Fso.GetDriveName(AbsolutePath)
|
||||
If Len(DriveName) = 0 Then
|
||||
Err.Raise vbObjectError + 801, "DxResolveRunPath", _
|
||||
"Run paths must use a local drive"
|
||||
End If
|
||||
CurrentPath = DriveName & "\"
|
||||
Remaining = Mid(AbsolutePath, Len(CurrentPath) + 1)
|
||||
If Len(Remaining) = 0 Then Exit Sub
|
||||
|
||||
Parts = Split(Remaining, "\")
|
||||
For Each Part In Parts
|
||||
If Len(CStr(Part)) > 0 Then
|
||||
CurrentPath = Fso.BuildPath(CurrentPath, CStr(Part))
|
||||
If Fso.FolderExists(CurrentPath) Then
|
||||
Attributes = Fso.GetFolder(CurrentPath).Attributes
|
||||
ElseIf Fso.FileExists(CurrentPath) Then
|
||||
Attributes = Fso.GetFile(CurrentPath).Attributes
|
||||
Else
|
||||
Exit For
|
||||
End If
|
||||
If (Attributes And 1024) <> 0 Then
|
||||
Err.Raise vbObjectError + 802, "DxResolveRunPath", _
|
||||
"Run path contains a reparse point"
|
||||
End If
|
||||
End If
|
||||
Next
|
||||
End Sub
|
||||
|
||||
Function DxCommandQuote(ByVal Value)
|
||||
DxCommandQuote = Chr(34) & Replace(CStr(Value), Chr(34), _
|
||||
Chr(92) & Chr(34)) & Chr(34)
|
||||
End Function
|
||||
@@ -0,0 +1,183 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$InstallRoot,
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$PythonExecutable,
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$CompatibilityProfile,
|
||||
[string]$SettingsRoot,
|
||||
[switch]$TestMode,
|
||||
[switch]$WhatIf
|
||||
)
|
||||
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = "Stop"
|
||||
. (Join-Path $PSScriptRoot "PathSafety.ps1")
|
||||
|
||||
function Resolve-FullPath {
|
||||
param([string]$Value)
|
||||
return [IO.Path]::GetFullPath($Value)
|
||||
}
|
||||
|
||||
function Resolve-ExistingFile {
|
||||
param([string]$Value, [string]$Name)
|
||||
$resolved = Resolve-FullPath $Value
|
||||
Assert-DxNoReparsePath $resolved $Name
|
||||
if (-not (Test-Path -LiteralPath $resolved -PathType Leaf)) {
|
||||
throw "$Name does not exist: $resolved"
|
||||
}
|
||||
return $resolved
|
||||
}
|
||||
|
||||
$toolHome = Resolve-FullPath $InstallRoot
|
||||
Assert-DxNoReparsePath $toolHome "installation root"
|
||||
if (-not (Test-Path -LiteralPath $toolHome -PathType Container)) {
|
||||
throw "installation root does not exist: $toolHome"
|
||||
}
|
||||
|
||||
$runtimeDirectory = Join-Path $toolHome "integration\dxdesigner795"
|
||||
Assert-DxNoReparsePath $runtimeDirectory "runtime directory"
|
||||
$requiredRuntimeFiles = @(
|
||||
"PathSafety.ps1",
|
||||
"PartReplacementContract.ps1",
|
||||
"MenuAdd.vbs",
|
||||
"MenuRuntime.vbs",
|
||||
"PartReplaceMenuRuntime.vbs",
|
||||
"BridgeCommon.vbs",
|
||||
"PartReplaceProbe.vbs",
|
||||
"PartReplaceBridge.vbs"
|
||||
)
|
||||
$missingRuntimeFiles = @()
|
||||
$requiredRuntimePaths = @()
|
||||
foreach ($runtimeName in $requiredRuntimeFiles) {
|
||||
$runtimePath = Join-Path $runtimeDirectory $runtimeName
|
||||
Assert-DxNoReparsePath $runtimePath "runtime file"
|
||||
$requiredRuntimePaths += $runtimePath
|
||||
if (-not (Test-Path -LiteralPath $runtimePath -PathType Leaf)) {
|
||||
$missingRuntimeFiles += $runtimePath
|
||||
}
|
||||
}
|
||||
if ($missingRuntimeFiles.Count -ne 0) {
|
||||
throw "required runtime files are missing (including MenuRuntime.vbs): $($missingRuntimeFiles -join ', ')"
|
||||
}
|
||||
|
||||
$python = Resolve-ExistingFile $PythonExecutable "Python executable"
|
||||
$profileSource = Resolve-ExistingFile $CompatibilityProfile `
|
||||
"compatibility profile"
|
||||
|
||||
if ($TestMode) {
|
||||
if ($env:DX_PRODUCTIVITY_TEST_MODE -cne "1") {
|
||||
throw "TestMode requires DX_PRODUCTIVITY_TEST_MODE=1"
|
||||
}
|
||||
if ([string]::IsNullOrWhiteSpace($SettingsRoot)) {
|
||||
throw "TestMode requires an explicit SettingsRoot"
|
||||
}
|
||||
$settingsBase = Resolve-FullPath $SettingsRoot
|
||||
Assert-DxNoReparsePath $settingsBase "TestMode settings root"
|
||||
$systemTemp = (Resolve-FullPath ([IO.Path]::GetTempPath())).TrimEnd('\')
|
||||
$tempPrefix = $systemTemp + "\"
|
||||
if (-not $toolHome.StartsWith(
|
||||
$tempPrefix,
|
||||
[StringComparison]::OrdinalIgnoreCase
|
||||
)) {
|
||||
throw "TestMode InstallRoot must be under the system temp directory"
|
||||
}
|
||||
if (-not $settingsBase.StartsWith(
|
||||
$tempPrefix,
|
||||
[StringComparison]::OrdinalIgnoreCase
|
||||
)) {
|
||||
throw "TestMode SettingsRoot must be under the system temp directory"
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (-not [string]::IsNullOrWhiteSpace($SettingsRoot)) {
|
||||
throw "SettingsRoot is allowed only with TestMode"
|
||||
}
|
||||
$settingsBase = [Environment]::GetFolderPath(
|
||||
[Environment+SpecialFolder]::LocalApplicationData
|
||||
)
|
||||
$settingsBase = Resolve-FullPath $settingsBase
|
||||
Assert-DxNoReparsePath $settingsBase "settings root"
|
||||
}
|
||||
|
||||
$settingsDirectory = Join-Path $settingsBase "DxProductivity"
|
||||
$settingsPath = Join-Path $settingsDirectory "settings.json"
|
||||
$runRoot = Join-Path $toolHome "runs"
|
||||
$deployedProfile = Join-Path $runRoot "compatibility-profile.json"
|
||||
Assert-DxNoReparsePath $settingsDirectory "settings directory"
|
||||
Assert-DxNoReparsePath $settingsPath "settings path"
|
||||
Assert-DxNoReparsePath $runRoot "run root"
|
||||
Assert-DxNoReparsePath $deployedProfile "deployed compatibility profile"
|
||||
|
||||
Write-Output "InstallRoot=$toolHome"
|
||||
Write-Output "PythonExecutable=$python"
|
||||
Write-Output "ProfileSource=$profileSource"
|
||||
Write-Output "CompatibilityProfile=$deployedProfile"
|
||||
Write-Output "SettingsPath=$settingsPath"
|
||||
Write-Output "RunRoot=$runRoot"
|
||||
Write-Output "DXTOOLS_HOME=$toolHome"
|
||||
if ($TestMode) {
|
||||
Write-Output "TEST MODE: user-scope DXTOOLS_HOME is not written"
|
||||
}
|
||||
if ($WhatIf) {
|
||||
exit 0
|
||||
}
|
||||
|
||||
Assert-DxNoReparsePath $toolHome "installation root"
|
||||
foreach ($runtimePath in $requiredRuntimePaths) {
|
||||
Assert-DxNoReparsePath $runtimePath "runtime file"
|
||||
}
|
||||
Assert-DxNoReparsePath $python "Python executable"
|
||||
Assert-DxNoReparsePath $profileSource "compatibility profile"
|
||||
Assert-DxNoReparsePath $runRoot "run root"
|
||||
Assert-DxNoReparsePath $deployedProfile "deployed compatibility profile"
|
||||
Assert-DxNoReparsePath $settingsPath "settings path"
|
||||
|
||||
$pythonCheck = @(
|
||||
"-c",
|
||||
"import sys, dx_productivity; raise SystemExit(0 if sys.version_info[:2] == (3, 12) else 1)"
|
||||
)
|
||||
& $python @pythonCheck
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Python must import dx_productivity and be exactly 3.12: $python"
|
||||
}
|
||||
|
||||
$profileDeploy = @(
|
||||
"-m",
|
||||
"dx_productivity",
|
||||
"deploy-profile",
|
||||
$profileSource,
|
||||
$deployedProfile
|
||||
)
|
||||
& $python @profileDeploy
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "compatibility profile deployment failed: $profileSource"
|
||||
}
|
||||
|
||||
$utf8 = New-Object Text.UTF8Encoding($false)
|
||||
$settingsData = [ordered]@{
|
||||
compatibility_profile = $deployedProfile
|
||||
dxtools_home = $toolHome
|
||||
python_executable = $python
|
||||
run_root = $runRoot
|
||||
}
|
||||
$settingsText = ($settingsData | ConvertTo-Json -Compress) + "`n"
|
||||
|
||||
Assert-DxNoReparsePath $settingsDirectory "settings directory"
|
||||
New-Item -ItemType Directory -Force -Path $settingsDirectory | Out-Null
|
||||
Assert-DxNoReparsePath $toolHome "installation root"
|
||||
foreach ($runtimePath in $requiredRuntimePaths) {
|
||||
Assert-DxNoReparsePath $runtimePath "runtime file"
|
||||
}
|
||||
Assert-DxNoReparsePath $deployedProfile "deployed compatibility profile"
|
||||
Assert-DxNoReparsePath $settingsPath "settings path"
|
||||
Write-DxBytesAtomic $settingsPath $utf8.GetBytes($settingsText)
|
||||
|
||||
if (-not $TestMode) {
|
||||
[Environment]::SetEnvironmentVariable(
|
||||
"DXTOOLS_HOME",
|
||||
$toolHome,
|
||||
[EnvironmentVariableTarget]::User
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
On Error Resume Next
|
||||
Set DxPartReplaceLoaderEntryPoint = GetRef("DxInstallPartReplacementMenu")
|
||||
DxPartReplaceLoaderNeedsRuntime = (Err.Number <> 0)
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
|
||||
If DxPartReplaceLoaderNeedsRuntime Then
|
||||
DxPartReplaceLoaderHome = CStr(Scripting.GetEnvVariable("DXTOOLS_HOME"))
|
||||
If Len(DxPartReplaceLoaderHome) = 0 Then
|
||||
Err.Raise vbObjectError + 795, "MenuAdd.vbs", _
|
||||
"DXTOOLS_HOME is not configured"
|
||||
End If
|
||||
DxPartReplaceLoaderSource = CreateObject( _
|
||||
"Scripting.FileSystemObject").OpenTextFile( _
|
||||
DxPartReplaceLoaderHome & _
|
||||
"\integration\dxdesigner795\MenuRuntime.vbs", _
|
||||
1, False, 0).ReadAll
|
||||
ExecuteGlobal DxPartReplaceLoaderSource
|
||||
End If
|
||||
|
||||
Set DxPartReplaceLoaderEntryPoint = GetRef("DxInstallPartReplacementMenu")
|
||||
Call DxPartReplaceLoaderEntryPoint()
|
||||
@@ -0,0 +1,86 @@
|
||||
Option Explicit
|
||||
|
||||
Const DX_PART_REPLACE_TAG = "DX_PRODUCTIVITY_PART_REPLACE"
|
||||
Dim DxMenuModulesLoaded
|
||||
|
||||
Sub DxInstallPartReplacementMenu()
|
||||
Dim Bar
|
||||
Dim Controls
|
||||
Dim Index
|
||||
Dim Existing
|
||||
Dim Control
|
||||
Set Bar = CommandBars("Sheet Menu Bar")
|
||||
Set Controls = Bar.Controls
|
||||
For Index = Controls.Count To 1 Step -1
|
||||
Set Existing = Controls.Item(Index)
|
||||
If Existing.Tag = DX_PART_REPLACE_TAG Then Existing.Delete
|
||||
Next
|
||||
Set Control = Controls.Add(10, , , , True)
|
||||
Control.Tag = DX_PART_REPLACE_TAG
|
||||
Control.Caption = "Dx Productivity"
|
||||
DxAddAction Control.Controls, "Part replacement probe", _
|
||||
"DxPartReplacementMenuProbe"
|
||||
DxAddAction Control.Controls, "Inventory current project", _
|
||||
"DxPartReplacementMenuInventory"
|
||||
DxAddAction Control.Controls, "Continue part replacement", _
|
||||
"DxPartReplacementMenuContinue"
|
||||
End Sub
|
||||
|
||||
Sub DxAddAction(ByVal Controls, ByVal Caption, ByVal MacroName)
|
||||
Dim Control
|
||||
Set Control = Controls.Add(1, , , , True)
|
||||
Control.Caption = Caption
|
||||
Control.OnAction = MacroName
|
||||
End Sub
|
||||
|
||||
Function DxMenuHome()
|
||||
DxMenuHome = CStr(Scripting.GetEnvVariable("DXTOOLS_HOME"))
|
||||
If Len(DxMenuHome) = 0 Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuHome", _
|
||||
"DXTOOLS_HOME is not configured"
|
||||
End If
|
||||
End Function
|
||||
|
||||
Sub DxMenuLoad(ByVal FileName)
|
||||
Dim Fso
|
||||
Dim Home
|
||||
Dim Text
|
||||
Home = DxMenuHome()
|
||||
Set Fso = CreateObject("Scripting.FileSystemObject")
|
||||
Text = Fso.OpenTextFile(Home & "\integration\dxdesigner795\" & _
|
||||
FileName, 1, False, 0).ReadAll
|
||||
ExecuteGlobal Text
|
||||
End Sub
|
||||
|
||||
Sub DxMenuLoadModules()
|
||||
If DxMenuModulesLoaded Then Exit Sub
|
||||
DxMenuLoad "BridgeCommon.vbs"
|
||||
DxMenuLoad "PartReplaceProbe.vbs"
|
||||
DxMenuLoad "PartReplaceBridge.vbs"
|
||||
DxMenuLoad "PartReplaceMenuRuntime.vbs"
|
||||
DxMenuModulesLoaded = True
|
||||
End Sub
|
||||
|
||||
Sub DxPartReplacementMenuProbe()
|
||||
Dim Request
|
||||
DxMenuLoadModules
|
||||
Request = "{""disposable_project_marker"":false," & _
|
||||
"""format_version"":1,""operator_confirmation"":false}" & vbLf
|
||||
DxWriteUtf8Atomic DxMenuHome() & _
|
||||
"\runs\menu-probe-request.json", Request
|
||||
DxRunPartReplaceProbe "runs\menu-probe-request.json", _
|
||||
"runs\menu-compatibility-profile.json"
|
||||
End Sub
|
||||
|
||||
Sub DxMenuBridge(ByVal MenuAction)
|
||||
DxMenuLoadModules
|
||||
DxPartReplaceMenuDispatch MenuAction
|
||||
End Sub
|
||||
|
||||
Sub DxPartReplacementMenuInventory()
|
||||
DxMenuBridge "inventory"
|
||||
End Sub
|
||||
|
||||
Sub DxPartReplacementMenuContinue()
|
||||
DxMenuBridge "continue"
|
||||
End Sub
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,332 @@
|
||||
' DxDesigner 7.9.5 part replacement menu runtime. ASCII-only source.
|
||||
|
||||
Sub DxMenuRequireFields(ByRef Record, ByVal FieldNames, _
|
||||
ByVal ExpectedCount, ByVal Context)
|
||||
Dim Name
|
||||
If Not DxBridgeIsDictionary(Record) Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuRequireFields", _
|
||||
Context & " must be an object"
|
||||
End If
|
||||
If Record.Count <> ExpectedCount Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuRequireFields", _
|
||||
Context & " fields are invalid"
|
||||
End If
|
||||
For Each Name In Split(CStr(FieldNames), ",")
|
||||
If Not Record.Exists(CStr(Name)) Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuRequireFields", _
|
||||
Context & " is missing " & CStr(Name)
|
||||
End If
|
||||
Next
|
||||
End Sub
|
||||
|
||||
Sub DxMenuRequireString(ByRef Record, ByVal Name, ByVal Context)
|
||||
If VarType(Record(CStr(Name))) <> vbString Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuRequireString", _
|
||||
Context & "." & CStr(Name) & " must be a string"
|
||||
End If
|
||||
If Len(CStr(Record(CStr(Name)))) = 0 Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuRequireString", _
|
||||
Context & "." & CStr(Name) & " must not be empty"
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Function DxMenuCanonicalProjectPath(ByRef Fso, ByVal Value)
|
||||
DxMenuCanonicalProjectPath = LCase(Replace( _
|
||||
Fso.GetAbsolutePathName(CStr(Value)), "/", "\"))
|
||||
End Function
|
||||
|
||||
Sub DxMenuValidateManifestRecord(ByRef Record, ByVal Home)
|
||||
Dim Name
|
||||
DxMenuRequireFields Record, _
|
||||
"command,profile,project_id,project_path,snapshot,status", 6, _
|
||||
"runtime manifest project"
|
||||
For Each Name In Array("command", "profile", "project_id", _
|
||||
"project_path", "snapshot", "status")
|
||||
DxMenuRequireString Record, CStr(Name), "runtime manifest project"
|
||||
Next
|
||||
If StrComp(CStr(Record("profile")), _
|
||||
"runs/compatibility-profile.json", vbBinaryCompare) <> 0 Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuValidateManifestRecord", _
|
||||
"runtime manifest profile is not the deployed profile"
|
||||
End If
|
||||
For Each Name In Array("profile", "command", "status", "snapshot")
|
||||
Call DxResolveRunPath(Home, CStr(Record(CStr(Name))))
|
||||
Next
|
||||
End Sub
|
||||
|
||||
Function DxMenuReadManifest(ByVal Home)
|
||||
Dim ManifestPath
|
||||
Dim Manifest
|
||||
ManifestPath = DxResolveRunPath(Home, _
|
||||
"runs/current-part-replacement.json")
|
||||
Set Manifest = DxBridgeParseJson(DxReadUtf8(ManifestPath))
|
||||
DxMenuRequireFields Manifest, _
|
||||
"complete,current_action,current_command_id,current_project_id," & _
|
||||
"format_version,projects", 6, _
|
||||
"runtime manifest"
|
||||
If VarType(Manifest("complete")) <> vbBoolean Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadManifest", _
|
||||
"runtime manifest complete must be Boolean"
|
||||
End If
|
||||
If Not DxBridgeIsProtocolInteger(Manifest("format_version")) Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadManifest", _
|
||||
"runtime manifest format_version must be integer 2"
|
||||
End If
|
||||
If CLng(Manifest("format_version")) <> 2 Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadManifest", _
|
||||
"runtime manifest format_version must be 2"
|
||||
End If
|
||||
If Not DxBridgeIsJsonArray(Manifest("projects")) Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadManifest", _
|
||||
"runtime manifest projects must be an array"
|
||||
End If
|
||||
If CBool(Manifest("complete")) Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadManifest", _
|
||||
"part replacement job is complete"
|
||||
End If
|
||||
DxMenuRequireString Manifest, "current_action", "runtime manifest"
|
||||
DxMenuRequireString Manifest, "current_command_id", "runtime manifest"
|
||||
DxMenuRequireString Manifest, "current_project_id", "runtime manifest"
|
||||
If Not DxMenuIsBaseAction(CStr(Manifest("current_action"))) Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadManifest", _
|
||||
"runtime manifest current_action is invalid"
|
||||
End If
|
||||
Set DxMenuReadManifest = Manifest
|
||||
End Function
|
||||
|
||||
Function DxMenuReadManifestRecord(ByRef Manifest, ByVal Home)
|
||||
Dim Entries
|
||||
Dim Record
|
||||
Dim MatchRecord
|
||||
Dim Index
|
||||
Dim Matches
|
||||
Set Entries = Manifest("projects")
|
||||
Matches = 0
|
||||
For Index = 0 To Entries.Count - 1
|
||||
If Not IsObject(Entries.Item(Index)) Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadManifestRecord", _
|
||||
"runtime manifest project must be an object"
|
||||
End If
|
||||
Set Record = Entries.Item(Index)
|
||||
DxMenuValidateManifestRecord Record, Home
|
||||
If StrComp(CStr(Record("project_id")), _
|
||||
CStr(Manifest("current_project_id")), _
|
||||
vbBinaryCompare) = 0 Then
|
||||
Matches = Matches + 1
|
||||
Set MatchRecord = Record
|
||||
End If
|
||||
Next
|
||||
If Matches <> 1 Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadManifestRecord", _
|
||||
"current project has zero or multiple runtime manifest matches"
|
||||
End If
|
||||
Set DxMenuReadManifestRecord = MatchRecord
|
||||
End Function
|
||||
|
||||
Function DxMenuIsBaseAction(ByVal ActionName)
|
||||
Select Case CStr(ActionName)
|
||||
Case "inventory", "close_project", "close_without_save", _
|
||||
"open_project", "replace_part", "undo", "save", _
|
||||
"packager", "erc", "netlist"
|
||||
DxMenuIsBaseAction = True
|
||||
Case Else
|
||||
DxMenuIsBaseAction = False
|
||||
End Select
|
||||
End Function
|
||||
|
||||
Function DxMenuReadBoundCommand(ByVal Home, ByRef Manifest, ByRef Record)
|
||||
Dim Command
|
||||
Dim Failure
|
||||
Set Command = DxBridgeParseJson(DxReadUtf8( _
|
||||
DxResolveRunPath(Home, CStr(Record("command")))))
|
||||
If Not DxBridgeIsDictionary(Command) Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadBoundCommand", _
|
||||
"current bridge command must be an object"
|
||||
End If
|
||||
Set Failure = DxBridgeNewFailure()
|
||||
If Not DxBridgeValidateCommand(Command, _
|
||||
CStr(Manifest("current_action")), Failure) Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadBoundCommand", _
|
||||
"current bridge command is missing or stale"
|
||||
End If
|
||||
If StrComp(CStr(Command("command_id")), _
|
||||
CStr(Manifest("current_command_id")), _
|
||||
vbBinaryCompare) <> 0 Or _
|
||||
StrComp(CStr(Command("project_id")), _
|
||||
CStr(Manifest("current_project_id")), _
|
||||
vbBinaryCompare) <> 0 Or _
|
||||
StrComp(CStr(Command("project_id")), _
|
||||
CStr(Record("project_id")), _
|
||||
vbBinaryCompare) <> 0 Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadBoundCommand", _
|
||||
"runtime manifest and command bindings do not match"
|
||||
End If
|
||||
Set DxMenuReadBoundCommand = Command
|
||||
End Function
|
||||
|
||||
Function DxMenuReadStatus(ByVal Home, ByRef Record)
|
||||
Dim Status
|
||||
Set Status = DxBridgeParseJson(DxReadUtf8( _
|
||||
DxResolveRunPath(Home, CStr(Record("status")))))
|
||||
If Not DxBridgeIsDictionary(Status) Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadStatus", _
|
||||
"bridge status must be an object"
|
||||
End If
|
||||
Set DxMenuReadStatus = Status
|
||||
End Function
|
||||
|
||||
Function DxMenuDispatchAction(ByVal Home, ByRef Record, _
|
||||
ByRef Command, ByVal BaseAction, ByRef ManualRoute)
|
||||
Dim Fso
|
||||
Dim StatusPath
|
||||
Dim Status
|
||||
Dim Failure
|
||||
Set Fso = CreateObject("Scripting.FileSystemObject")
|
||||
StatusPath = DxResolveRunPath(Home, CStr(Record("status")))
|
||||
ManualRoute = ""
|
||||
If Not Fso.FileExists(StatusPath) Then
|
||||
DxMenuDispatchAction = CStr(BaseAction)
|
||||
Exit Function
|
||||
End If
|
||||
|
||||
If BaseAction <> "replace_part" And _
|
||||
BaseAction <> "undo" And BaseAction <> "save" And _
|
||||
BaseAction <> "open_project" And _
|
||||
BaseAction <> "close_project" And _
|
||||
BaseAction <> "close_without_save" Then
|
||||
DxMenuDispatchAction = CStr(BaseAction)
|
||||
Exit Function
|
||||
End If
|
||||
|
||||
Set Status = DxMenuReadStatus(Home, Record)
|
||||
If BaseAction = "replace_part" Then
|
||||
Set Failure = DxBridgeNewFailure()
|
||||
If DxBridgeValidateManualContinuation(Command, Status, _
|
||||
"manual_exact_selection", Failure) Then
|
||||
ManualRoute = "manual_exact_selection"
|
||||
DxMenuDispatchAction = "continue_after_manual_selection"
|
||||
Exit Function
|
||||
End If
|
||||
Set Failure = DxBridgeNewFailure()
|
||||
If DxBridgeValidateManualContinuation(Command, Status, _
|
||||
"manual_native_dialog", Failure) Then
|
||||
ManualRoute = "manual_native_dialog"
|
||||
DxMenuDispatchAction = "continue_after_manual_dialog"
|
||||
Exit Function
|
||||
End If
|
||||
Err.Raise vbObjectError + 795, "DxMenuDispatchAction", _
|
||||
"bridge status does not permit replacement continuation"
|
||||
End If
|
||||
|
||||
Select Case CStr(BaseAction)
|
||||
Case "undo"
|
||||
ManualRoute = "manual_native_undo"
|
||||
Case "save"
|
||||
ManualRoute = "manual_native_save"
|
||||
Case "open_project"
|
||||
ManualRoute = "manual_project_open"
|
||||
Case "close_project"
|
||||
ManualRoute = "manual_close_project"
|
||||
Case "close_without_save"
|
||||
ManualRoute = "manual_close_without_save"
|
||||
End Select
|
||||
Set Failure = DxBridgeNewFailure()
|
||||
If DxBridgeValidateManualContinuation(Command, Status, _
|
||||
ManualRoute, Failure) Then
|
||||
DxMenuDispatchAction = CStr(BaseAction)
|
||||
Exit Function
|
||||
End If
|
||||
|
||||
If BaseAction = "undo" Or BaseAction = "save" Then
|
||||
Set Failure = DxBridgeNewFailure()
|
||||
If DxBridgeValidateControlStatus(Command, Status, Failure) Then
|
||||
ManualRoute = ""
|
||||
DxMenuDispatchAction = CStr(BaseAction)
|
||||
Exit Function
|
||||
End If
|
||||
End If
|
||||
Err.Raise vbObjectError + 795, "DxMenuDispatchAction", _
|
||||
"bridge status does not permit control continuation"
|
||||
End Function
|
||||
|
||||
Sub DxMenuRequireProjectContext(ByRef Record, ByVal BaseAction, _
|
||||
ByVal ManualRoute)
|
||||
Dim Fso
|
||||
Dim ActiveValue
|
||||
Dim ActivePath
|
||||
Dim RecordPath
|
||||
Set Fso = CreateObject("Scripting.FileSystemObject")
|
||||
ActiveValue = Application.ProjectPath
|
||||
If VarType(ActiveValue) <> vbString Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuRequireProjectContext", _
|
||||
"active project path must be a string"
|
||||
End If
|
||||
If Len(CStr(ActiveValue)) = 0 Then
|
||||
If BaseAction = "open_project" And Len(CStr(ManualRoute)) = 0 Then
|
||||
Exit Sub
|
||||
End If
|
||||
If (BaseAction = "close_project" Or _
|
||||
BaseAction = "close_without_save") And _
|
||||
Len(CStr(ManualRoute)) > 0 Then
|
||||
Exit Sub
|
||||
End If
|
||||
Err.Raise vbObjectError + 795, "DxMenuRequireProjectContext", _
|
||||
"there is no active project for the current command"
|
||||
End If
|
||||
|
||||
ActivePath = DxMenuCanonicalProjectPath(Fso, ActiveValue)
|
||||
RecordPath = DxMenuCanonicalProjectPath(Fso, Record("project_path"))
|
||||
If StrComp(ActivePath, RecordPath, vbTextCompare) <> 0 Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuRequireProjectContext", _
|
||||
"active project does not match the current command"
|
||||
End If
|
||||
If BaseAction = "open_project" And _
|
||||
CStr(ManualRoute) <> "manual_project_open" Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuRequireProjectContext", _
|
||||
"project open requires a closed project or manual continuation"
|
||||
End If
|
||||
If (BaseAction = "close_project" Or _
|
||||
BaseAction = "close_without_save") And _
|
||||
Len(CStr(ManualRoute)) > 0 Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuRequireProjectContext", _
|
||||
"manual project close has not completed"
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub DxPartReplaceMenuDispatch(ByVal MenuAction)
|
||||
Dim Home
|
||||
Dim Manifest
|
||||
Dim Record
|
||||
Dim Command
|
||||
Dim BaseAction
|
||||
Dim DispatchAction
|
||||
Dim ManualRoute
|
||||
Dim ProfilePath
|
||||
Dim CommandPath
|
||||
Dim StatusPath
|
||||
Dim SnapshotPath
|
||||
Home = DxMenuHome()
|
||||
Set Manifest = DxMenuReadManifest(Home)
|
||||
BaseAction = CStr(Manifest("current_action"))
|
||||
If CStr(MenuAction) = "inventory" And _
|
||||
BaseAction <> "inventory" Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuBridge", _
|
||||
"inventory menu action is not the current command"
|
||||
End If
|
||||
Set Record = DxMenuReadManifestRecord(Manifest, Home)
|
||||
Set Command = DxMenuReadBoundCommand(Home, Manifest, Record)
|
||||
DispatchAction = DxMenuDispatchAction(Home, Record, Command, _
|
||||
BaseAction, ManualRoute)
|
||||
DxMenuRequireProjectContext Record, BaseAction, ManualRoute
|
||||
ProfilePath = CStr(Record("profile"))
|
||||
CommandPath = CStr(Record("command"))
|
||||
StatusPath = CStr(Record("status"))
|
||||
SnapshotPath = CStr(Record("snapshot"))
|
||||
If BaseAction = "open_project" Then
|
||||
DxRunPartReplaceBridge DispatchAction, ProfilePath, CommandPath, _
|
||||
StatusPath, SnapshotPath, CStr(Record("project_path"))
|
||||
Else
|
||||
DxRunPartReplaceBridge DispatchAction, ProfilePath, CommandPath, _
|
||||
StatusPath, SnapshotPath, ""
|
||||
End If
|
||||
End Sub
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,152 @@
|
||||
function Assert-ExactObject {
|
||||
param([object]$Value, [string[]]$Fields, [string]$Context)
|
||||
if ($null -eq $Value -or
|
||||
$Value -isnot [System.Management.Automation.PSCustomObject]) {
|
||||
throw "$Context must be an object"
|
||||
}
|
||||
$actual = @($Value.PSObject.Properties.Name)
|
||||
if ($actual.Count -ne $Fields.Count) {
|
||||
throw "$Context fields are invalid"
|
||||
}
|
||||
foreach ($field in $Fields) {
|
||||
if (-not ($actual -ccontains $field)) {
|
||||
throw "$Context is missing $field"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-OptionalString {
|
||||
param([object]$Value, [string]$Name)
|
||||
if ($null -ne $Value -and
|
||||
($Value -isnot [string] -or [string]::IsNullOrWhiteSpace($Value))) {
|
||||
throw "$Name must be null or a nonempty string"
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-OperatorStepResult {
|
||||
param([object]$Step, [string]$ExpectedJobId)
|
||||
Assert-ExactObject $Step @(
|
||||
"bridge_state", "command", "complete", "consumed_action",
|
||||
"instruction", "manual_route", "project", "state"
|
||||
) "operator-step result"
|
||||
if ($Step.complete -isnot [bool]) {
|
||||
throw "operator-step complete must be Boolean"
|
||||
}
|
||||
foreach ($name in @(
|
||||
"bridge_state", "consumed_action", "instruction", "manual_route"
|
||||
)) {
|
||||
Assert-OptionalString $Step.$name "operator-step $name"
|
||||
}
|
||||
if ($Step.complete) {
|
||||
if ($null -ne $Step.command -or $null -ne $Step.project -or
|
||||
$null -ne $Step.state) {
|
||||
throw "completed operator-step must not expose a current command"
|
||||
}
|
||||
return
|
||||
}
|
||||
Assert-ExactObject $Step.project @(
|
||||
"display_name", "project_id", "project_path"
|
||||
) "operator-step project"
|
||||
foreach ($name in @("display_name", "project_id", "project_path")) {
|
||||
if ($Step.project.$name -isnot [string] -or
|
||||
[string]::IsNullOrWhiteSpace($Step.project.$name)) {
|
||||
throw "operator-step project $name is invalid"
|
||||
}
|
||||
}
|
||||
if ($Step.state -isnot [string] -or
|
||||
[string]::IsNullOrWhiteSpace($Step.state)) {
|
||||
throw "operator-step state is invalid"
|
||||
}
|
||||
Assert-ExactObject $Step.command @(
|
||||
"action", "command_id", "expected_count", "expected_fingerprint",
|
||||
"expected_logical_keys", "format_version", "job_id",
|
||||
"new_part_number", "old_part_number", "project_id", "scope"
|
||||
) "operator-step command"
|
||||
foreach ($name in @(
|
||||
"action", "command_id", "expected_fingerprint", "job_id",
|
||||
"new_part_number", "old_part_number", "project_id", "scope"
|
||||
)) {
|
||||
if ($Step.command.$name -isnot [string]) {
|
||||
throw "operator-step command $name is invalid"
|
||||
}
|
||||
}
|
||||
if ($Step.command.action -notin @(
|
||||
"close_project", "close_without_save", "erc", "inventory",
|
||||
"netlist", "open_project", "packager", "replace_part", "save",
|
||||
"undo"
|
||||
)) {
|
||||
throw "operator-step command action is unsupported"
|
||||
}
|
||||
if ($Step.command.command_id -notmatch '^[0-9a-f]{32}$') {
|
||||
throw "operator-step command_id is invalid"
|
||||
}
|
||||
if ($Step.command.format_version -ne 1 -or
|
||||
$Step.command.format_version -isnot [int]) {
|
||||
throw "operator-step command format_version is invalid"
|
||||
}
|
||||
if ($Step.command.expected_count -isnot [int] -or
|
||||
$Step.command.expected_count -lt 0) {
|
||||
throw "operator-step expected_count is invalid"
|
||||
}
|
||||
$expectedKeys = @($Step.command.expected_logical_keys)
|
||||
if ($expectedKeys.Count -ne $Step.command.expected_count -or
|
||||
@($expectedKeys | Where-Object { $_ -isnot [string] }).Count -ne 0) {
|
||||
throw "operator-step expected logical keys are invalid"
|
||||
}
|
||||
if ($Step.command.scope -cne "full_project" -or
|
||||
$Step.command.job_id -cne $ExpectedJobId -or
|
||||
$Step.command.project_id -cne $Step.project.project_id) {
|
||||
throw "operator-step command identity is invalid"
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-ResumeStatus {
|
||||
param([object]$Status)
|
||||
Assert-ExactObject $Status @("job_id", "projects") "status result"
|
||||
if ($Status.job_id -isnot [string] -or
|
||||
[string]::IsNullOrWhiteSpace($Status.job_id)) {
|
||||
throw "status result job_id is invalid"
|
||||
}
|
||||
if ($Status.projects -isnot [object[]] -or
|
||||
$Status.projects.Count -eq 0) {
|
||||
throw "status result projects must be a nonempty array"
|
||||
}
|
||||
$allowedActions = @(
|
||||
"await_inventory", "complete", "confirm-erc", "confirm-netlist",
|
||||
"confirm-packager", "confirm-saved", "confirm-undo", "ingest",
|
||||
"prepare", "prepare-close", "prepare-erc", "prepare-netlist",
|
||||
"prepare-open", "prepare-packager", "prepare-save", "prepare-undo",
|
||||
"reconcile"
|
||||
)
|
||||
$allowedStates = @(
|
||||
"apply_pending", "applying", "awaiting_external_checks",
|
||||
"awaiting_save_confirmation", "blocked", "inventory_complete",
|
||||
"inventory_pending", "verified_saved"
|
||||
)
|
||||
foreach ($project in $Status.projects) {
|
||||
Assert-ExactObject $project @(
|
||||
"action", "display_name", "project_id", "project_path", "state"
|
||||
) "status project"
|
||||
foreach ($name in @(
|
||||
"action", "display_name", "project_id", "project_path", "state"
|
||||
)) {
|
||||
if ($project.$name -isnot [string] -or
|
||||
[string]::IsNullOrWhiteSpace($project.$name)) {
|
||||
throw "status project $name is invalid"
|
||||
}
|
||||
}
|
||||
if ($project.action -cnotin $allowedActions) {
|
||||
throw "status project action is invalid"
|
||||
}
|
||||
if ($project.state -cnotin $allowedStates) {
|
||||
throw "status project state is invalid"
|
||||
}
|
||||
if (-not [IO.Path]::IsPathRooted([string]$project.project_path)) {
|
||||
throw "status project path must be absolute"
|
||||
}
|
||||
if (($project.state -ceq "verified_saved") -ne
|
||||
($project.action -ceq "complete")) {
|
||||
throw "status project completion is inconsistent"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
function Assert-DxNoReparsePath {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Value,
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Name
|
||||
)
|
||||
|
||||
$absolute = [IO.Path]::GetFullPath($Value)
|
||||
$driveRoot = [IO.Path]::GetPathRoot($absolute)
|
||||
if ([string]::IsNullOrWhiteSpace($driveRoot) -or
|
||||
$driveRoot -notmatch '^[A-Za-z]:\\$') {
|
||||
throw "$Name must use a local drive: $absolute"
|
||||
}
|
||||
|
||||
$current = $driveRoot
|
||||
$remaining = $absolute.Substring($driveRoot.Length)
|
||||
$parts = $remaining.Split(
|
||||
[char[]]@('\', '/'),
|
||||
[StringSplitOptions]::RemoveEmptyEntries
|
||||
)
|
||||
foreach ($part in $parts) {
|
||||
$current = Join-Path $current $part
|
||||
try {
|
||||
$attributes = [IO.File]::GetAttributes($current)
|
||||
}
|
||||
catch {
|
||||
$pathFailure = $_.Exception
|
||||
while ($null -ne $pathFailure.InnerException) {
|
||||
$pathFailure = $pathFailure.InnerException
|
||||
}
|
||||
if ($pathFailure -is [IO.FileNotFoundException] -or
|
||||
$pathFailure -is [IO.DirectoryNotFoundException]) {
|
||||
return
|
||||
}
|
||||
throw "$Name cannot be validated at: $current"
|
||||
}
|
||||
if (($attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) {
|
||||
throw "$Name contains a reparse point: $current"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (-not ("DxProductivity.PathSafetyNative" -as [type])) {
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace DxProductivity
|
||||
{
|
||||
public static class PathSafetyNative
|
||||
{
|
||||
private const uint FileReadAttributes = 0x00000080;
|
||||
private const uint GenericRead = 0x80000000;
|
||||
private const uint GenericWrite = 0x40000000;
|
||||
private const uint DeleteAccess = 0x00010000;
|
||||
private const uint FileShareRead = 0x00000001;
|
||||
private const uint FileShareWrite = 0x00000002;
|
||||
private const uint FileShareDelete = 0x00000004;
|
||||
private const uint CreateNew = 1;
|
||||
private const uint OpenExisting = 3;
|
||||
private const uint FileAttributeNormal = 0x00000080;
|
||||
private const uint FileFlagBackupSemantics = 0x02000000;
|
||||
private const uint FileFlagOpenReparsePoint = 0x00200000;
|
||||
private const int FileDispositionInfo = 4;
|
||||
private const int NativeFileRenameInformation = 10;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct IoStatusBlock
|
||||
{
|
||||
public IntPtr Status;
|
||||
public UIntPtr Information;
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern IntPtr CreateFile(
|
||||
string fileName,
|
||||
uint desiredAccess,
|
||||
uint shareMode,
|
||||
IntPtr securityAttributes,
|
||||
uint creationDisposition,
|
||||
uint flagsAndAttributes,
|
||||
IntPtr templateFile
|
||||
);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
public static extern bool CloseHandle(IntPtr handle);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern uint GetFinalPathNameByHandle(
|
||||
IntPtr handle,
|
||||
StringBuilder path,
|
||||
uint pathLength,
|
||||
uint flags
|
||||
);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool WriteFile(
|
||||
IntPtr handle,
|
||||
byte[] buffer,
|
||||
uint bytesToWrite,
|
||||
out uint bytesWritten,
|
||||
IntPtr overlapped
|
||||
);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool FlushFileBuffers(IntPtr handle);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool SetFileInformationByHandle(
|
||||
IntPtr handle,
|
||||
int informationClass,
|
||||
IntPtr information,
|
||||
uint bufferSize
|
||||
);
|
||||
|
||||
[DllImport("ntdll.dll")]
|
||||
private static extern int NtSetInformationFile(
|
||||
IntPtr handle,
|
||||
out IoStatusBlock ioStatus,
|
||||
IntPtr information,
|
||||
uint length,
|
||||
int informationClass
|
||||
);
|
||||
|
||||
[DllImport("ntdll.dll")]
|
||||
private static extern uint RtlNtStatusToDosError(int status);
|
||||
|
||||
public static IntPtr OpenDirectory(string path, bool denyRename)
|
||||
{
|
||||
uint access = FileReadAttributes;
|
||||
if (denyRename)
|
||||
{
|
||||
access |= DeleteAccess;
|
||||
}
|
||||
return CreateFile(
|
||||
path,
|
||||
access,
|
||||
FileShareRead | FileShareWrite,
|
||||
IntPtr.Zero,
|
||||
OpenExisting,
|
||||
FileFlagBackupSemantics | FileFlagOpenReparsePoint,
|
||||
IntPtr.Zero
|
||||
);
|
||||
}
|
||||
|
||||
public static IntPtr OpenStagedFile(string path)
|
||||
{
|
||||
IntPtr handle = CreateFile(
|
||||
path,
|
||||
GenericRead | GenericWrite | DeleteAccess,
|
||||
FileShareRead | FileShareDelete,
|
||||
IntPtr.Zero,
|
||||
CreateNew,
|
||||
FileAttributeNormal,
|
||||
IntPtr.Zero
|
||||
);
|
||||
if (handle == new IntPtr(-1))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
return handle;
|
||||
}
|
||||
|
||||
public static void WriteStagedFile(IntPtr handle, byte[] bytes)
|
||||
{
|
||||
if (bytes.LongLength > UInt32.MaxValue)
|
||||
{
|
||||
throw new IOException("Atomic publication payload is too large");
|
||||
}
|
||||
uint written;
|
||||
if (!WriteFile(handle, bytes, (uint)bytes.Length, out written,
|
||||
IntPtr.Zero))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
if (written != bytes.Length)
|
||||
{
|
||||
throw new IOException("Atomic publication staging write was incomplete");
|
||||
}
|
||||
if (!FlushFileBuffers(handle))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
}
|
||||
|
||||
public static void PublishStagedFile(
|
||||
IntPtr stagedHandle,
|
||||
IntPtr parentHandle,
|
||||
string destinationName
|
||||
)
|
||||
{
|
||||
if (String.IsNullOrEmpty(destinationName) ||
|
||||
destinationName == "." || destinationName == ".." ||
|
||||
destinationName.IndexOf('\\') >= 0 ||
|
||||
destinationName.IndexOf('/') >= 0)
|
||||
{
|
||||
throw new ArgumentException("Invalid atomic publication name");
|
||||
}
|
||||
byte[] name = Encoding.Unicode.GetBytes(destinationName);
|
||||
int pointerSize = IntPtr.Size;
|
||||
int rootOffset = (sizeof(uint) + pointerSize - 1) & -pointerSize;
|
||||
int lengthOffset = rootOffset + pointerSize;
|
||||
int nameOffset = lengthOffset + sizeof(uint);
|
||||
int bufferSize = nameOffset + name.Length + sizeof(char);
|
||||
IntPtr information = Marshal.AllocHGlobal(bufferSize);
|
||||
try
|
||||
{
|
||||
for (int index = 0; index < bufferSize; index++)
|
||||
{
|
||||
Marshal.WriteByte(information, index, 0);
|
||||
}
|
||||
Marshal.WriteByte(information, 0, 1);
|
||||
Marshal.WriteIntPtr(information, rootOffset, parentHandle);
|
||||
Marshal.WriteInt32(information, lengthOffset, name.Length);
|
||||
Marshal.Copy(name, 0, IntPtr.Add(information, nameOffset),
|
||||
name.Length);
|
||||
IoStatusBlock ioStatus;
|
||||
int status = NtSetInformationFile(
|
||||
stagedHandle,
|
||||
out ioStatus,
|
||||
information,
|
||||
(uint)bufferSize,
|
||||
NativeFileRenameInformation
|
||||
);
|
||||
if (status < 0)
|
||||
{
|
||||
throw new Win32Exception(
|
||||
(int)RtlNtStatusToDosError(status)
|
||||
);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.FreeHGlobal(information);
|
||||
}
|
||||
}
|
||||
|
||||
public static void DeleteStagedFile(IntPtr stagedHandle)
|
||||
{
|
||||
IntPtr disposition = Marshal.AllocHGlobal(1);
|
||||
try
|
||||
{
|
||||
Marshal.WriteByte(disposition, 1);
|
||||
if (!SetFileInformationByHandle(
|
||||
stagedHandle,
|
||||
FileDispositionInfo,
|
||||
disposition,
|
||||
1))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.FreeHGlobal(disposition);
|
||||
}
|
||||
}
|
||||
|
||||
public static string FinalPath(IntPtr handle)
|
||||
{
|
||||
uint capacity = 512;
|
||||
while (true)
|
||||
{
|
||||
StringBuilder buffer = new StringBuilder((int)capacity);
|
||||
uint result = GetFinalPathNameByHandle(
|
||||
handle,
|
||||
buffer,
|
||||
capacity,
|
||||
0
|
||||
);
|
||||
if (result == 0)
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
if (result < capacity)
|
||||
{
|
||||
return buffer.ToString();
|
||||
}
|
||||
capacity = result + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
'@
|
||||
}
|
||||
|
||||
function Convert-DxHandlePath {
|
||||
param([string]$Value)
|
||||
$text = $Value
|
||||
if ($text.StartsWith("\\?\UNC\", [StringComparison]::OrdinalIgnoreCase)) {
|
||||
$text = "\\" + $text.Substring(8)
|
||||
}
|
||||
elseif ($text.StartsWith("\\?\", [StringComparison]::OrdinalIgnoreCase)) {
|
||||
$text = $text.Substring(4)
|
||||
}
|
||||
return ([IO.Path]::GetFullPath($text)).TrimEnd('\')
|
||||
}
|
||||
|
||||
function Close-DxPublicationLock {
|
||||
param([object]$Lock)
|
||||
if ($null -eq $Lock) {
|
||||
return
|
||||
}
|
||||
for ($index = $Lock.Handles.Count - 1; $index -ge 0; $index--) {
|
||||
[void][DxProductivity.PathSafetyNative]::CloseHandle(
|
||||
$Lock.Handles[$index]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function Remove-DxStagedIdentity {
|
||||
param([IntPtr]$Handle)
|
||||
[DxProductivity.PathSafetyNative]::DeleteStagedFile($Handle)
|
||||
}
|
||||
|
||||
function Open-DxDirectoryLock {
|
||||
param(
|
||||
[string]$Path,
|
||||
[bool]$DenyRename,
|
||||
[string]$Name
|
||||
)
|
||||
$handle = [DxProductivity.PathSafetyNative]::OpenDirectory(
|
||||
$Path,
|
||||
$DenyRename
|
||||
)
|
||||
if ($handle -eq [IntPtr](-1)) {
|
||||
$errorCode = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
|
||||
throw "$Name cannot lock directory: $Path (Windows error $errorCode)"
|
||||
}
|
||||
try {
|
||||
$expected = ([IO.Path]::GetFullPath($Path)).TrimEnd('\')
|
||||
$actual = Convert-DxHandlePath (
|
||||
[DxProductivity.PathSafetyNative]::FinalPath($handle)
|
||||
)
|
||||
if (-not [string]::Equals(
|
||||
$expected,
|
||||
$actual,
|
||||
[StringComparison]::OrdinalIgnoreCase
|
||||
)) {
|
||||
throw "$Name directory handle resolves outside its lexical path: $Path"
|
||||
}
|
||||
Assert-DxNoReparsePath $Path $Name
|
||||
return $handle
|
||||
}
|
||||
catch {
|
||||
[void][DxProductivity.PathSafetyNative]::CloseHandle($handle)
|
||||
throw
|
||||
}
|
||||
}
|
||||
|
||||
function Enter-DxPublicationLock {
|
||||
param([string]$Destination, [string]$Name)
|
||||
$absolute = [IO.Path]::GetFullPath($Destination)
|
||||
$directory = Split-Path -Parent $absolute
|
||||
$driveRoot = [IO.Path]::GetPathRoot($directory)
|
||||
Assert-DxNoReparsePath $absolute $Name
|
||||
if ([string]::IsNullOrWhiteSpace($driveRoot) -or
|
||||
[string]::Equals(
|
||||
$directory.TrimEnd('\'),
|
||||
$driveRoot.TrimEnd('\'),
|
||||
[StringComparison]::OrdinalIgnoreCase
|
||||
)) {
|
||||
throw "$Name destination parent must be below a local drive root"
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $directory -PathType Container)) {
|
||||
throw "$Name destination directory does not exist: $directory"
|
||||
}
|
||||
|
||||
$handles = New-Object 'Collections.Generic.List[IntPtr]'
|
||||
$publicationLock = [pscustomobject]@{
|
||||
Handles = $handles
|
||||
Directory = $directory
|
||||
}
|
||||
try {
|
||||
$current = $driveRoot
|
||||
$handles.Add((Open-DxDirectoryLock $current $false $Name))
|
||||
$remaining = $directory.Substring($driveRoot.Length)
|
||||
$parts = $remaining.Split(
|
||||
[char[]]@('\', '/'),
|
||||
[StringSplitOptions]::RemoveEmptyEntries
|
||||
)
|
||||
for ($index = 0; $index -lt $parts.Count; $index++) {
|
||||
$current = Join-Path $current $parts[$index]
|
||||
$denyRename = $index -eq $parts.Count - 1
|
||||
$handles.Add((
|
||||
Open-DxDirectoryLock $current $denyRename $Name
|
||||
))
|
||||
}
|
||||
Assert-DxNoReparsePath $absolute $Name
|
||||
return $publicationLock
|
||||
}
|
||||
catch {
|
||||
Close-DxPublicationLock $publicationLock
|
||||
throw
|
||||
}
|
||||
}
|
||||
|
||||
function Write-DxBytesAtomic {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Destination,
|
||||
[Parameter(Mandatory = $true)]
|
||||
[byte[]]$Bytes,
|
||||
[scriptblock]$AfterValidation
|
||||
)
|
||||
$absolute = [IO.Path]::GetFullPath($Destination)
|
||||
$publicationLock = $null
|
||||
$temporary = $null
|
||||
$stagedHandle = [IntPtr](-1)
|
||||
$published = $false
|
||||
$primaryError = $null
|
||||
$cleanupError = $null
|
||||
try {
|
||||
$publicationLock = Enter-DxPublicationLock $absolute `
|
||||
"atomic publication"
|
||||
$temporary = Join-Path $publicationLock.Directory (
|
||||
"." + [IO.Path]::GetFileName($absolute) + "." +
|
||||
[guid]::NewGuid().ToString("N") + ".tmp"
|
||||
)
|
||||
$stagedHandle = [DxProductivity.PathSafetyNative]::OpenStagedFile(
|
||||
$temporary
|
||||
)
|
||||
[DxProductivity.PathSafetyNative]::WriteStagedFile(
|
||||
$stagedHandle,
|
||||
$Bytes
|
||||
)
|
||||
$expectedTemporary = ([IO.Path]::GetFullPath($temporary)).TrimEnd('\')
|
||||
$actualTemporary = Convert-DxHandlePath (
|
||||
[DxProductivity.PathSafetyNative]::FinalPath($stagedHandle)
|
||||
)
|
||||
if (-not [string]::Equals(
|
||||
$expectedTemporary,
|
||||
$actualTemporary,
|
||||
[StringComparison]::OrdinalIgnoreCase
|
||||
)) {
|
||||
throw "atomic publication staging handle changed identity"
|
||||
}
|
||||
Assert-DxNoReparsePath $temporary "atomic publication temporary file"
|
||||
Assert-DxNoReparsePath $absolute "atomic publication destination"
|
||||
if ($null -ne $AfterValidation) {
|
||||
& $AfterValidation $absolute $temporary
|
||||
}
|
||||
$parentHandle = $publicationLock.Handles[
|
||||
$publicationLock.Handles.Count - 1
|
||||
]
|
||||
[DxProductivity.PathSafetyNative]::PublishStagedFile(
|
||||
$stagedHandle,
|
||||
$parentHandle,
|
||||
[IO.Path]::GetFileName($absolute)
|
||||
)
|
||||
$published = $true
|
||||
}
|
||||
catch {
|
||||
$primaryError = $_.Exception
|
||||
}
|
||||
finally {
|
||||
try {
|
||||
if ($stagedHandle -ne [IntPtr](-1) -and -not $published) {
|
||||
try {
|
||||
Remove-DxStagedIdentity $stagedHandle
|
||||
}
|
||||
catch {
|
||||
$cleanupError = $_.Exception
|
||||
}
|
||||
}
|
||||
}
|
||||
finally {
|
||||
try {
|
||||
if ($stagedHandle -ne [IntPtr](-1)) {
|
||||
[void][DxProductivity.PathSafetyNative]::CloseHandle(
|
||||
$stagedHandle
|
||||
)
|
||||
}
|
||||
}
|
||||
finally {
|
||||
Close-DxPublicationLock $publicationLock
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($null -ne $primaryError) {
|
||||
throw $primaryError
|
||||
}
|
||||
if ($null -ne $cleanupError) {
|
||||
throw $cleanupError
|
||||
}
|
||||
}
|
||||
|
||||
function Write-DxUtf8Atomic {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Destination,
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Text,
|
||||
[scriptblock]$AfterValidation
|
||||
)
|
||||
$utf8 = New-Object Text.UTF8Encoding($false)
|
||||
Write-DxBytesAtomic -Destination $Destination -Bytes $utf8.GetBytes($Text) `
|
||||
-AfterValidation $AfterValidation
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,460 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$Mapping,
|
||||
[string]$Projects,
|
||||
[string]$DiscoveryRoot,
|
||||
[string]$CompatibilityProfile,
|
||||
[string]$PythonExecutable,
|
||||
[string]$RunRoot,
|
||||
[string]$DXToolsHome,
|
||||
[string]$Certifications,
|
||||
[string]$SettingsRoot,
|
||||
[string]$ResumeJob,
|
||||
[switch]$WhatIf
|
||||
)
|
||||
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = "Stop"
|
||||
[Console]::OutputEncoding = New-Object Text.UTF8Encoding($false)
|
||||
. (Join-Path $PSScriptRoot "PathSafety.ps1")
|
||||
. (Join-Path $PSScriptRoot "PartReplacementContract.ps1")
|
||||
|
||||
function Resolve-FullPath {
|
||||
param([string]$Value)
|
||||
return [IO.Path]::GetFullPath($Value)
|
||||
}
|
||||
|
||||
function Resolve-RequiredPath {
|
||||
param([string]$Value, [string]$Name)
|
||||
if ([string]::IsNullOrWhiteSpace($Value)) {
|
||||
throw "$Name is required"
|
||||
}
|
||||
$resolved = Resolve-FullPath $Value
|
||||
Assert-DxNoReparsePath $resolved $Name
|
||||
return $resolved
|
||||
}
|
||||
|
||||
function Test-SamePath {
|
||||
param([string]$Left, [string]$Right)
|
||||
return [string]::Equals(
|
||||
(Resolve-FullPath $Left).TrimEnd('\'),
|
||||
(Resolve-FullPath $Right).TrimEnd('\'),
|
||||
[StringComparison]::OrdinalIgnoreCase
|
||||
)
|
||||
}
|
||||
|
||||
function Test-DirectChildPath {
|
||||
param([string]$Parent, [string]$Child)
|
||||
$childParent = Split-Path -Parent (Resolve-FullPath $Child)
|
||||
return Test-SamePath $Parent $childParent
|
||||
}
|
||||
|
||||
function Convert-ToRunRelativePath {
|
||||
param([string]$ToolRoot, [string]$Path, [string]$Name)
|
||||
$resolvedRoot = Resolve-FullPath $ToolRoot
|
||||
Assert-DxNoReparsePath $resolvedRoot "DXTOOLS_HOME"
|
||||
$homePrefix = $resolvedRoot.TrimEnd('\') + "\"
|
||||
$resolved = Resolve-FullPath $Path
|
||||
Assert-DxNoReparsePath $resolved $Name
|
||||
if (-not $resolved.StartsWith(
|
||||
$homePrefix,
|
||||
[StringComparison]::OrdinalIgnoreCase
|
||||
)) {
|
||||
throw "$Name must be under DXTOOLS_HOME: $resolved"
|
||||
}
|
||||
return $resolved.Substring($homePrefix.Length).Replace('\', '/')
|
||||
}
|
||||
|
||||
function Read-Settings {
|
||||
param([string]$Base)
|
||||
$resolvedBase = Resolve-FullPath $Base
|
||||
Assert-DxNoReparsePath $resolvedBase "settings root"
|
||||
$settingsPath = Join-Path (Join-Path $resolvedBase "DxProductivity") "settings.json"
|
||||
Assert-DxNoReparsePath $settingsPath "settings path"
|
||||
try {
|
||||
$settings = Get-Content -LiteralPath $settingsPath -Raw -Encoding UTF8 |
|
||||
ConvertFrom-Json -ErrorAction Stop
|
||||
}
|
||||
catch {
|
||||
throw "settings are invalid or missing: $settingsPath"
|
||||
}
|
||||
Assert-ExactObject $settings @(
|
||||
"compatibility_profile", "dxtools_home", "python_executable", "run_root"
|
||||
) "settings"
|
||||
foreach ($name in @(
|
||||
"compatibility_profile", "dxtools_home", "python_executable", "run_root"
|
||||
)) {
|
||||
if ($settings.$name -isnot [string] -or
|
||||
[string]::IsNullOrWhiteSpace($settings.$name)) {
|
||||
throw "settings field is invalid: $name"
|
||||
}
|
||||
}
|
||||
return $settings
|
||||
}
|
||||
|
||||
$needsSettings = [string]::IsNullOrWhiteSpace($CompatibilityProfile) -or
|
||||
[string]::IsNullOrWhiteSpace($PythonExecutable) -or
|
||||
[string]::IsNullOrWhiteSpace($RunRoot) -or
|
||||
[string]::IsNullOrWhiteSpace($DXToolsHome)
|
||||
if ($needsSettings) {
|
||||
if ([string]::IsNullOrWhiteSpace($SettingsRoot)) {
|
||||
$SettingsRoot = [Environment]::GetFolderPath(
|
||||
[Environment+SpecialFolder]::LocalApplicationData
|
||||
)
|
||||
}
|
||||
$settingsBase = Resolve-FullPath $SettingsRoot
|
||||
Assert-DxNoReparsePath $settingsBase "settings root"
|
||||
$settings = Read-Settings $settingsBase
|
||||
if ([string]::IsNullOrWhiteSpace($CompatibilityProfile)) {
|
||||
$CompatibilityProfile = $settings.compatibility_profile
|
||||
}
|
||||
if ([string]::IsNullOrWhiteSpace($PythonExecutable)) {
|
||||
$PythonExecutable = $settings.python_executable
|
||||
}
|
||||
if ([string]::IsNullOrWhiteSpace($RunRoot)) {
|
||||
$RunRoot = $settings.run_root
|
||||
}
|
||||
if ([string]::IsNullOrWhiteSpace($DXToolsHome)) {
|
||||
$DXToolsHome = $settings.dxtools_home
|
||||
}
|
||||
}
|
||||
|
||||
$toolHome = Resolve-RequiredPath $DXToolsHome "DXToolsHome"
|
||||
$run = Resolve-RequiredPath $RunRoot "RunRoot"
|
||||
$profile = Resolve-RequiredPath $CompatibilityProfile "CompatibilityProfile"
|
||||
$python = Resolve-RequiredPath $PythonExecutable "PythonExecutable"
|
||||
if (-not (Test-Path -LiteralPath $toolHome -PathType Container)) {
|
||||
throw "DXTOOLS_HOME does not exist: $toolHome"
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $python -PathType Leaf)) {
|
||||
throw "PythonExecutable does not exist: $python"
|
||||
}
|
||||
|
||||
$deployedRun = Join-Path $toolHome "runs"
|
||||
$deployedProfile = Join-Path $deployedRun "compatibility-profile.json"
|
||||
Assert-DxNoReparsePath $deployedRun "deployed run root"
|
||||
Assert-DxNoReparsePath $deployedProfile "deployed compatibility profile"
|
||||
if (-not (Test-SamePath $run $deployedRun)) {
|
||||
throw "RunRoot must use the deployed DXTOOLS_HOME runs directory"
|
||||
}
|
||||
if (-not (Test-SamePath $profile $deployedProfile)) {
|
||||
throw "CompatibilityProfile must use the deployed compatibility profile"
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $deployedProfile -PathType Leaf)) {
|
||||
throw "deployed compatibility profile does not exist: $deployedProfile"
|
||||
}
|
||||
|
||||
$discovery = $null
|
||||
$mappingPath = $null
|
||||
$projectsPath = $null
|
||||
$certificationPath = $null
|
||||
$resume = $null
|
||||
$resumeMode = -not [string]::IsNullOrWhiteSpace($ResumeJob)
|
||||
if ($resumeMode) {
|
||||
foreach ($value in @($Mapping, $Projects, $Certifications, $DiscoveryRoot)) {
|
||||
if (-not [string]::IsNullOrWhiteSpace($value)) {
|
||||
throw "ResumeJob cannot be combined with create or discovery inputs"
|
||||
}
|
||||
}
|
||||
if (-not [IO.Path]::IsPathRooted($ResumeJob)) {
|
||||
throw "ResumeJob must be an absolute job directory"
|
||||
}
|
||||
$resume = Resolve-RequiredPath $ResumeJob "ResumeJob"
|
||||
if (-not (Test-DirectChildPath $deployedRun $resume)) {
|
||||
throw "ResumeJob must be a direct child of the deployed run root"
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $resume -PathType Container)) {
|
||||
throw "ResumeJob does not exist: $resume"
|
||||
}
|
||||
}
|
||||
elseif (-not [string]::IsNullOrWhiteSpace($DiscoveryRoot)) {
|
||||
$discovery = Resolve-RequiredPath $DiscoveryRoot "DiscoveryRoot"
|
||||
}
|
||||
else {
|
||||
$mappingPath = Resolve-RequiredPath $Mapping "Mapping"
|
||||
$projectsPath = Resolve-RequiredPath $Projects "Projects"
|
||||
$certificationPath = Resolve-RequiredPath $Certifications "Certifications"
|
||||
}
|
||||
|
||||
if ($null -ne $mappingPath) {
|
||||
Write-Output "Mapping=$mappingPath"
|
||||
Write-Output "Certifications=$certificationPath"
|
||||
}
|
||||
if ($null -ne $resume) {
|
||||
Write-Output "ResumeJob=$resume"
|
||||
}
|
||||
Write-Output "CompatibilityProfile=$deployedProfile"
|
||||
Write-Output "PythonExecutable=$python"
|
||||
Write-Output "RunRoot=$deployedRun"
|
||||
Write-Output "DXToolsHome=$toolHome"
|
||||
if ($null -ne $discovery) {
|
||||
Write-Output "DiscoveryRoot=$discovery"
|
||||
}
|
||||
elseif ($null -ne $projectsPath) {
|
||||
Write-Output "Projects=$projectsPath"
|
||||
}
|
||||
if ($WhatIf) {
|
||||
exit 0
|
||||
}
|
||||
|
||||
Assert-DxNoReparsePath $toolHome "DXTOOLS_HOME"
|
||||
Assert-DxNoReparsePath $deployedRun "deployed run root"
|
||||
Assert-DxNoReparsePath $deployedProfile "deployed compatibility profile"
|
||||
Assert-DxNoReparsePath $python "PythonExecutable"
|
||||
if ($null -ne $resume) {
|
||||
Assert-DxNoReparsePath $resume "ResumeJob"
|
||||
}
|
||||
elseif ($null -ne $discovery) {
|
||||
Assert-DxNoReparsePath $discovery "DiscoveryRoot"
|
||||
}
|
||||
else {
|
||||
Assert-DxNoReparsePath $mappingPath "Mapping"
|
||||
Assert-DxNoReparsePath $projectsPath "Projects"
|
||||
Assert-DxNoReparsePath $certificationPath "Certifications"
|
||||
}
|
||||
New-Item -ItemType Directory -Force -Path $deployedRun | Out-Null
|
||||
if ($null -ne $discovery) {
|
||||
$discoveredProjects = Join-Path $deployedRun "discovered-projects.txt"
|
||||
Assert-DxNoReparsePath $python "PythonExecutable"
|
||||
Assert-DxNoReparsePath $discovery "DiscoveryRoot"
|
||||
Assert-DxNoReparsePath $discoveredProjects "discovery output"
|
||||
$discoverArguments = @(
|
||||
"-m", "dx_productivity", "discover", $discovery,
|
||||
"--output", $discoveredProjects
|
||||
)
|
||||
& $python @discoverArguments
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
Write-Output "GeneratedProjects=$discoveredProjects"
|
||||
Write-Output "Review discovered candidates before creating a job."
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($null -ne $resume) {
|
||||
$job = $resume
|
||||
Assert-DxNoReparsePath $python "PythonExecutable"
|
||||
Assert-DxNoReparsePath $job "job directory"
|
||||
$statusArguments = @(
|
||||
"-m", "dx_productivity", "--json", "status", $job
|
||||
)
|
||||
$statusOutput = @(& $python @statusArguments)
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
try {
|
||||
$resumeStatus = [string]::Join(
|
||||
[Environment]::NewLine,
|
||||
$statusOutput
|
||||
) | ConvertFrom-Json -ErrorAction Stop
|
||||
}
|
||||
catch {
|
||||
throw "status did not return valid JSON"
|
||||
}
|
||||
Assert-ResumeStatus $resumeStatus
|
||||
if ([string]$resumeStatus.job_id -cne (Split-Path -Leaf $job)) {
|
||||
throw "status result job_id does not match ResumeJob"
|
||||
}
|
||||
$jobId = [string]$resumeStatus.job_id
|
||||
$projectRecords = @(
|
||||
$resumeStatus.projects | ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
display_name = [string]$_.display_name
|
||||
project_id = [string]$_.project_id
|
||||
project_path = [string]$_.project_path
|
||||
}
|
||||
}
|
||||
)
|
||||
$projectContext = "status"
|
||||
}
|
||||
else {
|
||||
$job = Join-Path $deployedRun (
|
||||
"part-replace-" + [guid]::NewGuid().ToString("N")
|
||||
)
|
||||
Assert-DxNoReparsePath $python "PythonExecutable"
|
||||
Assert-DxNoReparsePath $mappingPath "Mapping"
|
||||
Assert-DxNoReparsePath $projectsPath "Projects"
|
||||
Assert-DxNoReparsePath $certificationPath "Certifications"
|
||||
Assert-DxNoReparsePath $job "job directory"
|
||||
$createArguments = @(
|
||||
"-m", "dx_productivity", "--json", "create", $job,
|
||||
"--mapping", $mappingPath,
|
||||
"--projects", $projectsPath,
|
||||
"--certifications", $certificationPath
|
||||
)
|
||||
$createOutput = @(& $python @createArguments)
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
try {
|
||||
$created = [string]::Join([Environment]::NewLine, $createOutput) |
|
||||
ConvertFrom-Json -ErrorAction Stop
|
||||
}
|
||||
catch {
|
||||
throw "create did not return valid JSON"
|
||||
}
|
||||
Assert-ExactObject $created @("job_id", "projects", "states") "create result"
|
||||
if ($created.projects -isnot [object[]]) {
|
||||
throw "create result projects must be an array"
|
||||
}
|
||||
if ($created.projects.Count -eq 0) {
|
||||
throw "create returned no projects"
|
||||
}
|
||||
if ($created.job_id -isnot [string] -or
|
||||
[string]::IsNullOrWhiteSpace($created.job_id)) {
|
||||
throw "create result job_id is invalid"
|
||||
}
|
||||
$jobId = [string]$created.job_id
|
||||
$projectRecords = $created.projects
|
||||
$projectContext = "create"
|
||||
}
|
||||
|
||||
$entries = @()
|
||||
$seenProjectIds = New-Object 'Collections.Generic.HashSet[string]' (
|
||||
[StringComparer]::Ordinal
|
||||
)
|
||||
$seenProjectPaths = New-Object 'Collections.Generic.HashSet[string]' (
|
||||
[StringComparer]::OrdinalIgnoreCase
|
||||
)
|
||||
foreach ($project in $projectRecords) {
|
||||
Assert-ExactObject $project @(
|
||||
"display_name", "project_id", "project_path"
|
||||
) "$projectContext project"
|
||||
foreach ($name in @("display_name", "project_id", "project_path")) {
|
||||
if ($project.$name -isnot [string] -or
|
||||
[string]::IsNullOrWhiteSpace($project.$name)) {
|
||||
throw "$projectContext returned an invalid project $name"
|
||||
}
|
||||
}
|
||||
if (-not [IO.Path]::IsPathRooted([string]$project.project_path)) {
|
||||
throw "$projectContext returned a relative project path"
|
||||
}
|
||||
$projectId = [string]$project.project_id
|
||||
if (-not $seenProjectIds.Add($projectId)) {
|
||||
throw "$projectContext returned duplicate project_id: $projectId"
|
||||
}
|
||||
if ($projectId.IndexOfAny([IO.Path]::GetInvalidFileNameChars()) -ge 0 -or
|
||||
$projectId.Contains('/') -or $projectId.Contains('\')) {
|
||||
throw "create returned an invalid project_id: $projectId"
|
||||
}
|
||||
$canonicalProjectPath = Resolve-FullPath ([string]$project.project_path)
|
||||
if (-not $seenProjectPaths.Add($canonicalProjectPath)) {
|
||||
throw "$projectContext returned duplicate project path"
|
||||
}
|
||||
$mailboxDirectory = Join-Path (Join-Path $job "mailbox") $projectId
|
||||
$commandPath = Join-Path $mailboxDirectory "command.json"
|
||||
Assert-DxNoReparsePath $mailboxDirectory "mailbox directory"
|
||||
Assert-DxNoReparsePath $commandPath "mailbox command"
|
||||
$entries += [ordered]@{
|
||||
project_id = $projectId
|
||||
project_path = [string]$project.project_path
|
||||
profile = "runs/compatibility-profile.json"
|
||||
command = Convert-ToRunRelativePath $toolHome $commandPath "command"
|
||||
status = Convert-ToRunRelativePath $toolHome (
|
||||
Join-Path $mailboxDirectory "status.json"
|
||||
) "status"
|
||||
snapshot = Convert-ToRunRelativePath $toolHome (
|
||||
Join-Path $mailboxDirectory "snapshot.json"
|
||||
) "snapshot"
|
||||
}
|
||||
}
|
||||
|
||||
$manifestPath = Join-Path $deployedRun "current-part-replacement.json"
|
||||
Assert-DxNoReparsePath $toolHome "DXTOOLS_HOME"
|
||||
Assert-DxNoReparsePath $deployedRun "deployed run root"
|
||||
Assert-DxNoReparsePath $deployedProfile "deployed compatibility profile"
|
||||
Assert-DxNoReparsePath $job "job directory"
|
||||
Assert-DxNoReparsePath $manifestPath "manifest destination"
|
||||
|
||||
while ($true) {
|
||||
Assert-DxNoReparsePath $python "PythonExecutable"
|
||||
Assert-DxNoReparsePath $job "job directory"
|
||||
$stepArguments = @(
|
||||
"-m", "dx_productivity", "--json", "operator-step", $job
|
||||
)
|
||||
$stepOutput = @(& $python @stepArguments)
|
||||
$stepExitCode = $LASTEXITCODE
|
||||
if ($stepExitCode -notin @(0, 4)) {
|
||||
exit $stepExitCode
|
||||
}
|
||||
try {
|
||||
$step = [string]::Join([Environment]::NewLine, $stepOutput) |
|
||||
ConvertFrom-Json -ErrorAction Stop
|
||||
}
|
||||
catch {
|
||||
throw "operator-step did not return valid JSON"
|
||||
}
|
||||
Assert-OperatorStepResult $step $jobId
|
||||
|
||||
if ($step.complete) {
|
||||
if ($stepExitCode -ne 0) {
|
||||
throw "completed operator-step returned a nonzero status"
|
||||
}
|
||||
$manifest = [ordered]@{
|
||||
complete = $true
|
||||
current_action = $null
|
||||
current_command_id = $null
|
||||
current_project_id = $null
|
||||
format_version = 2
|
||||
projects = $entries
|
||||
}
|
||||
$manifestText = ($manifest | ConvertTo-Json -Depth 7 -Compress) + "`n"
|
||||
Write-DxUtf8Atomic $manifestPath $manifestText
|
||||
Write-Output "Part replacement job complete: $job"
|
||||
break
|
||||
}
|
||||
if ($stepExitCode -ne 4) {
|
||||
throw "pending operator-step must return status 4"
|
||||
}
|
||||
$matchingEntries = @(
|
||||
$entries | Where-Object {
|
||||
$_.project_id -ceq [string]$step.project.project_id
|
||||
}
|
||||
)
|
||||
if ($matchingEntries.Count -ne 1 -or
|
||||
-not (Test-SamePath $matchingEntries[0].project_path `
|
||||
$step.project.project_path)) {
|
||||
throw "operator-step project is not an exact created-project match"
|
||||
}
|
||||
$currentEntry = $matchingEntries[0]
|
||||
$currentCommandPath = Join-Path $toolHome (
|
||||
[string]$currentEntry.command
|
||||
)
|
||||
Assert-DxNoReparsePath $currentCommandPath "current mailbox command"
|
||||
if (-not (Test-Path -LiteralPath $currentCommandPath -PathType Leaf)) {
|
||||
throw "operator-step did not publish its current command"
|
||||
}
|
||||
$manifest = [ordered]@{
|
||||
complete = $false
|
||||
current_action = [string]$step.command.action
|
||||
current_command_id = [string]$step.command.command_id
|
||||
current_project_id = [string]$step.project.project_id
|
||||
format_version = 2
|
||||
projects = $entries
|
||||
}
|
||||
$manifestText = ($manifest | ConvertTo-Json -Depth 7 -Compress) + "`n"
|
||||
Write-DxUtf8Atomic $manifestPath $manifestText
|
||||
|
||||
Write-Output ("CurrentProject=" + [string]$step.project.project_path)
|
||||
Write-Output ("CurrentAction=" + [string]$step.command.action)
|
||||
if ($null -ne $step.manual_route) {
|
||||
Write-Output ("ManualRoute=" + [string]$step.manual_route)
|
||||
}
|
||||
if ($null -ne $step.instruction) {
|
||||
Write-Output ("Instruction=" + [string]$step.instruction)
|
||||
}
|
||||
$operatorPrompt = (
|
||||
"Run current part replacement step in DxDesigner, " +
|
||||
"then press Enter to continue or Q to quit"
|
||||
)
|
||||
Write-Output $operatorPrompt
|
||||
$response = Read-Host "Enter/Q"
|
||||
if ([string]::Equals(
|
||||
[string]$response,
|
||||
"q",
|
||||
[StringComparison]::OrdinalIgnoreCase
|
||||
)) {
|
||||
Write-Output "Part replacement job paused: $job"
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$PythonExecutable
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Remove-VerifiedBuildTarget {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$RepositoryRoot,
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$RelativeTarget
|
||||
)
|
||||
|
||||
$expected = [System.IO.Path]::GetFullPath((Join-Path $RepositoryRoot $RelativeTarget))
|
||||
$expectedRoot = [System.IO.Path]::GetFullPath($RepositoryRoot).TrimEnd('\', '/')
|
||||
if (-not $expected.StartsWith($expectedRoot + [System.IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase)) {
|
||||
throw "Refusing to remove a target outside the repository: $expected"
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $expected)) {
|
||||
return
|
||||
}
|
||||
|
||||
$resolved = (Resolve-Path -LiteralPath $expected -ErrorAction Stop).Path
|
||||
if (-not [string]::Equals($resolved, $expected, [System.StringComparison]::OrdinalIgnoreCase)) {
|
||||
throw "Refusing to remove a redirected target: $resolved"
|
||||
}
|
||||
Remove-Item -LiteralPath $resolved -Recurse -Force
|
||||
}
|
||||
|
||||
$repositoryRoot = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot "..")).Path
|
||||
$sourceRoot = (Resolve-Path -LiteralPath (Join-Path $repositoryRoot "src")).Path
|
||||
$projectPython = Join-Path $repositoryRoot ".venv\Scripts\python.exe"
|
||||
if (-not $PythonExecutable) {
|
||||
if (Test-Path -LiteralPath $projectPython -PathType Leaf) {
|
||||
$PythonExecutable = $projectPython
|
||||
}
|
||||
elseif ($env:DX_PART_REPLACE_PYTHON) {
|
||||
$PythonExecutable = $env:DX_PART_REPLACE_PYTHON
|
||||
}
|
||||
else {
|
||||
throw "Create .venv or pass -PythonExecutable with a Python 3.12 interpreter"
|
||||
}
|
||||
}
|
||||
$PythonExecutable = (Resolve-Path -LiteralPath $PythonExecutable -ErrorAction Stop).Path
|
||||
$env:PYTHONPATH = $sourceRoot
|
||||
$env:QT_QPA_PLATFORM = "offscreen"
|
||||
$smokeRoot = $null
|
||||
$distRoot = [System.IO.Path]::GetFullPath((Join-Path $repositoryRoot "dist\DxPartReplace"))
|
||||
$distData = Join-Path $distRoot "data"
|
||||
$preservedData = [System.IO.Path]::GetFullPath((Join-Path $repositoryRoot "build\DxPartReplace-preserved-data"))
|
||||
$dataWasPreserved = $false
|
||||
$locationPushed = $false
|
||||
|
||||
try {
|
||||
if (Test-Path -LiteralPath $distData) {
|
||||
$resolvedData = (Resolve-Path -LiteralPath $distData -ErrorAction Stop).Path
|
||||
if (-not [string]::Equals($resolvedData, $distData, [System.StringComparison]::OrdinalIgnoreCase)) {
|
||||
throw "Refusing to preserve redirected application data: $resolvedData"
|
||||
}
|
||||
if (Test-Path -LiteralPath $preservedData) {
|
||||
throw "Preserved application data target already exists: $preservedData"
|
||||
}
|
||||
New-Item -ItemType Directory -Path (Split-Path -Parent $preservedData) -Force | Out-Null
|
||||
Move-Item -LiteralPath $distData -Destination $preservedData -ErrorAction Stop
|
||||
$dataWasPreserved = $true
|
||||
}
|
||||
|
||||
Push-Location $repositoryRoot
|
||||
$locationPushed = $true
|
||||
& $PythonExecutable -m pytest -q tests\trial_task_center\test_application.py tests\packaging\test_dx_part_replace_build.py
|
||||
Remove-VerifiedBuildTarget -RepositoryRoot $repositoryRoot -RelativeTarget "build\DxPartReplace"
|
||||
Remove-VerifiedBuildTarget -RepositoryRoot $repositoryRoot -RelativeTarget "dist\DxPartReplace"
|
||||
& $PythonExecutable -m PyInstaller --noconfirm packaging\DxPartReplace.spec
|
||||
|
||||
$executable = [System.IO.Path]::GetFullPath((Join-Path $repositoryRoot "dist\DxPartReplace\DxPartReplace.exe"))
|
||||
if (-not (Test-Path -LiteralPath $executable -PathType Leaf)) {
|
||||
throw "PyInstaller did not produce $executable"
|
||||
}
|
||||
$sourceQuickPartReplace = Join-Path $repositoryRoot "integration\dxdesigner795\QuickPartReplace.vbs"
|
||||
$packagedQuickPartReplace = Join-Path $repositoryRoot "dist\DxPartReplace\_internal\legacy-runtime\dxdesigner795\QuickPartReplace.vbs"
|
||||
if (-not (Test-Path -LiteralPath $sourceQuickPartReplace -PathType Leaf)) {
|
||||
throw "QuickPartReplace.vbs source is missing: $sourceQuickPartReplace"
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $packagedQuickPartReplace -PathType Leaf)) {
|
||||
throw "PyInstaller did not package QuickPartReplace.vbs: $packagedQuickPartReplace"
|
||||
}
|
||||
$sourceQuickHash = (Get-FileHash -LiteralPath $sourceQuickPartReplace -Algorithm SHA256).Hash
|
||||
$packagedQuickHash = (Get-FileHash -LiteralPath $packagedQuickPartReplace -Algorithm SHA256).Hash
|
||||
if (-not [string]::Equals($sourceQuickHash, $packagedQuickHash, [System.StringComparison]::OrdinalIgnoreCase)) {
|
||||
throw "packaged QuickPartReplace.vbs SHA256 differs from the source"
|
||||
}
|
||||
$smokeRoot = Join-Path ([System.IO.Path]::GetTempPath()) ("DxPartReplace-smoke-" + [Guid]::NewGuid().ToString("N"))
|
||||
try {
|
||||
New-Item -ItemType Directory -Path $smokeRoot -ErrorAction Stop | Out-Null
|
||||
$quotedSmokeRoot = '"' + $smokeRoot + '"'
|
||||
$smokeProcess = Start-Process -FilePath $executable -ArgumentList @("--smoke-test", "--data-root", $quotedSmokeRoot) -Wait -PassThru -WindowStyle Hidden
|
||||
if ($smokeProcess.ExitCode -ne 0) {
|
||||
throw "DxPartReplace smoke test failed with exit code $($smokeProcess.ExitCode)"
|
||||
}
|
||||
$smokeLog = Join-Path $smokeRoot "logs\application.log"
|
||||
if (-not (Test-Path -LiteralPath $smokeLog -PathType Leaf)) {
|
||||
throw "DxPartReplace smoke test did not create $smokeLog"
|
||||
}
|
||||
$smokeLogText = Get-Content -LiteralPath $smokeLog -Raw -ErrorAction Stop
|
||||
if ($smokeLogText -notmatch "application_start") {
|
||||
throw "DxPartReplace smoke test did not log application_start"
|
||||
}
|
||||
if ($smokeLogText -notmatch "application_clean_shutdown") {
|
||||
throw "DxPartReplace smoke test did not log application_clean_shutdown"
|
||||
}
|
||||
}
|
||||
finally {
|
||||
if ($null -ne $smokeRoot -and (Test-Path -LiteralPath $smokeRoot)) {
|
||||
Remove-Item -LiteralPath $smokeRoot -Recurse -Force
|
||||
}
|
||||
}
|
||||
$logRoot = if ($env:DX_TASK_CENTER_HOME) { $env:DX_TASK_CENTER_HOME } else { Join-Path (Split-Path -Parent $executable) "data" }
|
||||
Write-Host "EXE: $executable"
|
||||
Write-Host "Logs: $([System.IO.Path]::GetFullPath((Join-Path $logRoot 'logs\application.log')))"
|
||||
}
|
||||
finally {
|
||||
if ($locationPushed) {
|
||||
Pop-Location
|
||||
}
|
||||
if ($dataWasPreserved) {
|
||||
New-Item -ItemType Directory -Path $distRoot -Force | Out-Null
|
||||
if (Test-Path -LiteralPath $distData) {
|
||||
throw "New build unexpectedly created an application data directory: $distData"
|
||||
}
|
||||
Move-Item -LiteralPath $preservedData -Destination $distData -ErrorAction Stop
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
# -*- mode: python ; coding: utf-8 -*-
|
||||
"""PyInstaller definition for the automatic DxDesigner replacement tool."""
|
||||
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
|
||||
import win32com.client.gencache
|
||||
|
||||
|
||||
project_root = Path(SPECPATH).parent
|
||||
generated_root = project_root / "build" / "DxPartReplace-generated"
|
||||
generated_root.mkdir(parents=True, exist_ok=True)
|
||||
viewdraw_api = win32com.client.gencache.EnsureModule(
|
||||
"{4ADEF4E1-690A-11CE-9261-0020C5E26659}", 0, 1, 0
|
||||
)
|
||||
if viewdraw_api is None:
|
||||
raise RuntimeError("DxDesigner EE 7.9.5 type library is required for packaging")
|
||||
shutil.copyfile(viewdraw_api.__file__, generated_root / "viewdraw_api.py")
|
||||
legacy_runtime_datas = [
|
||||
(
|
||||
str(project_root / "integration" / "dxdesigner795" / "QuickPartReplace.vbs"),
|
||||
"legacy-runtime/dxdesigner795",
|
||||
),
|
||||
]
|
||||
|
||||
a = Analysis(
|
||||
[str(project_root / "src" / "dx_productivity" / "trial_task_center" / "application.py")],
|
||||
pathex=[str(project_root / "src"), str(generated_root)],
|
||||
binaries=[],
|
||||
datas=legacy_runtime_datas,
|
||||
hiddenimports=[
|
||||
"viewdraw_api",
|
||||
"win32com.client",
|
||||
"win32com.client.dynamic",
|
||||
"win32con",
|
||||
"win32gui",
|
||||
"win32process",
|
||||
"pywinauto",
|
||||
"pywinauto.controls.uiawrapper",
|
||||
],
|
||||
excludes=[
|
||||
"PySide6.QtDesigner",
|
||||
"PySide6.QtMultimedia",
|
||||
"PySide6.QtMultimediaWidgets",
|
||||
"PySide6.QtOpenGL",
|
||||
"PySide6.QtOpenGLWidgets",
|
||||
"PySide6.QtPdf",
|
||||
"PySide6.QtPdfWidgets",
|
||||
"PySide6.QtQml",
|
||||
"PySide6.QtQuick",
|
||||
"PySide6.QtQuickWidgets",
|
||||
"PySide6.QtWebChannel",
|
||||
"PySide6.QtWebEngineCore",
|
||||
"PySide6.QtWebEngineWidgets",
|
||||
],
|
||||
noarchive=False,
|
||||
)
|
||||
excluded_qt_binaries = {
|
||||
"icudt78.dll",
|
||||
"icuuc.dll",
|
||||
"qpdf.dll",
|
||||
"qt6pdf.dll",
|
||||
"qt6qml.dll",
|
||||
"qt6qmlmeta.dll",
|
||||
"qt6qmlmodels.dll",
|
||||
"qt6qmlworkerscript.dll",
|
||||
"qt6quick.dll",
|
||||
}
|
||||
a.binaries = [
|
||||
entry
|
||||
for entry in a.binaries
|
||||
if Path(entry[0]).name.casefold() not in excluded_qt_binaries
|
||||
]
|
||||
pyz = PYZ(a.pure)
|
||||
exe = EXE(
|
||||
pyz,
|
||||
a.scripts,
|
||||
[],
|
||||
exclude_binaries=True,
|
||||
name='DxPartReplace',
|
||||
debug=False,
|
||||
bootloader_ignore_signals=False,
|
||||
strip=False,
|
||||
upx=True,
|
||||
console=False,
|
||||
)
|
||||
coll = COLLECT(
|
||||
exe,
|
||||
a.binaries,
|
||||
a.zipfiles,
|
||||
a.datas,
|
||||
strip=False,
|
||||
upx=True,
|
||||
upx_exclude=[],
|
||||
name="DxPartReplace",
|
||||
)
|
||||
@@ -0,0 +1,24 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=75"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "dx-productivity"
|
||||
version = "1.0.0"
|
||||
requires-python = ">=3.12,<3.13"
|
||||
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<1"]
|
||||
|
||||
[project.scripts]
|
||||
dx-part-replace = "dx_productivity.part_replace.cli:main"
|
||||
dx-part-replace-gui = "dx_productivity.trial_task_center.application:main"
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = ["pytest>=8,<9", "pytest-cov>=5,<7", "coverage>=7,<8", "build>=1.2,<2", "pytest-qt>=4.4,<5", "PyInstaller>=6.10,<7"]
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["src"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
addopts = "-ra"
|
||||
cache_dir = "build/pytest-cache"
|
||||
@@ -0,0 +1,14 @@
|
||||
Metadata-Version: 2.4
|
||||
Name: dx-productivity
|
||||
Version: 1.0.0
|
||||
Requires-Python: <3.13,>=3.12
|
||||
Requires-Dist: PySide6<7,>=6.7
|
||||
Requires-Dist: pywin32>=306
|
||||
Requires-Dist: pywinauto<1,>=0.6.9
|
||||
Provides-Extra: dev
|
||||
Requires-Dist: pytest<9,>=8; extra == "dev"
|
||||
Requires-Dist: pytest-cov<7,>=5; extra == "dev"
|
||||
Requires-Dist: coverage<8,>=7; extra == "dev"
|
||||
Requires-Dist: build<2,>=1.2; extra == "dev"
|
||||
Requires-Dist: pytest-qt<5,>=4.4; extra == "dev"
|
||||
Requires-Dist: PyInstaller<7,>=6.10; extra == "dev"
|
||||
@@ -0,0 +1,45 @@
|
||||
pyproject.toml
|
||||
src/dx_productivity/__init__.py
|
||||
src/dx_productivity/__main__.py
|
||||
src/dx_productivity.egg-info/PKG-INFO
|
||||
src/dx_productivity.egg-info/SOURCES.txt
|
||||
src/dx_productivity.egg-info/dependency_links.txt
|
||||
src/dx_productivity.egg-info/entry_points.txt
|
||||
src/dx_productivity.egg-info/requires.txt
|
||||
src/dx_productivity.egg-info/top_level.txt
|
||||
src/dx_productivity/part_replace/__init__.py
|
||||
src/dx_productivity/part_replace/certification.py
|
||||
src/dx_productivity/part_replace/cli.py
|
||||
src/dx_productivity/part_replace/command_schema.py
|
||||
src/dx_productivity/part_replace/compatibility_profile.py
|
||||
src/dx_productivity/part_replace/controller.py
|
||||
src/dx_productivity/part_replace/errors.py
|
||||
src/dx_productivity/part_replace/inputs.py
|
||||
src/dx_productivity/part_replace/mailbox.py
|
||||
src/dx_productivity/part_replace/models.py
|
||||
src/dx_productivity/part_replace/operator_runtime.py
|
||||
src/dx_productivity/part_replace/protocol.py
|
||||
src/dx_productivity/part_replace/reports.py
|
||||
src/dx_productivity/part_replace/run_store.py
|
||||
src/dx_productivity/part_replace/verification.py
|
||||
src/dx_productivity/trial_task_center/__init__.py
|
||||
src/dx_productivity/trial_task_center/application.py
|
||||
src/dx_productivity/trial_task_center/comparison.py
|
||||
src/dx_productivity/trial_task_center/errors.py
|
||||
src/dx_productivity/trial_task_center/evidence.py
|
||||
src/dx_productivity/trial_task_center/logging_setup.py
|
||||
src/dx_productivity/trial_task_center/models.py
|
||||
src/dx_productivity/trial_task_center/native_helper.py
|
||||
src/dx_productivity/trial_task_center/quick_run.py
|
||||
src/dx_productivity/trial_task_center/runner.py
|
||||
src/dx_productivity/trial_task_center/scanner.py
|
||||
src/dx_productivity/trial_task_center/service.py
|
||||
src/dx_productivity/trial_task_center/store.py
|
||||
src/dx_productivity/trial_task_center/ui/__init__.py
|
||||
src/dx_productivity/trial_task_center/ui/main_window.py
|
||||
src/dx_productivity/trial_task_center/ui/mapping_table.py
|
||||
src/dx_productivity/trial_task_center/ui/project_table.py
|
||||
src/dx_productivity/trial_task_center/ui/run_panel.py
|
||||
src/dx_productivity/trial_task_center/ui/styles.py
|
||||
src/dx_productivity/trial_task_center/ui/task_list.py
|
||||
src/dx_productivity/trial_task_center/ui/workers.py
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
[console_scripts]
|
||||
dx-part-replace = dx_productivity.part_replace.cli:main
|
||||
dx-part-replace-gui = dx_productivity.trial_task_center.application:main
|
||||
@@ -0,0 +1,11 @@
|
||||
PySide6<7,>=6.7
|
||||
pywin32>=306
|
||||
pywinauto<1,>=0.6.9
|
||||
|
||||
[dev]
|
||||
pytest<9,>=8
|
||||
pytest-cov<7,>=5
|
||||
coverage<8,>=7
|
||||
build<2,>=1.2
|
||||
pytest-qt<5,>=4.4
|
||||
PyInstaller<7,>=6.10
|
||||
@@ -0,0 +1 @@
|
||||
dx_productivity
|
||||
@@ -0,0 +1 @@
|
||||
"""Dx Productivity Python package."""
|
||||
@@ -0,0 +1,6 @@
|
||||
"""Package entry point for the part-replacement CLI."""
|
||||
|
||||
from .part_replace.cli import main
|
||||
|
||||
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Immutable domain records for part replacement."""
|
||||
|
||||
from .models import (
|
||||
ComponentSnapshot,
|
||||
DesignSnapshot,
|
||||
ExternalChecks,
|
||||
ImpactCell,
|
||||
Issue,
|
||||
MappingRule,
|
||||
PinSnapshot,
|
||||
ProjectRef,
|
||||
ProjectState,
|
||||
Scope,
|
||||
UnitSnapshot,
|
||||
VerificationResult,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"ComponentSnapshot", "DesignSnapshot", "ExternalChecks", "ImpactCell", "Issue",
|
||||
"MappingRule", "PinSnapshot", "ProjectRef", "ProjectState", "Scope", "UnitSnapshot",
|
||||
"VerificationResult",
|
||||
]
|
||||
@@ -0,0 +1,343 @@
|
||||
"""Immutable, fail-closed trial compatibility certifications."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from decimal import Decimal, InvalidOperation
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from .models import ComponentSnapshot, DesignSnapshot, ExternalChecks, MappingRule, PinSnapshot, UnitSnapshot, VerificationResult
|
||||
from .protocol import ProtocolError, atomic_write_text, snapshot_fingerprint
|
||||
from .verification import verify_replacement
|
||||
|
||||
|
||||
_FORMAT_VERSION = 1
|
||||
_DXDESIGNER_BUILD = "7.9.5"
|
||||
|
||||
|
||||
class CertificationError(ValueError):
|
||||
"""A trial certification is incomplete, corrupt, or not applicable."""
|
||||
|
||||
def __init__(self, code: str, message: str) -> None:
|
||||
self.code = code
|
||||
self.message = message
|
||||
super().__init__(f"{code}: {message}")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Certification:
|
||||
created_utc: str
|
||||
dxdesigner_build: str
|
||||
rule: MappingRule
|
||||
target_fingerprint: str
|
||||
library_identity: str | None
|
||||
representative_project_fingerprint: str
|
||||
evidence_paths: tuple[str, ...]
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "evidence_paths", tuple(self.evidence_paths))
|
||||
|
||||
|
||||
def _canonical_json(value: object) -> str:
|
||||
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)
|
||||
|
||||
|
||||
def _normalized_identity(value: str) -> str:
|
||||
return value.strip().casefold()
|
||||
|
||||
|
||||
def _decimal_text(value: object) -> str:
|
||||
try:
|
||||
decimal = value if isinstance(value, Decimal) else Decimal(str(value))
|
||||
except (InvalidOperation, ValueError) as error:
|
||||
raise CertificationError("invalid_interface", "interface coordinates must be finite Decimals") from error
|
||||
if not decimal.is_finite():
|
||||
raise CertificationError("invalid_interface", "interface coordinates must be finite Decimals")
|
||||
if decimal == 0:
|
||||
return "0"
|
||||
return format(decimal.normalize(), "f")
|
||||
|
||||
|
||||
def _local_coordinates(
|
||||
unit: UnitSnapshot,
|
||||
x: Decimal,
|
||||
y: Decimal,
|
||||
) -> tuple[str, str]:
|
||||
delta_x = x - unit.x
|
||||
delta_y = y - unit.y
|
||||
rotation = unit.rotation % 360
|
||||
if rotation == 0:
|
||||
transformed_x, transformed_y = delta_x, delta_y
|
||||
elif rotation == 90:
|
||||
transformed_x, transformed_y = delta_y, -delta_x
|
||||
elif rotation == 180:
|
||||
transformed_x, transformed_y = -delta_x, -delta_y
|
||||
elif rotation == 270:
|
||||
transformed_x, transformed_y = -delta_y, delta_x
|
||||
else:
|
||||
raise CertificationError("invalid_interface", "interface rotation must be a quarter turn")
|
||||
local_x = -transformed_x if unit.mirrored else transformed_x
|
||||
return _decimal_text(local_x), _decimal_text(transformed_y)
|
||||
|
||||
|
||||
def _local_pin_coordinates(unit: UnitSnapshot, pin: PinSnapshot) -> tuple[str, str]:
|
||||
return _local_coordinates(unit, pin.x, pin.y)
|
||||
|
||||
|
||||
def _occurrence_interface(component: ComponentSnapshot) -> dict[str, object]:
|
||||
if not component.units:
|
||||
raise CertificationError("invalid_interface", "selected component has no observed units")
|
||||
units: list[dict[str, object]] = []
|
||||
gate_ids: set[str] = set()
|
||||
for unit in component.units:
|
||||
gate_id = _normalized_identity(unit.unit_id)
|
||||
if not gate_id or gate_id in gate_ids:
|
||||
raise CertificationError("invalid_interface", "unit identities must be nonempty and unique after normalization")
|
||||
gate_ids.add(gate_id)
|
||||
if not isinstance(unit.symbol, str) or not unit.symbol:
|
||||
raise CertificationError("invalid_interface", "symbol identity must be nonempty")
|
||||
if not unit.pins:
|
||||
raise CertificationError("invalid_interface", "selected units must have observed pins")
|
||||
pins: list[list[str]] = []
|
||||
for pin in unit.pins:
|
||||
if not pin.number or not pin.name:
|
||||
raise CertificationError("invalid_interface", "pin number and name must be nonempty")
|
||||
local_x, local_y = _local_pin_coordinates(unit, pin)
|
||||
pins.append([pin.number, pin.name, local_x, local_y])
|
||||
pins.sort(key=lambda pin: (pin[0], pin[1], pin[2], pin[3]))
|
||||
units.append(
|
||||
{
|
||||
"gate_id": gate_id,
|
||||
"pins": pins,
|
||||
"symbol": unit.symbol,
|
||||
"symbol_origin": list(
|
||||
_local_coordinates(unit, unit.origin_x, unit.origin_y)
|
||||
),
|
||||
}
|
||||
)
|
||||
units.sort(key=_canonical_json)
|
||||
return {"logical_unit_count": len(units), "units": units}
|
||||
|
||||
|
||||
def interface_fingerprint(snapshot: DesignSnapshot, logical_keys: Sequence[str]) -> str:
|
||||
"""Hash only the library-visible interface of the selected logical components."""
|
||||
if not isinstance(snapshot, DesignSnapshot):
|
||||
raise CertificationError("invalid_snapshot", "interface fingerprint requires a DesignSnapshot")
|
||||
keys = tuple(logical_keys)
|
||||
if not keys or any(not isinstance(key, str) or not key for key in keys) or len(keys) != len(set(keys)):
|
||||
raise CertificationError("invalid_logical_keys", "logical keys must be nonempty unique strings")
|
||||
components = {component.logical_key: component for component in snapshot.components}
|
||||
if len(components) != len(snapshot.components) or any(key not in components for key in keys):
|
||||
raise CertificationError("invalid_logical_keys", "logical keys must identify unambiguous snapshot components")
|
||||
|
||||
observed_interfaces = tuple(_occurrence_interface(components[key]) for key in keys)
|
||||
canonical_interfaces = tuple(_canonical_json(interface) for interface in observed_interfaces)
|
||||
if len(set(canonical_interfaces)) != 1:
|
||||
raise CertificationError(
|
||||
"heterogeneous_interface",
|
||||
"selected target occurrences do not expose one identical normalized part interface",
|
||||
)
|
||||
return hashlib.sha256(canonical_interfaces[0].encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _duplicate_rejecting_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
||||
data: dict[str, Any] = {}
|
||||
for name, value in pairs:
|
||||
if name in data:
|
||||
raise CertificationError("corrupt_certification", f"duplicate JSON field {name!r}")
|
||||
data[name] = value
|
||||
return data
|
||||
|
||||
|
||||
def _load_data(path: Path) -> dict[str, Any]:
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8")
|
||||
except FileNotFoundError:
|
||||
return {"format_version": _FORMAT_VERSION, "certifications": []}
|
||||
except (OSError, UnicodeError) as error:
|
||||
raise CertificationError("corrupt_certification", f"cannot read certifications: {path}") from error
|
||||
try:
|
||||
data = json.loads(text, object_pairs_hook=_duplicate_rejecting_object)
|
||||
except (json.JSONDecodeError, CertificationError) as error:
|
||||
raise CertificationError("corrupt_certification", f"invalid certifications JSON: {path}") from error
|
||||
if not isinstance(data, dict) or set(data) != {"format_version", "certifications"}:
|
||||
raise CertificationError("corrupt_certification", "certification document fields are invalid")
|
||||
if type(data["format_version"]) is not int or data["format_version"] != _FORMAT_VERSION:
|
||||
raise CertificationError("corrupt_certification", "certification document version is invalid")
|
||||
if not isinstance(data["certifications"], list):
|
||||
raise CertificationError("corrupt_certification", "certifications must be an array")
|
||||
return data
|
||||
|
||||
|
||||
def _valid_timestamp(value: object) -> bool:
|
||||
if not isinstance(value, str) or not value.endswith("Z"):
|
||||
return False
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value[:-1] + "+00:00")
|
||||
except ValueError:
|
||||
return False
|
||||
return parsed.tzinfo is not None and parsed.utcoffset() == timezone.utc.utcoffset(parsed)
|
||||
|
||||
|
||||
def _certification_from_data(data: object) -> Certification:
|
||||
if not isinstance(data, dict):
|
||||
raise CertificationError("corrupt_certification", "certification record must be an object")
|
||||
required = {
|
||||
"created_utc", "dxdesigner_build", "evidence_paths", "library_identity",
|
||||
"new_part_number", "old_part_number", "representative_project_fingerprint", "target_fingerprint",
|
||||
}
|
||||
if set(data) != required:
|
||||
raise CertificationError("corrupt_certification", "certification record fields are invalid")
|
||||
strings = (
|
||||
"created_utc", "dxdesigner_build", "new_part_number", "old_part_number",
|
||||
"representative_project_fingerprint", "target_fingerprint",
|
||||
)
|
||||
if any(not isinstance(data[name], str) or not data[name] for name in strings):
|
||||
raise CertificationError("corrupt_certification", "certification record string fields are invalid")
|
||||
if not _valid_timestamp(data["created_utc"]) or data["dxdesigner_build"] != _DXDESIGNER_BUILD:
|
||||
raise CertificationError("corrupt_certification", "certification timestamp or build is invalid")
|
||||
library_identity = data["library_identity"]
|
||||
if library_identity is not None and (not isinstance(library_identity, str) or not library_identity):
|
||||
raise CertificationError("corrupt_certification", "library identity is invalid")
|
||||
evidence_paths = data["evidence_paths"]
|
||||
if not isinstance(evidence_paths, list) or not evidence_paths or any(
|
||||
not isinstance(path, str) or not path for path in evidence_paths
|
||||
):
|
||||
raise CertificationError("corrupt_certification", "evidence paths are invalid")
|
||||
return Certification(
|
||||
created_utc=data["created_utc"],
|
||||
dxdesigner_build=data["dxdesigner_build"],
|
||||
rule=MappingRule(data["old_part_number"], data["new_part_number"]),
|
||||
target_fingerprint=data["target_fingerprint"],
|
||||
library_identity=library_identity,
|
||||
representative_project_fingerprint=data["representative_project_fingerprint"],
|
||||
evidence_paths=tuple(evidence_paths),
|
||||
)
|
||||
|
||||
|
||||
def _certification_to_data(certification: Certification) -> dict[str, object]:
|
||||
return {
|
||||
"created_utc": certification.created_utc,
|
||||
"dxdesigner_build": certification.dxdesigner_build,
|
||||
"evidence_paths": list(certification.evidence_paths),
|
||||
"library_identity": certification.library_identity,
|
||||
"new_part_number": certification.rule.new_part_number,
|
||||
"old_part_number": certification.rule.old_part_number,
|
||||
"representative_project_fingerprint": certification.representative_project_fingerprint,
|
||||
"target_fingerprint": certification.target_fingerprint,
|
||||
}
|
||||
|
||||
|
||||
class CertificationStore:
|
||||
"""Persist and require records created by one verified representative trial."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
path: Path,
|
||||
*,
|
||||
before: DesignSnapshot | None = None,
|
||||
after: DesignSnapshot | None = None,
|
||||
verification: VerificationResult | None = None,
|
||||
evidence_paths: Sequence[str] = (),
|
||||
) -> None:
|
||||
self.path = Path(path)
|
||||
self._before = before
|
||||
self._after = after
|
||||
self._verification = verification
|
||||
self._evidence_paths = tuple(evidence_paths)
|
||||
|
||||
@staticmethod
|
||||
def _require_complete_trial_observation(
|
||||
before: DesignSnapshot,
|
||||
after: DesignSnapshot,
|
||||
logical_keys: Sequence[str],
|
||||
) -> None:
|
||||
for snapshot in (before, after):
|
||||
components = {component.logical_key: component for component in snapshot.components}
|
||||
for logical_key in logical_keys:
|
||||
component = components.get(logical_key)
|
||||
if component is None or not component.units:
|
||||
raise CertificationError("trial_data_incomplete", "expected component has no observed units")
|
||||
for unit in component.units:
|
||||
if not unit.pins:
|
||||
raise CertificationError("trial_data_incomplete", "expected unit has no observed pins")
|
||||
if any(not isinstance(pin.net, str) or not pin.net.strip() for pin in unit.pins):
|
||||
raise CertificationError("trial_data_incomplete", "expected pin has no network identity")
|
||||
|
||||
def _require_trial_context(self, rule: MappingRule, target_fingerprint: str) -> tuple[DesignSnapshot, DesignSnapshot, VerificationResult]:
|
||||
before, after, verification = self._before, self._after, self._verification
|
||||
if not isinstance(before, DesignSnapshot) or not isinstance(after, DesignSnapshot) or not isinstance(verification, VerificationResult):
|
||||
raise CertificationError("trial_context_missing", "recording requires trial snapshots and hard verification")
|
||||
self._require_complete_trial_observation(before, after, verification.expected_logical_keys)
|
||||
recomputed = verify_replacement(before, after, rule, verification.expected_logical_keys)
|
||||
if verification.passed is not True or verification.rule != rule or recomputed != verification or recomputed.passed is not True:
|
||||
raise CertificationError("hard_verification_failed", "representative trial did not pass hard verification")
|
||||
if before.project_id != after.project_id or verification.project_id != before.project_id:
|
||||
raise CertificationError("hard_verification_failed", "trial verification does not match the representative project")
|
||||
expected = interface_fingerprint(after, verification.expected_logical_keys)
|
||||
if target_fingerprint != expected:
|
||||
raise CertificationError("target_fingerprint_mismatch", "target fingerprint does not match the verified observed interface")
|
||||
return before, after, verification
|
||||
|
||||
def record(
|
||||
self,
|
||||
rule: MappingRule,
|
||||
target_fingerprint: str,
|
||||
library_identity: str | None,
|
||||
checks: ExternalChecks,
|
||||
) -> Certification:
|
||||
if not isinstance(rule, MappingRule) or not rule.old_part_number or not rule.new_part_number:
|
||||
raise CertificationError("invalid_mapping_rule", "certification requires a nonempty MappingRule")
|
||||
if not isinstance(target_fingerprint, str) or not target_fingerprint:
|
||||
raise CertificationError("invalid_target_fingerprint", "target fingerprint must be a nonempty string")
|
||||
if library_identity is not None and (not isinstance(library_identity, str) or not library_identity):
|
||||
raise CertificationError("invalid_library_identity", "library identity must be a nonempty string or None")
|
||||
if not isinstance(checks, ExternalChecks) or not (
|
||||
checks.packager is True and checks.erc is True and checks.netlist is True
|
||||
):
|
||||
raise CertificationError("external_checks_incomplete", "Packager, ERC, and netlist must each explicitly pass")
|
||||
before, _, _ = self._require_trial_context(rule, target_fingerprint)
|
||||
if not self._evidence_paths or any(not isinstance(path, str) or not path for path in self._evidence_paths):
|
||||
raise CertificationError("invalid_evidence_paths", "evidence paths must be nonempty strings")
|
||||
certification = Certification(
|
||||
created_utc=datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z"),
|
||||
dxdesigner_build=_DXDESIGNER_BUILD,
|
||||
rule=rule,
|
||||
target_fingerprint=target_fingerprint,
|
||||
library_identity=library_identity,
|
||||
representative_project_fingerprint=snapshot_fingerprint(before),
|
||||
evidence_paths=self._evidence_paths,
|
||||
)
|
||||
data = _load_data(self.path)
|
||||
records = [_certification_from_data(record) for record in data["certifications"]]
|
||||
records = [
|
||||
record for record in records
|
||||
if (record.rule, record.target_fingerprint, record.library_identity) != (
|
||||
rule, target_fingerprint, library_identity
|
||||
)
|
||||
]
|
||||
records.append(certification)
|
||||
document = {"format_version": _FORMAT_VERSION, "certifications": [_certification_to_data(record) for record in records]}
|
||||
try:
|
||||
atomic_write_text(self.path, _canonical_json(document) + "\n")
|
||||
except (OSError, ProtocolError) as error:
|
||||
raise CertificationError("certification_write_failed", f"cannot persist certification: {self.path}") from error
|
||||
return certification
|
||||
|
||||
def require(self, rule: MappingRule, target_fingerprint: str, library_identity: str | None) -> Certification:
|
||||
if not isinstance(rule, MappingRule) or not isinstance(target_fingerprint, str):
|
||||
raise CertificationError("certification_mismatch", "no matching certification exists")
|
||||
records = [_certification_from_data(record) for record in _load_data(self.path)["certifications"]]
|
||||
for certification in records:
|
||||
if (
|
||||
certification.rule == rule
|
||||
and certification.target_fingerprint == target_fingerprint
|
||||
and certification.library_identity == library_identity
|
||||
):
|
||||
return certification
|
||||
raise CertificationError("certification_mismatch", "no matching certification exists")
|
||||
@@ -0,0 +1,340 @@
|
||||
"""Reproducible command-line interface for part-replacement jobs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from typing import Sequence
|
||||
|
||||
from .certification import CertificationError
|
||||
from .command_schema import command_data as _command_data
|
||||
from .compatibility_profile import (
|
||||
CompatibilityProfileError,
|
||||
deploy_compatibility_profile,
|
||||
promote_compatibility_profile,
|
||||
)
|
||||
from .controller import BatchController, ControllerError
|
||||
from .inputs import InputError, discover_projects
|
||||
from .models import ProjectRef, ProjectState, VerificationResult
|
||||
from .operator_runtime import OperatorStepResult
|
||||
from .protocol import ProtocolError, atomic_write_text
|
||||
from .run_store import BackupError, StateError
|
||||
|
||||
|
||||
class _UsageError(ValueError):
|
||||
code = "invalid_arguments"
|
||||
|
||||
|
||||
class _Parser(argparse.ArgumentParser):
|
||||
def error(self, message: str) -> None:
|
||||
raise _UsageError(message)
|
||||
|
||||
|
||||
def _parser() -> argparse.ArgumentParser:
|
||||
parser = _Parser(prog="dx-part-replace", description="DxDesigner 7.9.5 multi-project native part replacement")
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
discover = commands.add_parser("discover", help="discover candidate project-definition files")
|
||||
discover.add_argument("root", type=Path)
|
||||
discover.add_argument("--suffix", action="append", dest="suffixes")
|
||||
discover.add_argument("--output", type=Path)
|
||||
|
||||
create = commands.add_parser("create", help="create a validated immutable job")
|
||||
create.add_argument("job", type=Path)
|
||||
create.add_argument("--mapping", required=True, type=Path)
|
||||
create.add_argument("--projects", required=True, type=Path)
|
||||
create.add_argument("--certifications", required=True, type=Path)
|
||||
create.add_argument("--suffix", action="append", dest="suffixes")
|
||||
create.add_argument("--library-identity")
|
||||
|
||||
deploy_profile = commands.add_parser(
|
||||
"deploy-profile",
|
||||
help="validate and atomically deploy a compatibility profile",
|
||||
)
|
||||
deploy_profile.add_argument("source", type=Path)
|
||||
deploy_profile.add_argument("destination", type=Path)
|
||||
|
||||
promote_profile = commands.add_parser(
|
||||
"promote-profile",
|
||||
help="bind completed live evidence and deploy an accepted profile",
|
||||
)
|
||||
promote_profile.add_argument("source", type=Path)
|
||||
promote_profile.add_argument("acceptance", type=Path)
|
||||
promote_profile.add_argument("destination", type=Path)
|
||||
|
||||
ingest = commands.add_parser("ingest")
|
||||
ingest.add_argument("job", type=Path)
|
||||
ingest.add_argument("project_id")
|
||||
|
||||
next_command = commands.add_parser("next")
|
||||
next_command.add_argument("job", type=Path)
|
||||
|
||||
operator_step = commands.add_parser("operator-step")
|
||||
operator_step.add_argument("job", type=Path)
|
||||
|
||||
inventory_command = commands.add_parser("prepare-inventory")
|
||||
inventory_command.add_argument("job", type=Path)
|
||||
inventory_command.add_argument("project_id")
|
||||
|
||||
for name in (
|
||||
"prepare-close",
|
||||
"confirm-close",
|
||||
"prepare-open",
|
||||
"confirm-open",
|
||||
"prepare-undo",
|
||||
"confirm-undo",
|
||||
"prepare-save",
|
||||
"confirm-saved",
|
||||
"restore",
|
||||
"reconcile",
|
||||
):
|
||||
control = commands.add_parser(name)
|
||||
control.add_argument("job", type=Path)
|
||||
control.add_argument("project_id")
|
||||
|
||||
for name in ("prepare-check", "confirm-check"):
|
||||
check = commands.add_parser(name)
|
||||
check.add_argument("job", type=Path)
|
||||
check.add_argument("project_id")
|
||||
check.add_argument("check", choices=("packager", "erc", "netlist"))
|
||||
|
||||
prepare = commands.add_parser("prepare")
|
||||
prepare.add_argument("job", type=Path)
|
||||
prepare.add_argument("project_id")
|
||||
prepare.add_argument("rule_index", type=int)
|
||||
|
||||
verify = commands.add_parser("verify")
|
||||
verify.add_argument("job", type=Path)
|
||||
verify.add_argument("project_id")
|
||||
verify.add_argument("rule_index", type=int)
|
||||
|
||||
report = commands.add_parser("report")
|
||||
report.add_argument("job", type=Path)
|
||||
status = commands.add_parser("status")
|
||||
status.add_argument("job", type=Path)
|
||||
return parser
|
||||
|
||||
|
||||
def _suffixes(value: list[str] | None) -> tuple[str, ...]:
|
||||
return tuple(value) if value else (".prj",)
|
||||
|
||||
|
||||
def _project_data(project: ProjectRef) -> dict[str, str]:
|
||||
return {
|
||||
"display_name": project.display_name,
|
||||
"project_id": project.project_id,
|
||||
"project_path": project.project_path,
|
||||
}
|
||||
|
||||
|
||||
def _result_data(result: VerificationResult) -> dict[str, object]:
|
||||
return {
|
||||
"changed_logical_keys": list(result.changed_logical_keys),
|
||||
"expected_logical_keys": list(result.expected_logical_keys),
|
||||
"issues": [
|
||||
{
|
||||
"code": issue.code,
|
||||
"details": dict(issue.details),
|
||||
"message": issue.message,
|
||||
"severity": issue.severity,
|
||||
}
|
||||
for issue in result.issues
|
||||
],
|
||||
"new_part_number": result.rule.new_part_number,
|
||||
"old_part_number": result.rule.old_part_number,
|
||||
"passed": result.passed,
|
||||
"project_id": result.project_id,
|
||||
}
|
||||
|
||||
|
||||
def _operator_step_data(result: OperatorStepResult) -> dict[str, object]:
|
||||
command = result.command
|
||||
project = result.project
|
||||
state = result.state
|
||||
return {
|
||||
"bridge_state": result.bridge_state,
|
||||
"command": None if command is None else _command_data(command),
|
||||
"complete": result.complete,
|
||||
"consumed_action": result.consumed_action,
|
||||
"instruction": result.instruction,
|
||||
"manual_route": result.manual_route,
|
||||
"project": None if project is None else _project_data(project),
|
||||
"state": None if state is None else state.value,
|
||||
}
|
||||
|
||||
|
||||
def _run(args: argparse.Namespace) -> tuple[int, dict[str, object]]:
|
||||
if args.command == "discover":
|
||||
projects = discover_projects(args.root, _suffixes(args.suffixes))
|
||||
if args.output is not None:
|
||||
atomic_write_text(args.output, "".join(f"{project}\n" for project in projects))
|
||||
return 0, {"projects": [str(project) for project in projects]}
|
||||
if args.command == "create":
|
||||
controller = BatchController.create_job(
|
||||
args.job,
|
||||
args.mapping,
|
||||
args.projects,
|
||||
certification_path=args.certifications,
|
||||
allowed_suffixes=_suffixes(args.suffixes),
|
||||
library_identity=args.library_identity,
|
||||
)
|
||||
return 0, {
|
||||
"job_id": controller.job_id,
|
||||
"projects": [_project_data(project) for project in controller.projects],
|
||||
"states": {project.project_id: controller.project_state(project.project_id).value for project in controller.projects},
|
||||
}
|
||||
if args.command == "deploy-profile":
|
||||
deployed = deploy_compatibility_profile(args.source, args.destination)
|
||||
return 0, {"compatibility_profile": str(deployed.resolve())}
|
||||
if args.command == "promote-profile":
|
||||
promoted = promote_compatibility_profile(
|
||||
args.source,
|
||||
args.acceptance,
|
||||
args.destination,
|
||||
)
|
||||
return 0, {"compatibility_profile": str(promoted.resolve())}
|
||||
|
||||
controller = BatchController.open(args.job)
|
||||
if args.command == "ingest":
|
||||
controller.ingest_inventory(args.project_id)
|
||||
state = controller.project_state(args.project_id)
|
||||
if state is ProjectState.BLOCKED:
|
||||
return 3, {
|
||||
"error": {
|
||||
"code": "impact_blocked",
|
||||
"message": "inventory impact contains blocking issues",
|
||||
},
|
||||
"project_id": args.project_id,
|
||||
"state": state.value,
|
||||
}
|
||||
return 0, {"project_id": args.project_id, "state": state.value}
|
||||
if args.command == "next":
|
||||
project = controller.next_project()
|
||||
if project is None:
|
||||
return 0, {"complete": True, "project": None}
|
||||
return 4, {"action": controller.action_for(project.project_id), "complete": False, "project": _project_data(project)}
|
||||
if args.command == "operator-step":
|
||||
result = controller.operator_step()
|
||||
return (0 if result.complete else 4), _operator_step_data(result)
|
||||
if args.command == "prepare-inventory":
|
||||
return 0, _command_data(controller.prepare_inventory(args.project_id))
|
||||
if args.command == "prepare-close":
|
||||
return 4, _command_data(controller.prepare_close(args.project_id))
|
||||
if args.command == "confirm-close":
|
||||
controller.confirm_close(args.project_id)
|
||||
return 0, {
|
||||
"project_id": args.project_id,
|
||||
"state": controller.project_state(args.project_id).value,
|
||||
}
|
||||
if args.command == "prepare-open":
|
||||
return 4, _command_data(controller.prepare_open(args.project_id))
|
||||
if args.command == "confirm-open":
|
||||
controller.confirm_open(args.project_id)
|
||||
return 0, {
|
||||
"project_id": args.project_id,
|
||||
"state": controller.project_state(args.project_id).value,
|
||||
}
|
||||
if args.command == "prepare":
|
||||
command = controller.prepare_apply(args.project_id, args.rule_index)
|
||||
return 4, _command_data(command)
|
||||
if args.command == "verify":
|
||||
result = controller.verify_apply(args.project_id, args.rule_index)
|
||||
return (0 if result.passed else 3), _result_data(result)
|
||||
if args.command == "prepare-undo":
|
||||
return 4, _command_data(controller.prepare_undo(args.project_id))
|
||||
if args.command == "confirm-undo":
|
||||
controller.confirm_undo(args.project_id)
|
||||
return 0, {
|
||||
"project_id": args.project_id,
|
||||
"state": controller.project_state(args.project_id).value,
|
||||
}
|
||||
if args.command == "prepare-save":
|
||||
return 4, _command_data(controller.prepare_save(args.project_id))
|
||||
if args.command == "confirm-saved":
|
||||
state = controller.confirm_saved(args.project_id)
|
||||
return (0 if state is ProjectState.VERIFIED_SAVED else 4), {"project_id": args.project_id, "state": state.value}
|
||||
if args.command == "prepare-check":
|
||||
return 4, _command_data(
|
||||
controller.prepare_external_check(args.project_id, args.check)
|
||||
)
|
||||
if args.command == "confirm-check":
|
||||
state = controller.confirm_external_check(args.project_id, args.check)
|
||||
return (0 if state is ProjectState.VERIFIED_SAVED else 4), {
|
||||
"project_id": args.project_id,
|
||||
"state": state.value,
|
||||
}
|
||||
if args.command == "restore":
|
||||
recovery = controller.restore(args.project_id)
|
||||
return 0, {
|
||||
"project_id": args.project_id,
|
||||
"recovery_path": str(recovery),
|
||||
"state": controller.project_state(args.project_id).value,
|
||||
}
|
||||
if args.command == "reconcile":
|
||||
controller.reconcile(args.project_id)
|
||||
return 0, {
|
||||
"project_id": args.project_id,
|
||||
"state": controller.project_state(args.project_id).value,
|
||||
}
|
||||
if args.command == "report":
|
||||
return 0, controller.report()
|
||||
if args.command == "status":
|
||||
return 0, controller.status()
|
||||
raise _UsageError(f"unknown command: {args.command}")
|
||||
|
||||
|
||||
def _text(payload: dict[str, object]) -> str:
|
||||
if "error" in payload:
|
||||
error = payload["error"]
|
||||
assert isinstance(error, dict)
|
||||
return f"{error['code']}: {error['message']}"
|
||||
if "action" in payload:
|
||||
return f"{payload['action']}: {payload.get('project_id', payload.get('project', ''))}"
|
||||
if "state" in payload:
|
||||
return f"{payload.get('project_id', 'job')}: {payload['state']}"
|
||||
if "job_id" in payload:
|
||||
return f"job {payload['job_id']}"
|
||||
if "projects" in payload and isinstance(payload["projects"], list):
|
||||
return "\n".join(str(item) for item in payload["projects"])
|
||||
return _canonical_display(payload)
|
||||
|
||||
|
||||
def _canonical_display(payload: dict[str, object]) -> str:
|
||||
return json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
"""Run one CLI operation and return only the documented 0/2/3/4 status."""
|
||||
arguments = list(sys.argv[1:] if argv is None else argv)
|
||||
json_output = "--json" in arguments
|
||||
arguments = [argument for argument in arguments if argument != "--json"]
|
||||
try:
|
||||
code, payload = _run(_parser().parse_args(arguments))
|
||||
except (
|
||||
InputError,
|
||||
ProtocolError,
|
||||
StateError,
|
||||
BackupError,
|
||||
CertificationError,
|
||||
CompatibilityProfileError,
|
||||
ControllerError,
|
||||
_UsageError,
|
||||
OSError,
|
||||
) as error:
|
||||
raw_code = getattr(error, "exit_code", 2)
|
||||
code = raw_code if raw_code in {2, 3, 4} else 2
|
||||
payload = {
|
||||
"error": {
|
||||
"code": getattr(error, "code", "invalid_input"),
|
||||
"message": getattr(error, "message", str(error)),
|
||||
}
|
||||
}
|
||||
output = _canonical_display(payload) if json_output else _text(payload)
|
||||
print(output)
|
||||
return code
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover - exercised by the package entry point
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Exact durable dictionary schema for bridge commands."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .errors import ControllerError
|
||||
from .models import Scope
|
||||
from .protocol import BridgeCommand
|
||||
|
||||
|
||||
_COMMAND_FIELDS = {
|
||||
"action",
|
||||
"command_id",
|
||||
"expected_count",
|
||||
"expected_fingerprint",
|
||||
"expected_logical_keys",
|
||||
"format_version",
|
||||
"job_id",
|
||||
"new_part_number",
|
||||
"old_part_number",
|
||||
"project_id",
|
||||
"scope",
|
||||
}
|
||||
|
||||
|
||||
def command_data(command: BridgeCommand) -> dict[str, object]:
|
||||
"""Return the canonical durable dictionary for a bridge command."""
|
||||
return {
|
||||
"action": command.action,
|
||||
"command_id": command.command_id,
|
||||
"expected_count": command.expected_count,
|
||||
"expected_fingerprint": command.expected_fingerprint,
|
||||
"expected_logical_keys": list(command.expected_logical_keys),
|
||||
"format_version": command.format_version,
|
||||
"job_id": command.job_id,
|
||||
"new_part_number": command.new_part_number,
|
||||
"old_part_number": command.old_part_number,
|
||||
"project_id": command.project_id,
|
||||
"scope": command.scope.value,
|
||||
}
|
||||
|
||||
|
||||
def command_from_data(value: object) -> BridgeCommand:
|
||||
"""Parse one exact durable command dictionary and fail closed."""
|
||||
if type(value) is not dict or set(value) != _COMMAND_FIELDS:
|
||||
raise ControllerError(
|
||||
"corrupt_publication",
|
||||
"durable command fields are invalid",
|
||||
)
|
||||
strings = (
|
||||
"action",
|
||||
"command_id",
|
||||
"expected_fingerprint",
|
||||
"job_id",
|
||||
"new_part_number",
|
||||
"old_part_number",
|
||||
"project_id",
|
||||
"scope",
|
||||
)
|
||||
if any(type(value[name]) is not str for name in strings):
|
||||
raise ControllerError(
|
||||
"corrupt_publication",
|
||||
"durable command strings are invalid",
|
||||
)
|
||||
command_id = value["command_id"]
|
||||
expected_keys = value["expected_logical_keys"]
|
||||
expected_count = value["expected_count"]
|
||||
if (
|
||||
value["format_version"] != 1
|
||||
or type(value["format_version"]) is not int
|
||||
or type(expected_count) is not int
|
||||
or expected_count < 0
|
||||
or type(expected_keys) is not list
|
||||
or any(type(item) is not str for item in expected_keys)
|
||||
or expected_count != len(expected_keys)
|
||||
or len(command_id) != 32
|
||||
or any(character not in "0123456789abcdef" for character in command_id)
|
||||
):
|
||||
raise ControllerError(
|
||||
"corrupt_publication",
|
||||
"durable command values are invalid",
|
||||
)
|
||||
try:
|
||||
scope = Scope(value["scope"])
|
||||
except ValueError as error:
|
||||
raise ControllerError(
|
||||
"corrupt_publication",
|
||||
"durable command scope is invalid",
|
||||
) from error
|
||||
return BridgeCommand(
|
||||
format_version=value["format_version"],
|
||||
command_id=command_id,
|
||||
action=value["action"],
|
||||
job_id=value["job_id"],
|
||||
project_id=value["project_id"],
|
||||
scope=scope,
|
||||
old_part_number=value["old_part_number"],
|
||||
new_part_number=value["new_part_number"],
|
||||
expected_logical_keys=tuple(expected_keys),
|
||||
expected_count=expected_count,
|
||||
expected_fingerprint=value["expected_fingerprint"],
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,13 @@
|
||||
"""Stable use-case errors shared by orchestration modules."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ControllerError(ValueError):
|
||||
"""A stable orchestration failure suitable for CLI reporting."""
|
||||
|
||||
def __init__(self, code: str, message: str, *, exit_code: int = 2) -> None:
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.exit_code = exit_code
|
||||
super().__init__(f"{code}: {message}")
|
||||
@@ -0,0 +1,204 @@
|
||||
"""Validation and discovery for replacement-job input files."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from .models import MappingRule, ProjectRef
|
||||
|
||||
|
||||
class InputError(ValueError):
|
||||
"""A user-correctable input error with a stable machine-readable code."""
|
||||
|
||||
def __init__(self, code: str, message: str) -> None:
|
||||
self.code = code
|
||||
self.message = message
|
||||
super().__init__(f"{code}: {message}")
|
||||
|
||||
|
||||
_MAPPING_HEADER = ("old_part_number", "new_part_number")
|
||||
|
||||
|
||||
def _mapping_rows(data: bytes, source: Path) -> list[dict[str, str | None]]:
|
||||
try:
|
||||
with io.StringIO(data.decode("utf-8-sig"), newline="") as handle:
|
||||
reader = csv.DictReader(handle, strict=True)
|
||||
fields = tuple(reader.fieldnames or ())
|
||||
if len(fields) != 2 or set(fields) != set(_MAPPING_HEADER):
|
||||
raise InputError(
|
||||
"mapping_header",
|
||||
"mapping must have exactly old_part_number,new_part_number columns",
|
||||
)
|
||||
return list(reader)
|
||||
except InputError:
|
||||
raise
|
||||
except UnicodeError as error:
|
||||
raise InputError("mapping_encoding", f"mapping is not valid UTF-8: {source}") from error
|
||||
except csv.Error as error:
|
||||
raise InputError("mapping_csv", f"invalid mapping CSV: {source}") from error
|
||||
|
||||
|
||||
def _read_input_bytes(path: Path, role: str) -> bytes:
|
||||
try:
|
||||
return path.read_bytes()
|
||||
except OSError as error:
|
||||
raise InputError(f"{role}_file", f"cannot read {role} file: {path}") from error
|
||||
|
||||
|
||||
def _has_cycle(graph: dict[str, str]) -> bool:
|
||||
visited: set[str] = set()
|
||||
for source in graph:
|
||||
path: set[str] = set()
|
||||
node: str | None = source
|
||||
while node is not None and node in graph:
|
||||
if node in path:
|
||||
return True
|
||||
if node in visited:
|
||||
break
|
||||
path.add(node)
|
||||
visited.add(node)
|
||||
node = graph[node]
|
||||
return False
|
||||
|
||||
|
||||
def parse_mapping_bytes(data: bytes, source: Path) -> tuple[MappingRule, ...]:
|
||||
"""Validate one immutable byte snapshot of an ordered replacement mapping."""
|
||||
rows = _mapping_rows(data, source)
|
||||
rules: list[MappingRule] = []
|
||||
sources: set[str] = set()
|
||||
graph: dict[str, str] = {}
|
||||
|
||||
for row_number, row in enumerate(rows, start=2):
|
||||
if None in row:
|
||||
raise InputError("mapping_columns", f"mapping row {row_number} has extra values")
|
||||
old = (row.get("old_part_number") or "").strip()
|
||||
new = (row.get("new_part_number") or "").strip()
|
||||
if not old or not new:
|
||||
raise InputError("blank_part_number", f"mapping row {row_number} has a blank part number")
|
||||
old_identity = old.casefold()
|
||||
new_identity = new.casefold()
|
||||
if old_identity == new_identity:
|
||||
raise InputError("equal_rule", f"mapping row {row_number} maps a part to itself")
|
||||
if old_identity in sources:
|
||||
raise InputError("duplicate_source", f"mapping row {row_number} repeats source {old!r}")
|
||||
sources.add(old_identity)
|
||||
graph[old_identity] = new_identity
|
||||
rules.append(MappingRule(old, new))
|
||||
|
||||
if _has_cycle(graph):
|
||||
raise InputError("mapping_cycle", "mapping contains a directed cycle")
|
||||
if any(target in sources for target in graph.values()):
|
||||
raise InputError("mapping_chain", "mapping contains a chained target")
|
||||
return tuple(rules)
|
||||
|
||||
|
||||
def load_mapping(path: Path) -> tuple[MappingRule, ...]:
|
||||
"""Load and validate an ordered, non-chaining replacement mapping."""
|
||||
source = Path(path)
|
||||
return parse_mapping_bytes(_read_input_bytes(source, "mapping"), source)
|
||||
|
||||
|
||||
def _canonical_path(path: Path) -> Path:
|
||||
return path.resolve()
|
||||
|
||||
|
||||
def _path_identity(path: Path) -> str:
|
||||
canonical = os.path.normpath(str(path))
|
||||
return os.path.normcase(canonical) if os.name == "nt" else canonical
|
||||
|
||||
|
||||
def _project_id(path: Path) -> str:
|
||||
return hashlib.sha256(_path_identity(path).encode("utf-8")).hexdigest()[:16]
|
||||
|
||||
|
||||
def _allowed_suffixes(allowed_suffixes: tuple[str, ...]) -> set[str]:
|
||||
return {suffix.casefold() for suffix in allowed_suffixes}
|
||||
|
||||
|
||||
def _contains_path(parent: Path, child: Path) -> bool:
|
||||
parent_identity = _path_identity(parent)
|
||||
child_identity = _path_identity(child)
|
||||
try:
|
||||
return os.path.commonpath((parent_identity, child_identity)) == parent_identity
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def parse_projects_bytes(
|
||||
data: bytes,
|
||||
source: Path,
|
||||
allowed_suffixes: tuple[str, ...],
|
||||
) -> tuple[ProjectRef, ...]:
|
||||
"""Validate one immutable byte snapshot of a project list."""
|
||||
try:
|
||||
lines = data.decode("utf-8-sig").splitlines()
|
||||
except UnicodeError as error:
|
||||
raise InputError("projects_encoding", f"project list is not valid UTF-8: {source}") from error
|
||||
|
||||
suffixes = _allowed_suffixes(allowed_suffixes)
|
||||
refs: list[ProjectRef] = []
|
||||
identities: set[str] = set()
|
||||
ownership_roots: list[Path] = []
|
||||
for line_number, raw_line in enumerate(lines, start=1):
|
||||
raw_path = raw_line.strip()
|
||||
if not raw_path or raw_path.startswith("#"):
|
||||
continue
|
||||
project = Path(raw_path)
|
||||
if not project.is_absolute():
|
||||
raise InputError("project_path_not_absolute", f"line {line_number} is not an absolute path")
|
||||
if not project.exists():
|
||||
raise InputError("project_not_found", f"project on line {line_number} does not exist")
|
||||
if not project.is_file():
|
||||
raise InputError("project_not_file", f"project on line {line_number} is not a file")
|
||||
if project.suffix.casefold() not in suffixes:
|
||||
raise InputError("unsupported_project_suffix", f"project on line {line_number} has an unsupported suffix")
|
||||
|
||||
canonical = _canonical_path(project)
|
||||
identity = _path_identity(canonical)
|
||||
if identity in identities:
|
||||
raise InputError("duplicate_project", f"project on line {line_number} duplicates an earlier path")
|
||||
ownership_root = canonical.parent
|
||||
if any(
|
||||
_contains_path(existing, ownership_root)
|
||||
or _contains_path(ownership_root, existing)
|
||||
for existing in ownership_roots
|
||||
):
|
||||
raise InputError(
|
||||
"overlapping_project_roots",
|
||||
f"project on line {line_number} has an overlapping ownership root",
|
||||
)
|
||||
identities.add(identity)
|
||||
ownership_roots.append(ownership_root)
|
||||
refs.append(ProjectRef(_project_id(canonical), str(canonical), canonical.stem))
|
||||
return tuple(refs)
|
||||
|
||||
|
||||
def load_projects(path: Path, allowed_suffixes: tuple[str, ...]) -> tuple[ProjectRef, ...]:
|
||||
"""Load an ordered list of existing absolute project-definition files."""
|
||||
source = Path(path)
|
||||
return parse_projects_bytes(
|
||||
_read_input_bytes(source, "projects"),
|
||||
source,
|
||||
allowed_suffixes,
|
||||
)
|
||||
|
||||
|
||||
def discover_projects(root: Path, allowed_suffixes: tuple[str, ...]) -> tuple[Path, ...]:
|
||||
"""Find project-definition candidates recursively without modifying inputs."""
|
||||
if not root.exists():
|
||||
raise InputError("discovery_root", f"discovery root does not exist: {root}")
|
||||
if not root.is_dir():
|
||||
raise InputError("discovery_root", f"discovery root is not a directory: {root}")
|
||||
|
||||
suffixes = _allowed_suffixes(allowed_suffixes)
|
||||
candidates: dict[str, Path] = {}
|
||||
for candidate in root.rglob("*"):
|
||||
if not candidate.is_file() or candidate.suffix.casefold() not in suffixes:
|
||||
continue
|
||||
canonical = _canonical_path(candidate)
|
||||
candidates.setdefault(_path_identity(canonical), canonical)
|
||||
return tuple(sorted(candidates.values(), key=lambda path: str(path).casefold()))
|
||||
@@ -0,0 +1,221 @@
|
||||
"""Fail-closed correlation for bridge mailbox evidence."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from .errors import ControllerError
|
||||
from .models import DesignSnapshot, ProjectRef
|
||||
from .protocol import (
|
||||
BridgeCommand,
|
||||
ProtocolError,
|
||||
load_snapshot,
|
||||
load_status,
|
||||
snapshot_fingerprint,
|
||||
)
|
||||
|
||||
|
||||
_BLOCKING_EXIT = 3
|
||||
|
||||
|
||||
def same_path(left: str | Path, right: str | Path) -> bool:
|
||||
"""Compare paths using host-native absolute-path casing rules."""
|
||||
return os.path.normcase(os.path.abspath(os.fspath(left))) == os.path.normcase(
|
||||
os.path.abspath(os.fspath(right))
|
||||
)
|
||||
|
||||
|
||||
def validate_snapshot_identity(
|
||||
project: ProjectRef,
|
||||
snapshot: DesignSnapshot,
|
||||
) -> None:
|
||||
"""Require snapshot ownership to match the queued project exactly."""
|
||||
if snapshot.project_id != project.project_id or not same_path(
|
||||
snapshot.project_path,
|
||||
project.project_path,
|
||||
):
|
||||
raise ControllerError(
|
||||
"snapshot_project_mismatch",
|
||||
f"snapshot identity does not match queued project {project.project_id}",
|
||||
)
|
||||
if not snapshot.fingerprint:
|
||||
raise ControllerError(
|
||||
"invalid_snapshot_fingerprint",
|
||||
"snapshot fingerprint must be nonempty",
|
||||
)
|
||||
|
||||
|
||||
def consume_correlated_snapshot(
|
||||
project: ProjectRef,
|
||||
command: BridgeCommand,
|
||||
expected_state: str,
|
||||
status_path: Path,
|
||||
snapshot_path: Path,
|
||||
) -> tuple[DesignSnapshot, Path]:
|
||||
"""Load a snapshot only when status and command lineage match exactly."""
|
||||
try:
|
||||
status = load_status(status_path)
|
||||
except ProtocolError as error:
|
||||
raise ControllerError(
|
||||
"mailbox_evidence_uncorrelated",
|
||||
"bridge status is missing or invalid",
|
||||
exit_code=_BLOCKING_EXIT,
|
||||
) from error
|
||||
expected_details = (
|
||||
("action", command.action),
|
||||
("expected_count", str(command.expected_count)),
|
||||
("job_id", command.job_id),
|
||||
)
|
||||
if (
|
||||
status.command_id != command.command_id
|
||||
or status.project_id != command.project_id
|
||||
or status.details != expected_details
|
||||
or (status.error_code is None) != (status.error_message is None)
|
||||
):
|
||||
raise ControllerError(
|
||||
"mailbox_evidence_uncorrelated",
|
||||
"bridge status does not match the durable command",
|
||||
exit_code=_BLOCKING_EXIT,
|
||||
)
|
||||
if status.error_code is not None:
|
||||
raise ControllerError(
|
||||
status.error_code,
|
||||
status.error_message or "bridge action failed",
|
||||
exit_code=_BLOCKING_EXIT,
|
||||
)
|
||||
if (
|
||||
status.state != expected_state
|
||||
or status.snapshot_path is None
|
||||
or not same_path(status.snapshot_path, snapshot_path)
|
||||
):
|
||||
raise ControllerError(
|
||||
"mailbox_evidence_uncorrelated",
|
||||
"bridge result state or snapshot path is not the expected mailbox output",
|
||||
exit_code=_BLOCKING_EXIT,
|
||||
)
|
||||
try:
|
||||
snapshot = load_snapshot(snapshot_path)
|
||||
validate_snapshot_identity(project, snapshot)
|
||||
except (ControllerError, ProtocolError) as error:
|
||||
raise ControllerError(
|
||||
"mailbox_evidence_uncorrelated",
|
||||
"bridge snapshot is missing or invalid",
|
||||
exit_code=_BLOCKING_EXIT,
|
||||
) from error
|
||||
if snapshot.fingerprint != snapshot_fingerprint(snapshot):
|
||||
raise ControllerError(
|
||||
"mailbox_evidence_uncorrelated",
|
||||
"bridge snapshot fingerprint does not match its contents",
|
||||
exit_code=_BLOCKING_EXIT,
|
||||
)
|
||||
return snapshot, snapshot_path.resolve()
|
||||
|
||||
|
||||
def has_correlated_snapshot(
|
||||
project: ProjectRef,
|
||||
command: BridgeCommand,
|
||||
status_path: Path,
|
||||
snapshot_path: Path,
|
||||
) -> bool:
|
||||
"""Return whether mailbox outputs prove completion of this command."""
|
||||
expected_state = {
|
||||
"close_project": "project_closed",
|
||||
"close_without_save": "project_closed",
|
||||
"erc": "external_check_passed",
|
||||
"inventory": "inventory_exported",
|
||||
"netlist": "external_check_passed",
|
||||
"open_project": "project_opened",
|
||||
"packager": "external_check_passed",
|
||||
"replace_part": "applied",
|
||||
}.get(command.action)
|
||||
if expected_state is None:
|
||||
return False
|
||||
try:
|
||||
consume_correlated_snapshot(
|
||||
project,
|
||||
command,
|
||||
expected_state,
|
||||
status_path,
|
||||
snapshot_path,
|
||||
)
|
||||
except (ControllerError, ProtocolError):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def operator_waiting_status(
|
||||
status_path: Path,
|
||||
command: BridgeCommand,
|
||||
) -> tuple[str, str | None, str | None] | None:
|
||||
"""Parse only status states that authorize an explicit operator wait."""
|
||||
if not status_path.is_file():
|
||||
return None
|
||||
try:
|
||||
status = load_status(status_path)
|
||||
except ProtocolError:
|
||||
return None
|
||||
details = dict(status.details)
|
||||
if (
|
||||
status.command_id != command.command_id
|
||||
or status.project_id != command.project_id
|
||||
or status.snapshot_path is not None
|
||||
or status.error_code is not None
|
||||
or status.error_message is not None
|
||||
or details.get("action") != command.action
|
||||
or details.get("expected_count") != str(command.expected_count)
|
||||
or details.get("job_id") != command.job_id
|
||||
):
|
||||
return None
|
||||
if status.state == "native_dialog_opening" and command.action == "replace_part":
|
||||
return status.state, None, details.get("instruction")
|
||||
if status.state not in {
|
||||
"manual_action_required",
|
||||
"manual_project_open_required",
|
||||
}:
|
||||
return None
|
||||
manual_route = details.get("manual_route")
|
||||
allowed_routes = {
|
||||
"close_project": {"manual_close_project"},
|
||||
"close_without_save": {"manual_close_without_save"},
|
||||
"open_project": {"manual_project_open"},
|
||||
"replace_part": {"manual_exact_selection", "manual_native_dialog"},
|
||||
"save": {"manual_native_save"},
|
||||
"undo": {"manual_native_undo"},
|
||||
}.get(command.action, set())
|
||||
expected_state = (
|
||||
"manual_project_open_required"
|
||||
if manual_route == "manual_project_open"
|
||||
else "manual_action_required"
|
||||
)
|
||||
if manual_route not in allowed_routes or status.state != expected_state:
|
||||
return None
|
||||
return status.state, manual_route, details.get("instruction")
|
||||
|
||||
|
||||
def has_control_predecessor_status(
|
||||
status_path: Path,
|
||||
command: BridgeCommand,
|
||||
) -> bool:
|
||||
"""Recognize retained Apply evidence needed before native Undo or Save."""
|
||||
if command.action not in {"save", "undo"} or not status_path.is_file():
|
||||
return False
|
||||
try:
|
||||
status = load_status(status_path)
|
||||
except ProtocolError:
|
||||
return False
|
||||
return (
|
||||
status.command_id == command.command_id
|
||||
and status.project_id == command.project_id
|
||||
and status.state == "applied"
|
||||
and status.snapshot_path is not None
|
||||
and same_path(status.snapshot_path, status_path.parent / "snapshot.json")
|
||||
and status.error_code is None
|
||||
and status.error_message is None
|
||||
and status.details
|
||||
== (
|
||||
("action", "replace_part"),
|
||||
("expected_count", str(command.expected_count)),
|
||||
("job_id", command.job_id),
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,156 @@
|
||||
"""Immutable protocol and domain records for part replacement."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal
|
||||
from enum import Enum
|
||||
from typing import Mapping
|
||||
|
||||
|
||||
class Scope(str, Enum):
|
||||
FULL_PROJECT = "full_project"
|
||||
CURRENT_SHEET = "current_sheet"
|
||||
SELECTED_COMPONENT = "selected_component"
|
||||
|
||||
|
||||
class ProjectState(str, Enum):
|
||||
INVENTORY_PENDING = "inventory_pending"
|
||||
INVENTORY_COMPLETE = "inventory_complete"
|
||||
APPLY_PENDING = "apply_pending"
|
||||
APPLYING = "applying"
|
||||
AWAITING_SAVE_CONFIRMATION = "awaiting_save_confirmation"
|
||||
AWAITING_EXTERNAL_CHECKS = "awaiting_external_checks"
|
||||
VERIFIED_SAVED = "verified_saved"
|
||||
BLOCKED = "blocked"
|
||||
|
||||
|
||||
def _pairs(value: Mapping[str, str] | tuple[tuple[str, str], ...] | list[tuple[str, str]] | None) -> tuple[tuple[str, str], ...]:
|
||||
if value is None:
|
||||
return ()
|
||||
return tuple(sorted((str(key), str(item)) for key, item in dict(value).items())) if isinstance(value, Mapping) else tuple(sorted((str(key), str(item)) for key, item in value))
|
||||
|
||||
|
||||
def _detail_pairs(value: tuple[tuple[str, str], ...] | list[tuple[str, str]]) -> tuple[tuple[str, str], ...]:
|
||||
pairs: list[tuple[str, str]] = []
|
||||
for entry in value:
|
||||
if len(entry) != 2:
|
||||
raise ValueError("issue detail entries must contain exactly two values")
|
||||
pairs.append((str(entry[0]), str(entry[1])))
|
||||
return tuple(pairs)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class MappingRule:
|
||||
old_part_number: str
|
||||
new_part_number: str
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ProjectRef:
|
||||
project_id: str
|
||||
project_path: str
|
||||
display_name: str
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PinSnapshot:
|
||||
number: str
|
||||
name: str
|
||||
x: Decimal
|
||||
y: Decimal
|
||||
net: str | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "x", Decimal(str(self.x)))
|
||||
object.__setattr__(self, "y", Decimal(str(self.y)))
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class UnitSnapshot:
|
||||
unit_id: str
|
||||
sheet: str
|
||||
symbol: str
|
||||
origin_x: Decimal
|
||||
origin_y: Decimal
|
||||
x: Decimal
|
||||
y: Decimal
|
||||
rotation: int
|
||||
mirrored: bool
|
||||
pins: tuple[PinSnapshot, ...] = ()
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "origin_x", Decimal(str(self.origin_x)))
|
||||
object.__setattr__(self, "origin_y", Decimal(str(self.origin_y)))
|
||||
object.__setattr__(self, "x", Decimal(str(self.x)))
|
||||
object.__setattr__(self, "y", Decimal(str(self.y)))
|
||||
object.__setattr__(self, "rotation", int(self.rotation))
|
||||
object.__setattr__(self, "pins", tuple(self.pins))
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ComponentSnapshot:
|
||||
logical_key: str
|
||||
refdes: str
|
||||
part_number: str
|
||||
units: tuple[UnitSnapshot, ...] = ()
|
||||
attributes: tuple[tuple[str, str], ...] = ()
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "units", tuple(self.units))
|
||||
object.__setattr__(self, "attributes", _pairs(self.attributes))
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DesignSnapshot:
|
||||
format_version: int
|
||||
project_id: str
|
||||
project_path: str
|
||||
fingerprint: str
|
||||
components: tuple[ComponentSnapshot, ...] = ()
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "components", tuple(self.components))
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Issue:
|
||||
code: str
|
||||
severity: str
|
||||
message: str
|
||||
details: tuple[tuple[str, str], ...] = ()
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "details", _detail_pairs(self.details))
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class VerificationResult:
|
||||
project_id: str
|
||||
rule: MappingRule
|
||||
expected_logical_keys: tuple[str, ...]
|
||||
changed_logical_keys: tuple[str, ...] = ()
|
||||
issues: tuple[Issue, ...] = ()
|
||||
passed: bool = False
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "expected_logical_keys", tuple(self.expected_logical_keys))
|
||||
object.__setattr__(self, "changed_logical_keys", tuple(self.changed_logical_keys))
|
||||
object.__setattr__(self, "issues", tuple(self.issues))
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ImpactCell:
|
||||
project_id: str
|
||||
rule: MappingRule
|
||||
logical_count: int
|
||||
unit_count: int
|
||||
issues: tuple[Issue, ...] = ()
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "issues", tuple(self.issues))
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ExternalChecks:
|
||||
packager: bool | None = None
|
||||
erc: bool | None = None
|
||||
netlist: bool | None = None
|
||||
@@ -0,0 +1,446 @@
|
||||
"""Resumable operator-loop policy over controller use cases."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Protocol
|
||||
|
||||
from .errors import ControllerError
|
||||
from .mailbox import has_control_predecessor_status, operator_waiting_status
|
||||
from .models import MappingRule, ProjectRef, ProjectState
|
||||
from .protocol import BridgeCommand
|
||||
|
||||
|
||||
_MANUAL_EXIT = 4
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class OperatorStepResult:
|
||||
"""One resumable operator-loop outcome and, at most, one live command."""
|
||||
|
||||
complete: bool
|
||||
project: ProjectRef | None
|
||||
command: BridgeCommand | None
|
||||
state: ProjectState | None
|
||||
consumed_action: str | None = None
|
||||
bridge_state: str | None = None
|
||||
manual_route: str | None = None
|
||||
instruction: str | None = None
|
||||
|
||||
|
||||
class OperatorBackend(Protocol):
|
||||
"""Controller operations and projections required by the operator policy."""
|
||||
|
||||
projects: Sequence[ProjectRef]
|
||||
rules: Sequence[MappingRule]
|
||||
|
||||
def project_state(self, project_id: str) -> ProjectState: ...
|
||||
|
||||
def command_path(self, project_id: str) -> Any: ...
|
||||
|
||||
def _latest_event(
|
||||
self,
|
||||
project_id: str,
|
||||
names: set[str],
|
||||
) -> dict[str, Any] | None: ...
|
||||
|
||||
def _latest_cycle_event(
|
||||
self,
|
||||
project_id: str,
|
||||
names: set[str],
|
||||
) -> dict[str, Any] | None: ...
|
||||
|
||||
def _unfinished_command_publication(
|
||||
self,
|
||||
project_id: str,
|
||||
intent_event: str,
|
||||
prepared_event: str,
|
||||
) -> dict[str, Any] | None: ...
|
||||
|
||||
def _pending_command_event(self, project_id: str) -> dict[str, Any] | None: ...
|
||||
|
||||
def _pending_auxiliary_event(
|
||||
self,
|
||||
project_id: str,
|
||||
prepared_event: str,
|
||||
completed_events: set[str],
|
||||
) -> dict[str, Any] | None: ...
|
||||
|
||||
def _recorded_inventory_command(
|
||||
self,
|
||||
project_id: str,
|
||||
prepared: dict[str, Any],
|
||||
) -> BridgeCommand: ...
|
||||
|
||||
def _recorded_apply_command(
|
||||
self,
|
||||
project_id: str,
|
||||
prepared: dict[str, Any],
|
||||
) -> BridgeCommand: ...
|
||||
|
||||
def _verified_rule_indices(self, project_id: str) -> tuple[int, ...]: ...
|
||||
|
||||
def _matching_rule_indices(self, project_id: str) -> tuple[int, ...]: ...
|
||||
|
||||
def _finish_inventory_phase(self) -> None: ...
|
||||
|
||||
def _passed_external_checks(self, project_id: str) -> tuple[str, ...]: ...
|
||||
|
||||
def prepare_inventory(self, project_id: str) -> BridgeCommand: ...
|
||||
|
||||
def ingest_inventory(self, project_id: str) -> None: ...
|
||||
|
||||
def prepare_close(self, project_id: str) -> BridgeCommand: ...
|
||||
|
||||
def confirm_close(self, project_id: str) -> None: ...
|
||||
|
||||
def prepare_open(self, project_id: str) -> BridgeCommand: ...
|
||||
|
||||
def confirm_open(self, project_id: str) -> None: ...
|
||||
|
||||
def prepare_apply(self, project_id: str, rule_index: int) -> BridgeCommand: ...
|
||||
|
||||
def verify_apply(self, project_id: str, rule_index: int) -> Any: ...
|
||||
|
||||
def prepare_undo(self, project_id: str) -> BridgeCommand: ...
|
||||
|
||||
def confirm_undo(self, project_id: str) -> None: ...
|
||||
|
||||
def prepare_save(self, project_id: str) -> BridgeCommand: ...
|
||||
|
||||
def confirm_saved(self, project_id: str) -> ProjectState: ...
|
||||
|
||||
def prepare_external_check(
|
||||
self,
|
||||
project_id: str,
|
||||
check: str,
|
||||
) -> BridgeCommand: ...
|
||||
|
||||
def confirm_external_check(
|
||||
self,
|
||||
project_id: str,
|
||||
check: str,
|
||||
) -> ProjectState: ...
|
||||
|
||||
def reconcile(self, project_id: str) -> None: ...
|
||||
|
||||
def complete_verified_rules(self, project_id: str) -> None: ...
|
||||
|
||||
|
||||
def _apply_rule_index(backend: OperatorBackend, project_id: str) -> int:
|
||||
pending = backend._pending_command_event(project_id)
|
||||
if pending is not None:
|
||||
value = pending["payload"].get("rule_index")
|
||||
if type(value) is int and 0 <= value < len(backend.rules):
|
||||
return value
|
||||
unfinished = backend._unfinished_command_publication(
|
||||
project_id,
|
||||
"apply_command_publication_started",
|
||||
"command_prepared",
|
||||
)
|
||||
if unfinished is not None:
|
||||
value = unfinished["payload"].get("rule_index")
|
||||
if type(value) is int and 0 <= value < len(backend.rules):
|
||||
return value
|
||||
verified = set(backend._verified_rule_indices(project_id))
|
||||
remaining = tuple(
|
||||
index
|
||||
for index in backend._matching_rule_indices(project_id)
|
||||
if index not in verified
|
||||
)
|
||||
if not remaining:
|
||||
raise ControllerError(
|
||||
"rule_order",
|
||||
"project has no remaining replacement rule to prepare",
|
||||
)
|
||||
return remaining[0]
|
||||
|
||||
|
||||
def _current_command(
|
||||
backend: OperatorBackend,
|
||||
) -> tuple[ProjectRef | None, BridgeCommand | None]:
|
||||
while True:
|
||||
project = next_project(backend)
|
||||
if project is None:
|
||||
return None, None
|
||||
project_id = project.project_id
|
||||
action = action_for(backend, project_id)
|
||||
if action == "ingest":
|
||||
prepared = backend._latest_cycle_event(
|
||||
project_id,
|
||||
{"inventory_command_prepared"},
|
||||
)
|
||||
if prepared is not None:
|
||||
return project, backend._recorded_inventory_command(
|
||||
project_id,
|
||||
prepared,
|
||||
)
|
||||
return project, backend.prepare_inventory(project_id)
|
||||
if action == "prepare-close":
|
||||
return project, backend.prepare_close(project_id)
|
||||
if action == "prepare-open":
|
||||
return project, backend.prepare_open(project_id)
|
||||
if action in {"prepare-undo", "confirm-undo"}:
|
||||
return project, backend.prepare_undo(project_id)
|
||||
if action in {"prepare-save", "confirm-saved"}:
|
||||
return project, backend.prepare_save(project_id)
|
||||
if action == "prepare":
|
||||
return project, backend.prepare_apply(
|
||||
project_id,
|
||||
_apply_rule_index(backend, project_id),
|
||||
)
|
||||
if action == "reconcile":
|
||||
if backend.project_state(project_id) is ProjectState.APPLYING:
|
||||
pending = backend._pending_command_event(project_id)
|
||||
if pending is not None:
|
||||
return project, backend._recorded_apply_command(
|
||||
project_id,
|
||||
pending,
|
||||
)
|
||||
matching = set(backend._matching_rule_indices(project_id))
|
||||
verified = set(backend._verified_rule_indices(project_id))
|
||||
if matching and matching.issubset(verified):
|
||||
backend.complete_verified_rules(project_id)
|
||||
continue
|
||||
return project, backend.prepare_apply(
|
||||
project_id,
|
||||
_apply_rule_index(backend, project_id),
|
||||
)
|
||||
backend.reconcile(project_id)
|
||||
continue
|
||||
if action == "await_inventory":
|
||||
backend._finish_inventory_phase()
|
||||
if action_for(backend, project_id) == "await_inventory":
|
||||
raise ControllerError(
|
||||
"inventory_barrier_wait",
|
||||
"another project inventory must complete before Apply",
|
||||
exit_code=_MANUAL_EXIT,
|
||||
)
|
||||
continue
|
||||
if action.startswith("prepare-") or action.startswith("confirm-"):
|
||||
check = action.split("-", 1)[1]
|
||||
if check in {"packager", "erc", "netlist"}:
|
||||
pending = backend._pending_auxiliary_event(
|
||||
project_id,
|
||||
"external_check_command_prepared",
|
||||
{"external_check_verified"},
|
||||
)
|
||||
if pending is None and action == "confirm-netlist":
|
||||
backend.confirm_external_check(project_id, check)
|
||||
continue
|
||||
return project, backend.prepare_external_check(project_id, check)
|
||||
raise ControllerError(
|
||||
"operator_action_unsupported",
|
||||
f"operator loop cannot dispatch action {action!r}",
|
||||
)
|
||||
|
||||
|
||||
def _consume(backend: OperatorBackend, command: BridgeCommand) -> None:
|
||||
project_id = command.project_id
|
||||
if command.action == "inventory":
|
||||
backend.ingest_inventory(project_id)
|
||||
return
|
||||
if command.action in {"close_project", "close_without_save"}:
|
||||
backend.confirm_close(project_id)
|
||||
return
|
||||
if command.action == "open_project":
|
||||
backend.confirm_open(project_id)
|
||||
return
|
||||
if command.action == "replace_part":
|
||||
backend.verify_apply(project_id, _apply_rule_index(backend, project_id))
|
||||
return
|
||||
if command.action == "undo":
|
||||
backend.confirm_undo(project_id)
|
||||
return
|
||||
if command.action == "save":
|
||||
backend.confirm_saved(project_id)
|
||||
return
|
||||
if command.action in {"packager", "erc", "netlist"}:
|
||||
backend.confirm_external_check(project_id, command.action)
|
||||
return
|
||||
raise ControllerError(
|
||||
"operator_action_unsupported",
|
||||
f"operator loop cannot consume action {command.action!r}",
|
||||
)
|
||||
|
||||
|
||||
def _result(
|
||||
backend: OperatorBackend,
|
||||
project: ProjectRef | None,
|
||||
command: BridgeCommand | None,
|
||||
*,
|
||||
consumed_action: str | None,
|
||||
) -> OperatorStepResult:
|
||||
if project is None or command is None:
|
||||
return OperatorStepResult(
|
||||
complete=True,
|
||||
project=None,
|
||||
command=None,
|
||||
state=None,
|
||||
consumed_action=consumed_action,
|
||||
)
|
||||
waiting = operator_waiting_status(
|
||||
backend.command_path(command.project_id).parent / "status.json",
|
||||
command,
|
||||
)
|
||||
bridge_state: str | None = None
|
||||
manual_route: str | None = None
|
||||
instruction: str | None = None
|
||||
if waiting is not None:
|
||||
bridge_state, manual_route, instruction = waiting
|
||||
return OperatorStepResult(
|
||||
complete=False,
|
||||
project=project,
|
||||
command=command,
|
||||
state=backend.project_state(project.project_id),
|
||||
consumed_action=consumed_action,
|
||||
bridge_state=bridge_state,
|
||||
manual_route=manual_route,
|
||||
instruction=instruction,
|
||||
)
|
||||
|
||||
|
||||
def operator_step(backend: OperatorBackend) -> OperatorStepResult:
|
||||
"""Consume at most one result and publish at most one next command."""
|
||||
project, command = _current_command(backend)
|
||||
if project is None or command is None:
|
||||
return _result(
|
||||
backend,
|
||||
project,
|
||||
command,
|
||||
consumed_action=None,
|
||||
)
|
||||
status_path = backend.command_path(project.project_id).parent / "status.json"
|
||||
if (
|
||||
not status_path.exists()
|
||||
or operator_waiting_status(status_path, command) is not None
|
||||
or has_control_predecessor_status(status_path, command)
|
||||
):
|
||||
return _result(
|
||||
backend,
|
||||
project,
|
||||
command,
|
||||
consumed_action=None,
|
||||
)
|
||||
|
||||
try:
|
||||
_consume(backend, command)
|
||||
except ControllerError as error:
|
||||
if error.code != "recovery_snapshot_mismatch":
|
||||
raise
|
||||
return OperatorStepResult(
|
||||
complete=False,
|
||||
project=project,
|
||||
command=None,
|
||||
state=backend.project_state(project.project_id),
|
||||
consumed_action=command.action,
|
||||
instruction=error.message,
|
||||
)
|
||||
next_item, next_command = _current_command(backend)
|
||||
return _result(
|
||||
backend,
|
||||
next_item,
|
||||
next_command,
|
||||
consumed_action=command.action,
|
||||
)
|
||||
|
||||
|
||||
def action_for(backend: OperatorBackend, project_id: str) -> str:
|
||||
"""Project durable state projected to its next operator action."""
|
||||
state = backend.project_state(project_id)
|
||||
if state is ProjectState.INVENTORY_PENDING:
|
||||
reconcile = backend._latest_event(project_id, {"reconcile"})
|
||||
if (
|
||||
reconcile is not None
|
||||
and reconcile["payload"].get("recovery_event")
|
||||
in {"close_without_save_verified", "restore_verified"}
|
||||
and backend._latest_cycle_event(project_id, {"project_opened"}) is None
|
||||
):
|
||||
return "prepare-open"
|
||||
return "ingest"
|
||||
if state is ProjectState.INVENTORY_COMPLETE:
|
||||
return "await_inventory"
|
||||
if state is ProjectState.APPLY_PENDING:
|
||||
backup = backend._latest_cycle_event(project_id, {"backup_verified"})
|
||||
if backup is None:
|
||||
return "prepare-close"
|
||||
opened = backend._latest_cycle_event(project_id, {"project_opened"})
|
||||
if opened is None or opened["sequence"] < backup["sequence"]:
|
||||
return "prepare-open"
|
||||
return "prepare"
|
||||
if state is ProjectState.APPLYING:
|
||||
return "reconcile"
|
||||
if state is ProjectState.AWAITING_SAVE_CONFIRMATION:
|
||||
if backend._pending_auxiliary_event(
|
||||
project_id,
|
||||
"save_command_prepared",
|
||||
{"saved_snapshot_verified"},
|
||||
) is not None:
|
||||
return "confirm-saved"
|
||||
return "prepare-save"
|
||||
if state is ProjectState.AWAITING_EXTERNAL_CHECKS:
|
||||
pending = backend._pending_auxiliary_event(
|
||||
project_id,
|
||||
"external_check_command_prepared",
|
||||
{"external_check_verified"},
|
||||
)
|
||||
if pending is not None:
|
||||
return f"confirm-{pending['payload'].get('check', 'external-check')}"
|
||||
passed = set(backend._passed_external_checks(project_id))
|
||||
remaining = tuple(
|
||||
name for name in ("packager", "erc", "netlist") if name not in passed
|
||||
)
|
||||
return "confirm-netlist" if not remaining else f"prepare-{remaining[0]}"
|
||||
if state is ProjectState.BLOCKED:
|
||||
recovery = backend._latest_cycle_event(
|
||||
project_id,
|
||||
{"close_without_save_verified", "restore_verified", "undo_verified"},
|
||||
)
|
||||
mutation = backend._latest_cycle_event(
|
||||
project_id,
|
||||
{
|
||||
"apply_command_publication_started",
|
||||
"command_prepared",
|
||||
"rule_verified",
|
||||
"undo_required",
|
||||
},
|
||||
)
|
||||
if recovery is not None and (
|
||||
mutation is None or recovery["sequence"] > mutation["sequence"]
|
||||
):
|
||||
return "reconcile"
|
||||
undo = backend._latest_cycle_event(project_id, {"undo_required"})
|
||||
if undo is not None:
|
||||
if backend._pending_auxiliary_event(
|
||||
project_id,
|
||||
"undo_command_prepared",
|
||||
{"undo_verified"},
|
||||
) is not None:
|
||||
return "confirm-undo"
|
||||
return "prepare-undo"
|
||||
if mutation is not None:
|
||||
return "prepare-close"
|
||||
return "reconcile"
|
||||
return "complete"
|
||||
|
||||
|
||||
def next_project(backend: OperatorBackend) -> ProjectRef | None:
|
||||
"""Choose the next incomplete project using fail-safe recovery priority."""
|
||||
candidates = tuple(
|
||||
project
|
||||
for project in backend.projects
|
||||
if backend.project_state(project.project_id) is not ProjectState.VERIFIED_SAVED
|
||||
)
|
||||
|
||||
def priority(project: ProjectRef) -> int:
|
||||
state = backend.project_state(project.project_id)
|
||||
if state is ProjectState.INVENTORY_PENDING:
|
||||
return 0
|
||||
if state is ProjectState.BLOCKED:
|
||||
return 2
|
||||
if state is ProjectState.INVENTORY_COMPLETE:
|
||||
return 3
|
||||
return 1
|
||||
|
||||
return min(candidates, key=priority, default=None)
|
||||
@@ -0,0 +1,405 @@
|
||||
"""Versioned JSON snapshots and atomic mailbox publication."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal, InvalidOperation
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
from typing import Any
|
||||
|
||||
from .models import ComponentSnapshot, DesignSnapshot, PinSnapshot, Scope, UnitSnapshot
|
||||
|
||||
|
||||
_SNAPSHOT_FORMAT_VERSION = 2
|
||||
_MAILBOX_FORMAT_VERSION = 1
|
||||
|
||||
|
||||
class ProtocolError(ValueError):
|
||||
"""A malformed or unsupported bridge-protocol document."""
|
||||
|
||||
def __init__(self, code: str, message: str) -> None:
|
||||
self.code = code
|
||||
self.message = message
|
||||
super().__init__(f"{code}: {message}")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class BridgeCommand:
|
||||
format_version: int
|
||||
command_id: str
|
||||
action: str
|
||||
job_id: str
|
||||
project_id: str
|
||||
scope: Scope
|
||||
old_part_number: str
|
||||
new_part_number: str
|
||||
expected_logical_keys: tuple[str, ...]
|
||||
expected_count: int
|
||||
expected_fingerprint: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "scope", Scope(self.scope))
|
||||
object.__setattr__(self, "expected_logical_keys", tuple(self.expected_logical_keys))
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class BridgeStatus:
|
||||
format_version: int
|
||||
command_id: str
|
||||
project_id: str
|
||||
state: str
|
||||
snapshot_path: str | None
|
||||
error_code: str | None
|
||||
error_message: str | None
|
||||
details: tuple[tuple[str, str], ...]
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "details", tuple((str(key), str(value)) for key, value in self.details))
|
||||
|
||||
|
||||
def _duplicate_rejecting_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
||||
data: dict[str, Any] = {}
|
||||
for name, value in pairs:
|
||||
if name in data:
|
||||
raise ProtocolError("duplicate_field", f"JSON object repeats field {name!r}")
|
||||
data[name] = value
|
||||
return data
|
||||
|
||||
|
||||
def _load_json(path: Path, document_name: str) -> dict[str, Any]:
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8")
|
||||
except UnicodeError as error:
|
||||
raise ProtocolError("invalid_encoding", f"{document_name} is not valid UTF-8: {path}") from error
|
||||
except OSError as error:
|
||||
raise ProtocolError("protocol_file", f"cannot read {document_name}: {path}") from error
|
||||
try:
|
||||
data = json.loads(text, object_pairs_hook=_duplicate_rejecting_object)
|
||||
except ProtocolError:
|
||||
raise
|
||||
except json.JSONDecodeError as error:
|
||||
raise ProtocolError("invalid_json", f"invalid {document_name} JSON: {path}") from error
|
||||
if not isinstance(data, dict):
|
||||
raise ProtocolError("wrong_type", f"{document_name} root must be an object")
|
||||
return data
|
||||
|
||||
|
||||
def _expect_fields(data: dict[str, Any], required: tuple[str, ...], context: str) -> None:
|
||||
missing = set(required) - set(data)
|
||||
if missing:
|
||||
raise ProtocolError("missing_required_field", f"{context} is missing {sorted(missing)[0]!r}")
|
||||
unknown = set(data) - set(required)
|
||||
if unknown:
|
||||
raise ProtocolError("unknown_field", f"{context} has unknown field {sorted(unknown)[0]!r}")
|
||||
|
||||
|
||||
def _string(value: Any, context: str) -> str:
|
||||
if not isinstance(value, str):
|
||||
raise ProtocolError("wrong_type", f"{context} must be a string")
|
||||
return value
|
||||
|
||||
|
||||
def _optional_string(value: Any, context: str) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
return _string(value, context)
|
||||
|
||||
|
||||
def _integer(value: Any, context: str) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise ProtocolError("wrong_type", f"{context} must be an integer")
|
||||
return value
|
||||
|
||||
|
||||
def _boolean(value: Any, context: str) -> bool:
|
||||
if not isinstance(value, bool):
|
||||
raise ProtocolError("wrong_type", f"{context} must be a boolean")
|
||||
return value
|
||||
|
||||
|
||||
def _array(value: Any, context: str) -> list[Any]:
|
||||
if not isinstance(value, list):
|
||||
raise ProtocolError("wrong_type", f"{context} must be an array")
|
||||
return value
|
||||
|
||||
|
||||
def _object(value: Any, context: str) -> dict[str, Any]:
|
||||
if not isinstance(value, dict):
|
||||
raise ProtocolError("wrong_type", f"{context} must be an object")
|
||||
return value
|
||||
|
||||
|
||||
def _decimal(value: Any, context: str) -> Decimal:
|
||||
text = _string(value, context)
|
||||
try:
|
||||
decimal = Decimal(text)
|
||||
except InvalidOperation as error:
|
||||
raise ProtocolError("invalid_decimal", f"{context} is not a Decimal string") from error
|
||||
if not decimal.is_finite():
|
||||
raise ProtocolError("invalid_decimal", f"{context} must be finite")
|
||||
return decimal
|
||||
|
||||
|
||||
def _pin_from_data(data: Any, context: str) -> PinSnapshot:
|
||||
pin = _object(data, context)
|
||||
_expect_fields(pin, ("number", "name", "x", "y", "net"), context)
|
||||
return PinSnapshot(
|
||||
number=_string(pin["number"], f"{context}.number"),
|
||||
name=_string(pin["name"], f"{context}.name"),
|
||||
x=_decimal(pin["x"], f"{context}.x"),
|
||||
y=_decimal(pin["y"], f"{context}.y"),
|
||||
net=_optional_string(pin["net"], f"{context}.net"),
|
||||
)
|
||||
|
||||
|
||||
def _unit_from_data(data: Any, context: str) -> UnitSnapshot:
|
||||
unit = _object(data, context)
|
||||
_expect_fields(
|
||||
unit,
|
||||
(
|
||||
"unit_id",
|
||||
"sheet",
|
||||
"symbol",
|
||||
"origin_x",
|
||||
"origin_y",
|
||||
"x",
|
||||
"y",
|
||||
"rotation",
|
||||
"mirrored",
|
||||
"pins",
|
||||
),
|
||||
context,
|
||||
)
|
||||
pins = tuple(_pin_from_data(pin, f"{context}.pins[{index}]") for index, pin in enumerate(_array(unit["pins"], f"{context}.pins")))
|
||||
numbers = [pin.number for pin in pins]
|
||||
if len(numbers) != len(set(numbers)):
|
||||
raise ProtocolError("duplicate_pin_number", f"{context} has duplicate pin numbers")
|
||||
return UnitSnapshot(
|
||||
unit_id=_string(unit["unit_id"], f"{context}.unit_id"),
|
||||
sheet=_string(unit["sheet"], f"{context}.sheet"),
|
||||
symbol=_string(unit["symbol"], f"{context}.symbol"),
|
||||
origin_x=_decimal(unit["origin_x"], f"{context}.origin_x"),
|
||||
origin_y=_decimal(unit["origin_y"], f"{context}.origin_y"),
|
||||
x=_decimal(unit["x"], f"{context}.x"),
|
||||
y=_decimal(unit["y"], f"{context}.y"),
|
||||
rotation=_integer(unit["rotation"], f"{context}.rotation"),
|
||||
mirrored=_boolean(unit["mirrored"], f"{context}.mirrored"),
|
||||
pins=pins,
|
||||
)
|
||||
|
||||
|
||||
def _component_from_data(data: Any, context: str) -> ComponentSnapshot:
|
||||
component = _object(data, context)
|
||||
_expect_fields(component, ("logical_key", "refdes", "part_number", "units", "attributes"), context)
|
||||
units = tuple(_unit_from_data(unit, f"{context}.units[{index}]") for index, unit in enumerate(_array(component["units"], f"{context}.units")))
|
||||
unit_ids = [unit.unit_id for unit in units]
|
||||
if len(unit_ids) != len(set(unit_ids)):
|
||||
raise ProtocolError("duplicate_unit_id", f"{context} has duplicate unit IDs")
|
||||
attributes: list[tuple[str, str]] = []
|
||||
for index, raw_attribute in enumerate(_array(component["attributes"], f"{context}.attributes")):
|
||||
attribute_context = f"{context}.attributes[{index}]"
|
||||
attribute = _object(raw_attribute, attribute_context)
|
||||
_expect_fields(attribute, ("name", "value"), attribute_context)
|
||||
attributes.append((_string(attribute["name"], f"{attribute_context}.name"), _string(attribute["value"], f"{attribute_context}.value")))
|
||||
attribute_names = [name for name, _ in attributes]
|
||||
if len(attribute_names) != len(set(attribute_names)):
|
||||
raise ProtocolError("duplicate_attribute_name", f"{context} has duplicate attribute names")
|
||||
return ComponentSnapshot(
|
||||
logical_key=_string(component["logical_key"], f"{context}.logical_key"),
|
||||
refdes=_string(component["refdes"], f"{context}.refdes"),
|
||||
part_number=_string(component["part_number"], f"{context}.part_number"),
|
||||
units=units,
|
||||
attributes=tuple(attributes),
|
||||
)
|
||||
|
||||
|
||||
def _snapshot_from_data(data: dict[str, Any]) -> DesignSnapshot:
|
||||
if "format_version" not in data:
|
||||
raise ProtocolError("missing_required_field", "snapshot is missing 'format_version'")
|
||||
format_version = _integer(data["format_version"], "snapshot.format_version")
|
||||
if format_version == 1:
|
||||
raise ProtocolError(
|
||||
"legacy_snapshot_missing_origin",
|
||||
"snapshot format version 1 cannot prove unit origin preservation",
|
||||
)
|
||||
if format_version != _SNAPSHOT_FORMAT_VERSION:
|
||||
raise ProtocolError("unsupported_format_version", f"unsupported snapshot format version {format_version}")
|
||||
_expect_fields(data, ("format_version", "project_id", "project_path", "fingerprint", "components"), "snapshot")
|
||||
components = tuple(_component_from_data(component, f"snapshot.components[{index}]") for index, component in enumerate(_array(data["components"], "snapshot.components")))
|
||||
logical_keys = [component.logical_key for component in components]
|
||||
if len(logical_keys) != len(set(logical_keys)):
|
||||
raise ProtocolError("duplicate_logical_key", "snapshot has duplicate logical keys")
|
||||
return DesignSnapshot(
|
||||
format_version=format_version,
|
||||
project_id=_string(data["project_id"], "snapshot.project_id"),
|
||||
project_path=_string(data["project_path"], "snapshot.project_path"),
|
||||
fingerprint=_string(data["fingerprint"], "snapshot.fingerprint"),
|
||||
components=components,
|
||||
)
|
||||
|
||||
|
||||
def load_snapshot(path: Path) -> DesignSnapshot:
|
||||
"""Load a fully validated snapshot with independent origin evidence."""
|
||||
return _snapshot_from_data(_load_json(path, "snapshot"))
|
||||
|
||||
|
||||
def _pin_to_data(pin: PinSnapshot) -> dict[str, object]:
|
||||
if not isinstance(pin, PinSnapshot):
|
||||
raise ProtocolError("wrong_type", "snapshot pins must be PinSnapshot records")
|
||||
return {"number": pin.number, "name": pin.name, "x": str(pin.x), "y": str(pin.y), "net": pin.net}
|
||||
|
||||
|
||||
def _unit_to_data(unit: UnitSnapshot) -> dict[str, object]:
|
||||
if not isinstance(unit, UnitSnapshot):
|
||||
raise ProtocolError("wrong_type", "snapshot units must be UnitSnapshot records")
|
||||
return {
|
||||
"unit_id": unit.unit_id,
|
||||
"sheet": unit.sheet,
|
||||
"symbol": unit.symbol,
|
||||
"origin_x": str(unit.origin_x),
|
||||
"origin_y": str(unit.origin_y),
|
||||
"x": str(unit.x),
|
||||
"y": str(unit.y),
|
||||
"rotation": unit.rotation,
|
||||
"mirrored": unit.mirrored,
|
||||
"pins": [_pin_to_data(pin) for pin in unit.pins],
|
||||
}
|
||||
|
||||
|
||||
def _component_to_data(component: ComponentSnapshot) -> dict[str, object]:
|
||||
if not isinstance(component, ComponentSnapshot):
|
||||
raise ProtocolError("wrong_type", "snapshot components must be ComponentSnapshot records")
|
||||
attributes: list[dict[str, object]] = []
|
||||
for entry in component.attributes:
|
||||
if not isinstance(entry, tuple) or len(entry) != 2:
|
||||
raise ProtocolError("wrong_type", "snapshot attributes must be name/value pairs")
|
||||
attributes.append({"name": entry[0], "value": entry[1]})
|
||||
return {
|
||||
"logical_key": component.logical_key,
|
||||
"refdes": component.refdes,
|
||||
"part_number": component.part_number,
|
||||
"units": [_unit_to_data(unit) for unit in component.units],
|
||||
"attributes": sorted(attributes, key=lambda attribute: str(attribute["name"])),
|
||||
}
|
||||
|
||||
|
||||
def _snapshot_to_data(snapshot: DesignSnapshot) -> dict[str, object]:
|
||||
if not isinstance(snapshot, DesignSnapshot):
|
||||
raise ProtocolError("wrong_type", "snapshot must be a DesignSnapshot")
|
||||
data: dict[str, object] = {
|
||||
"format_version": snapshot.format_version,
|
||||
"project_id": snapshot.project_id,
|
||||
"project_path": snapshot.project_path,
|
||||
"fingerprint": snapshot.fingerprint,
|
||||
"components": [_component_to_data(component) for component in snapshot.components],
|
||||
}
|
||||
_snapshot_from_data(data)
|
||||
return data
|
||||
|
||||
|
||||
def _canonical_json(data: object) -> str:
|
||||
return json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)
|
||||
|
||||
|
||||
def snapshot_fingerprint(snapshot: DesignSnapshot) -> str:
|
||||
"""Hash the complete semantic snapshot except its stored fingerprint."""
|
||||
data = _snapshot_to_data(snapshot)
|
||||
del data["fingerprint"]
|
||||
return hashlib.sha256(_canonical_json(data).encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def atomic_write_text(path: Path, text: str) -> None:
|
||||
"""Atomically publish UTF-8 text after durable staging in the target directory."""
|
||||
normalized = text.replace("\r\n", "\n").replace("\r", "\n")
|
||||
temporary: Path | None = None
|
||||
try:
|
||||
descriptor, temporary_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
|
||||
temporary = Path(temporary_name)
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as handle:
|
||||
handle.write(normalized)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temporary, path)
|
||||
temporary = None
|
||||
finally:
|
||||
if temporary is not None:
|
||||
try:
|
||||
temporary.unlink()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
def write_snapshot(path: Path, snapshot: DesignSnapshot) -> None:
|
||||
"""Write one canonical version-1 snapshot through the atomic mailbox path."""
|
||||
atomic_write_text(path, _canonical_json(_snapshot_to_data(snapshot)) + "\n")
|
||||
|
||||
|
||||
def _command_to_data(command: BridgeCommand) -> dict[str, object]:
|
||||
if not isinstance(command, BridgeCommand):
|
||||
raise ProtocolError("wrong_type", "command must be a BridgeCommand")
|
||||
_integer(command.format_version, "command.format_version")
|
||||
if command.format_version != _MAILBOX_FORMAT_VERSION:
|
||||
raise ProtocolError("unsupported_format_version", f"unsupported command format version {command.format_version}")
|
||||
string_fields = (
|
||||
(command.command_id, "command_id"), (command.action, "action"), (command.job_id, "job_id"),
|
||||
(command.project_id, "project_id"), (command.old_part_number, "old_part_number"),
|
||||
(command.new_part_number, "new_part_number"), (command.expected_fingerprint, "expected_fingerprint"),
|
||||
)
|
||||
for value, name in string_fields:
|
||||
_string(value, f"command.{name}")
|
||||
_integer(command.expected_count, "command.expected_count")
|
||||
if any(not isinstance(key, str) for key in command.expected_logical_keys):
|
||||
raise ProtocolError("wrong_type", "command.expected_logical_keys must contain strings")
|
||||
return {
|
||||
"format_version": command.format_version,
|
||||
"command_id": command.command_id,
|
||||
"action": command.action,
|
||||
"job_id": command.job_id,
|
||||
"project_id": command.project_id,
|
||||
"scope": command.scope.value,
|
||||
"old_part_number": command.old_part_number,
|
||||
"new_part_number": command.new_part_number,
|
||||
"expected_logical_keys": list(command.expected_logical_keys),
|
||||
"expected_count": command.expected_count,
|
||||
"expected_fingerprint": command.expected_fingerprint,
|
||||
}
|
||||
|
||||
|
||||
def write_command(path: Path, command: BridgeCommand) -> None:
|
||||
"""Publish an apply command atomically in canonical JSON."""
|
||||
atomic_write_text(path, _canonical_json(_command_to_data(command)) + "\n")
|
||||
|
||||
|
||||
def load_status(path: Path) -> BridgeStatus:
|
||||
"""Load a fully validated version-1 bridge status document."""
|
||||
data = _load_json(path, "status")
|
||||
_expect_fields(
|
||||
data,
|
||||
("format_version", "command_id", "project_id", "state", "snapshot_path", "error_code", "error_message", "details"),
|
||||
"status",
|
||||
)
|
||||
format_version = _integer(data["format_version"], "status.format_version")
|
||||
if format_version != _MAILBOX_FORMAT_VERSION:
|
||||
raise ProtocolError("unsupported_format_version", f"unsupported status format version {format_version}")
|
||||
details: list[tuple[str, str]] = []
|
||||
for index, entry in enumerate(_array(data["details"], "status.details")):
|
||||
if not isinstance(entry, list) or len(entry) != 2:
|
||||
raise ProtocolError("wrong_type", f"status.details[{index}] must be a pair")
|
||||
details.append((_string(entry[0], f"status.details[{index}][0]"), _string(entry[1], f"status.details[{index}][1]")))
|
||||
detail_names = [name for name, _ in details]
|
||||
if len(detail_names) != len(set(detail_names)):
|
||||
raise ProtocolError("duplicate_detail_name", "status has duplicate detail names")
|
||||
return BridgeStatus(
|
||||
format_version,
|
||||
_string(data["command_id"], "status.command_id"),
|
||||
_string(data["project_id"], "status.project_id"),
|
||||
_string(data["state"], "status.state"),
|
||||
_optional_string(data["snapshot_path"], "status.snapshot_path"),
|
||||
_optional_string(data["error_code"], "status.error_code"),
|
||||
_optional_string(data["error_message"], "status.error_message"),
|
||||
tuple(details),
|
||||
)
|
||||
@@ -0,0 +1,217 @@
|
||||
"""Passive, deterministic operator reports for part-replacement batches."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from html import escape
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
from .certification import Certification
|
||||
from .models import ExternalChecks, ImpactCell, Issue, ProjectState, VerificationResult
|
||||
from .protocol import atomic_write_text
|
||||
|
||||
|
||||
_REMOTE_URL = re.compile(r"(?i)\b(?:https?|ftp)://[^\s\"'<>]+")
|
||||
_HARD_SEVERITIES = frozenset({"blocking", "error", "fatal", "hard"})
|
||||
|
||||
|
||||
def _pairs(value: Mapping[str, object] | Sequence[tuple[str, object]]) -> tuple[tuple[str, object], ...]:
|
||||
entries = value.items() if isinstance(value, Mapping) else value
|
||||
return tuple(sorted(((str(key), item) for key, item in entries), key=lambda entry: entry[0]))
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class BatchReport:
|
||||
"""Immutable report inputs projected from signed-off records and event state."""
|
||||
|
||||
job_id: str
|
||||
generated_time: str
|
||||
input_hashes: Mapping[str, str] | Sequence[tuple[str, str]] = ()
|
||||
project_states: Mapping[str, ProjectState] | Sequence[tuple[str, ProjectState]] = ()
|
||||
impact_cells: Sequence[ImpactCell] = ()
|
||||
verification_results: Sequence[VerificationResult] = ()
|
||||
external_checks: Mapping[str, ExternalChecks] | Sequence[tuple[str, ExternalChecks]] = ()
|
||||
certifications: Sequence[Certification] = ()
|
||||
backup_path: str | None = None
|
||||
resume_action: str | None = None
|
||||
advisory_attachments: Sequence[str] = ()
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "input_hashes", tuple((key, str(value)) for key, value in _pairs(self.input_hashes)))
|
||||
object.__setattr__(
|
||||
self,
|
||||
"project_states",
|
||||
tuple((key, ProjectState(value)) for key, value in _pairs(self.project_states)),
|
||||
)
|
||||
object.__setattr__(self, "impact_cells", tuple(self.impact_cells))
|
||||
object.__setattr__(self, "verification_results", tuple(self.verification_results))
|
||||
object.__setattr__(self, "external_checks", tuple(_pairs(self.external_checks)))
|
||||
object.__setattr__(self, "certifications", tuple(self.certifications))
|
||||
object.__setattr__(self, "advisory_attachments", tuple(str(item) for item in self.advisory_attachments))
|
||||
|
||||
|
||||
def _canonical_json(value: object) -> str:
|
||||
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)
|
||||
|
||||
|
||||
def _issue_data(issue: Issue) -> dict[str, object]:
|
||||
return {
|
||||
"code": issue.code,
|
||||
"details": dict(sorted(issue.details)),
|
||||
"message": issue.message,
|
||||
"severity": issue.severity,
|
||||
}
|
||||
|
||||
|
||||
def _is_hard(issue: Issue) -> bool:
|
||||
return issue.severity.casefold() in _HARD_SEVERITIES
|
||||
|
||||
|
||||
def _result_data(result: VerificationResult) -> dict[str, object]:
|
||||
hard_issues = [_issue_data(issue) for issue in result.issues if _is_hard(issue)]
|
||||
nonblocking = [_issue_data(issue) for issue in result.issues if not _is_hard(issue)]
|
||||
return {
|
||||
"changed_logical_keys": list(result.changed_logical_keys),
|
||||
"expected_logical_keys": list(result.expected_logical_keys),
|
||||
"hard_issues": hard_issues,
|
||||
"new_part_number": result.rule.new_part_number,
|
||||
"nonblocking_differences": nonblocking,
|
||||
"old_part_number": result.rule.old_part_number,
|
||||
"passed": result.passed,
|
||||
"project_id": result.project_id,
|
||||
}
|
||||
|
||||
|
||||
def _result_key(result: VerificationResult) -> tuple[str, str, str]:
|
||||
return result.project_id, result.rule.old_part_number, result.rule.new_part_number
|
||||
|
||||
|
||||
def write_impact_csv(path: Path, cells: Sequence[ImpactCell]) -> None:
|
||||
"""Write the project-by-mapping impact matrix as a deterministic CSV file."""
|
||||
stream = io.StringIO(newline="")
|
||||
writer = csv.DictWriter(
|
||||
stream,
|
||||
fieldnames=("project_id", "old_part_number", "new_part_number", "logical_count", "unit_count", "issues"),
|
||||
lineterminator="\n",
|
||||
)
|
||||
writer.writeheader()
|
||||
for cell in sorted(cells, key=lambda item: (item.project_id, item.rule.old_part_number, item.rule.new_part_number)):
|
||||
writer.writerow(
|
||||
{
|
||||
"project_id": cell.project_id,
|
||||
"old_part_number": cell.rule.old_part_number,
|
||||
"new_part_number": cell.rule.new_part_number,
|
||||
"logical_count": cell.logical_count,
|
||||
"unit_count": cell.unit_count,
|
||||
"issues": "; ".join(f"{issue.code}: {issue.message}" for issue in cell.issues),
|
||||
}
|
||||
)
|
||||
atomic_write_text(path, stream.getvalue())
|
||||
|
||||
|
||||
def write_differences_json(path: Path, results: Sequence[VerificationResult]) -> None:
|
||||
"""Write hard verification issues and advisory differences in canonical JSON."""
|
||||
data = {"results": [_result_data(result) for result in sorted(results, key=_result_key)]}
|
||||
atomic_write_text(path, _canonical_json(data) + "\n")
|
||||
|
||||
|
||||
def _safe_text(value: object) -> str:
|
||||
"""Escape display text and remove URL-like content from static local reports."""
|
||||
return escape(_REMOTE_URL.sub("", str(value)), quote=True)
|
||||
|
||||
|
||||
def _status(report: BatchReport) -> str:
|
||||
states = tuple(state for _, state in report.project_states)
|
||||
if states and all(state is ProjectState.VERIFIED_SAVED for state in states):
|
||||
return "SUCCESS"
|
||||
if any(state is ProjectState.VERIFIED_SAVED for state in states):
|
||||
return "PARTIAL"
|
||||
if any(state is ProjectState.BLOCKED for state in states):
|
||||
return "BLOCKED"
|
||||
return "IN PROGRESS"
|
||||
|
||||
|
||||
def _table(headers: Sequence[str], rows: Sequence[Sequence[object]]) -> str:
|
||||
header_html = "".join(f"<th>{_safe_text(header)}</th>" for header in headers)
|
||||
row_html = "".join(
|
||||
"<tr>" + "".join(f"<td>{_safe_text(value)}</td>" for value in row) + "</tr>"
|
||||
for row in rows
|
||||
)
|
||||
return f"<table><thead><tr>{header_html}</tr></thead><tbody>{row_html}</tbody></table>"
|
||||
|
||||
|
||||
def _check_text(name: str, value: bool | None) -> str:
|
||||
outcome = "PASS" if value is True else "FAIL" if value is False else "NOT RUN"
|
||||
return f"{name}: {outcome}"
|
||||
|
||||
|
||||
def write_summary_html(path: Path, report: BatchReport) -> None:
|
||||
"""Write an escaped, offline-only HTML projection of immutable batch evidence."""
|
||||
state_rows = [(project_id, state.value.upper()) for project_id, state in report.project_states]
|
||||
impact_rows = [
|
||||
(cell.project_id, cell.rule.old_part_number, cell.rule.new_part_number, cell.logical_count, cell.unit_count)
|
||||
for cell in sorted(report.impact_cells, key=lambda item: (item.project_id, item.rule.old_part_number, item.rule.new_part_number))
|
||||
]
|
||||
hard_rows: list[tuple[object, ...]] = []
|
||||
advisory_rows: list[tuple[object, ...]] = []
|
||||
for cell in sorted(report.impact_cells, key=lambda item: (item.project_id, item.rule.old_part_number, item.rule.new_part_number)):
|
||||
for issue in cell.issues:
|
||||
if _is_hard(issue):
|
||||
hard_rows.append(
|
||||
(cell.project_id, cell.rule.old_part_number, cell.rule.new_part_number, issue.code, issue.message)
|
||||
)
|
||||
for result in sorted(report.verification_results, key=_result_key):
|
||||
for issue in result.issues:
|
||||
row = (result.project_id, result.rule.old_part_number, result.rule.new_part_number, issue.code, issue.message)
|
||||
(hard_rows if _is_hard(issue) else advisory_rows).append(row)
|
||||
hard_rows.sort()
|
||||
check_rows = [
|
||||
(project_id, _check_text("packager", checks.packager), _check_text("erc", checks.erc), _check_text("netlist", checks.netlist))
|
||||
for project_id, checks in report.external_checks
|
||||
]
|
||||
certification_rows = [
|
||||
(
|
||||
certification.rule.old_part_number,
|
||||
certification.rule.new_part_number,
|
||||
certification.target_fingerprint,
|
||||
certification.library_identity or "not recorded",
|
||||
certification.created_utc,
|
||||
)
|
||||
for certification in sorted(
|
||||
report.certifications,
|
||||
key=lambda item: (item.rule.old_part_number, item.rule.new_part_number, item.target_fingerprint),
|
||||
)
|
||||
]
|
||||
attachments = "".join(f"<li>{_safe_text(item)}</li>" for item in report.advisory_attachments) or "<li>None</li>"
|
||||
document = """<!doctype html>
|
||||
<html lang="en"><head><meta charset="utf-8"><title>Part replacement batch report</title>
|
||||
<style>body{font-family:Arial,sans-serif;margin:2rem;color:#1d2731;background:#fff}h1,h2{margin:1.25rem 0 .5rem}table{border-collapse:collapse;width:100%;margin:.5rem 0 1.25rem}th,td{border:1px solid #aab4bd;padding:.45rem;text-align:left;vertical-align:top}th{background:#e9eff3}code{font-family:Consolas,monospace}p{margin:.4rem 0}.status{font-weight:bold}</style>
|
||||
</head><body>"""
|
||||
document += f"<h1>BATCH STATUS: {_safe_text(_status(report))}</h1>"
|
||||
document += f"<p>Job ID: <code>{_safe_text(report.job_id)}</code></p>"
|
||||
document += f"<p>Generated time: {_safe_text(report.generated_time)}</p>"
|
||||
document += "<h2>Input hashes</h2>" + _table(("Input", "Hash"), report.input_hashes)
|
||||
document += "<h2>Project states</h2>" + _table(("Project", "State"), state_rows)
|
||||
document += "<h2>Project-by-mapping impact</h2>" + _table(
|
||||
("Project", "Old part number", "New part number", "Logical components", "Placed units"), impact_rows
|
||||
)
|
||||
document += "<h2>Hard issues</h2>" + _table(
|
||||
("Project", "Old part number", "New part number", "Code", "Message"), hard_rows
|
||||
)
|
||||
document += "<h2>Nonblocking attribute differences</h2>" + _table(
|
||||
("Project", "Old part number", "New part number", "Code", "Message"), advisory_rows
|
||||
)
|
||||
document += "<h2>External checks</h2>" + _table(("Project", "Packager", "ERC", "Netlist"), check_rows)
|
||||
document += "<h2>Certification identity</h2>" + _table(
|
||||
("Old part number", "New part number", "Target fingerprint", "Library identity", "Created"), certification_rows
|
||||
)
|
||||
document += f"<h2>Backup path</h2><p>{_safe_text(report.backup_path or 'Not recorded')}</p>"
|
||||
document += f"<h2>Resume action</h2><p>{_safe_text(report.resume_action or 'No resume action recorded.')}</p>"
|
||||
document += f"<h2>Advisory attachments</h2><ul>{attachments}</ul>"
|
||||
document += "</body></html>\n"
|
||||
atomic_write_text(path, document)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,331 @@
|
||||
"""Deterministic impact analysis and fail-closed replacement verification."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable, Sequence
|
||||
from decimal import Decimal, InvalidOperation
|
||||
|
||||
from .models import ComponentSnapshot, DesignSnapshot, ImpactCell, Issue, MappingRule, UnitSnapshot, VerificationResult
|
||||
|
||||
|
||||
_DEFAULT_TOLERANCE = Decimal("0.000001")
|
||||
|
||||
|
||||
def _part_identity(value: str) -> str:
|
||||
return value.strip().casefold()
|
||||
|
||||
|
||||
def _issue(code: str, message: str, *, severity: str = "error", **details: object) -> Issue:
|
||||
return Issue(code, severity, message, tuple((name, str(value)) for name, value in details.items()))
|
||||
|
||||
|
||||
def _component_index(snapshot: DesignSnapshot) -> tuple[dict[str, ComponentSnapshot], tuple[Issue, ...]]:
|
||||
index: dict[str, ComponentSnapshot] = {}
|
||||
issues: list[Issue] = []
|
||||
for component in snapshot.components:
|
||||
if component.logical_key in index:
|
||||
issues.append(_issue(
|
||||
"duplicate_logical_key",
|
||||
"Snapshot contains a duplicate logical component identity.",
|
||||
logical_key=component.logical_key,
|
||||
))
|
||||
continue
|
||||
index[component.logical_key] = component
|
||||
issues.extend(_component_structure_issues(component))
|
||||
return index, tuple(issues)
|
||||
|
||||
|
||||
def _component_structure_issues(component: ComponentSnapshot) -> tuple[Issue, ...]:
|
||||
issues: list[Issue] = []
|
||||
units: set[str] = set()
|
||||
for unit in component.units:
|
||||
if unit.unit_id in units:
|
||||
issues.append(_issue(
|
||||
"duplicate_unit_id",
|
||||
"Component contains a duplicate unit identity.",
|
||||
logical_key=component.logical_key,
|
||||
unit_id=unit.unit_id,
|
||||
))
|
||||
continue
|
||||
units.add(unit.unit_id)
|
||||
pins: set[str] = set()
|
||||
for pin in unit.pins:
|
||||
if pin.number in pins:
|
||||
issues.append(_issue(
|
||||
"duplicate_pin_number",
|
||||
"Unit contains a duplicate pin number.",
|
||||
logical_key=component.logical_key,
|
||||
unit_id=unit.unit_id,
|
||||
pin_number=pin.number,
|
||||
))
|
||||
pins.add(pin.number)
|
||||
return tuple(issues)
|
||||
|
||||
|
||||
def _component_evidence_issues(component: ComponentSnapshot) -> tuple[Issue, ...]:
|
||||
issues: list[Issue] = []
|
||||
if not component.units:
|
||||
return (_issue(
|
||||
"missing_units",
|
||||
"Matched component has no observed unit or gate evidence.",
|
||||
logical_key=component.logical_key,
|
||||
),)
|
||||
for unit in component.units:
|
||||
if not unit.pins:
|
||||
issues.append(_issue(
|
||||
"missing_pins",
|
||||
"Matched component unit has no observed pin evidence.",
|
||||
logical_key=component.logical_key,
|
||||
unit_id=unit.unit_id,
|
||||
))
|
||||
continue
|
||||
for pin in unit.pins:
|
||||
if not isinstance(pin.net, str) or not pin.net.strip():
|
||||
issues.append(_issue(
|
||||
"missing_network_identity",
|
||||
"Matched component pin has no observed network identity.",
|
||||
logical_key=component.logical_key,
|
||||
unit_id=unit.unit_id,
|
||||
pin_number=pin.number,
|
||||
))
|
||||
return tuple(issues)
|
||||
|
||||
|
||||
def _snapshot_ambiguity_issues(snapshot: DesignSnapshot) -> tuple[Issue, ...]:
|
||||
_, issues = _component_index(snapshot)
|
||||
result = list(issues)
|
||||
refdes_keys: dict[str, str] = {}
|
||||
for component in snapshot.components:
|
||||
refdes_key = component.refdes.strip().casefold()
|
||||
previous_key = refdes_keys.get(refdes_key)
|
||||
if previous_key is not None and previous_key != component.logical_key:
|
||||
result.append(_issue(
|
||||
"duplicate_refdes",
|
||||
"Snapshot contains a duplicate reference designator.",
|
||||
refdes=component.refdes,
|
||||
))
|
||||
else:
|
||||
refdes_keys[refdes_key] = component.logical_key
|
||||
return tuple(result)
|
||||
|
||||
|
||||
def _valid_rule(rule: MappingRule) -> bool:
|
||||
return bool(_part_identity(rule.old_part_number)) and bool(_part_identity(rule.new_part_number))
|
||||
|
||||
|
||||
def eligible_logical_keys(snapshot: DesignSnapshot, rule: MappingRule) -> tuple[str, ...]:
|
||||
"""Return matching component identities in the snapshot's original order.
|
||||
|
||||
Directly-constructed ambiguous snapshots are ineligible. Protocol-loaded
|
||||
snapshots already reject these shapes, but a verifier must not trust callers.
|
||||
"""
|
||||
if _snapshot_ambiguity_issues(snapshot) or not _valid_rule(rule):
|
||||
return ()
|
||||
old_part = _part_identity(rule.old_part_number)
|
||||
return tuple(
|
||||
component.logical_key
|
||||
for component in snapshot.components
|
||||
if _part_identity(component.part_number) == old_part
|
||||
)
|
||||
|
||||
|
||||
def build_impact_matrix(snapshots: Iterable[DesignSnapshot], rules: Sequence[MappingRule]) -> tuple[ImpactCell, ...]:
|
||||
"""Build project-by-rule impact cells without changing source snapshots."""
|
||||
cells: list[ImpactCell] = []
|
||||
for snapshot in snapshots:
|
||||
snapshot_issues = _snapshot_ambiguity_issues(snapshot)
|
||||
for rule in rules:
|
||||
rule_issues = () if _valid_rule(rule) else (
|
||||
_issue("invalid_mapping_rule", "Mapping rule has a blank Part Number."),
|
||||
)
|
||||
keys = () if snapshot_issues or rule_issues else eligible_logical_keys(snapshot, rule)
|
||||
components = {component.logical_key: component for component in snapshot.components}
|
||||
matches = tuple(components[key] for key in keys)
|
||||
evidence_issues = tuple(issue for component in matches for issue in _component_evidence_issues(component))
|
||||
cells.append(ImpactCell(
|
||||
project_id=snapshot.project_id,
|
||||
rule=rule,
|
||||
logical_count=len(matches),
|
||||
unit_count=sum(len(component.units) for component in matches),
|
||||
issues=snapshot_issues + rule_issues + evidence_issues,
|
||||
))
|
||||
return tuple(cells)
|
||||
|
||||
|
||||
def _tolerance_issue(coordinate_tolerance: Decimal) -> Issue | None:
|
||||
try:
|
||||
tolerance = Decimal(str(coordinate_tolerance))
|
||||
except (InvalidOperation, ValueError):
|
||||
return _issue("invalid_coordinate_tolerance", "Coordinate tolerance is not a finite Decimal.")
|
||||
if not tolerance.is_finite() or tolerance < 0:
|
||||
return _issue("invalid_coordinate_tolerance", "Coordinate tolerance must be a non-negative finite Decimal.")
|
||||
return None
|
||||
|
||||
|
||||
def _within_tolerance(before: Decimal, after: Decimal, tolerance: Decimal) -> bool:
|
||||
return before.is_finite() and after.is_finite() and abs(before - after) <= tolerance
|
||||
|
||||
|
||||
def _changed(before: ComponentSnapshot, after: ComponentSnapshot) -> bool:
|
||||
return before != after
|
||||
|
||||
|
||||
def _compare_unit(
|
||||
logical_key: str,
|
||||
before: UnitSnapshot,
|
||||
after: UnitSnapshot,
|
||||
tolerance: Decimal,
|
||||
) -> tuple[Issue, ...]:
|
||||
issues: list[Issue] = []
|
||||
if before.sheet != after.sheet:
|
||||
issues.append(_issue("sheet_changed", "Component unit moved to a different sheet.", logical_key=logical_key, unit_id=before.unit_id))
|
||||
if not (
|
||||
_within_tolerance(before.origin_x, after.origin_x, tolerance)
|
||||
and _within_tolerance(before.origin_y, after.origin_y, tolerance)
|
||||
):
|
||||
issues.append(
|
||||
_issue(
|
||||
"origin_changed",
|
||||
"Component unit origin changed.",
|
||||
logical_key=logical_key,
|
||||
unit_id=before.unit_id,
|
||||
)
|
||||
)
|
||||
if not (_within_tolerance(before.x, after.x, tolerance) and _within_tolerance(before.y, after.y, tolerance)):
|
||||
issues.append(_issue("placement_changed", "Component placement changed.", logical_key=logical_key, unit_id=before.unit_id))
|
||||
if before.rotation != after.rotation:
|
||||
issues.append(_issue("rotation_changed", "Component rotation changed.", logical_key=logical_key, unit_id=before.unit_id))
|
||||
if before.mirrored != after.mirrored:
|
||||
issues.append(_issue("mirror_changed", "Component mirror state changed.", logical_key=logical_key, unit_id=before.unit_id))
|
||||
if before.symbol != after.symbol:
|
||||
issues.append(_issue(
|
||||
"library_symbol_changed",
|
||||
"Library-controlled symbol identity changed.",
|
||||
severity="info",
|
||||
logical_key=logical_key,
|
||||
unit_id=before.unit_id,
|
||||
))
|
||||
|
||||
before_pins = {pin.number: pin for pin in before.pins}
|
||||
after_pins = {pin.number: pin for pin in after.pins}
|
||||
if before_pins.keys() != after_pins.keys():
|
||||
issues.append(_issue("pin_set_changed", "Component pin-number set changed.", logical_key=logical_key, unit_id=before.unit_id))
|
||||
return tuple(issues)
|
||||
for number, before_pin in before_pins.items():
|
||||
after_pin = after_pins[number]
|
||||
if not (_within_tolerance(before_pin.x, after_pin.x, tolerance) and _within_tolerance(before_pin.y, after_pin.y, tolerance)):
|
||||
issues.append(_issue("pin_position_changed", "Pin position changed.", logical_key=logical_key, unit_id=before.unit_id, pin_number=number))
|
||||
if before_pin.net != after_pin.net:
|
||||
issues.append(_issue("connectivity_changed", "Pin net identity changed.", logical_key=logical_key, unit_id=before.unit_id, pin_number=number))
|
||||
if before_pin.name != after_pin.name:
|
||||
issues.append(_issue(
|
||||
"library_pin_name_changed",
|
||||
"Library-controlled pin name changed.",
|
||||
severity="info",
|
||||
logical_key=logical_key,
|
||||
unit_id=before.unit_id,
|
||||
pin_number=number,
|
||||
))
|
||||
return tuple(issues)
|
||||
|
||||
|
||||
def _compare_expected_component(
|
||||
before: ComponentSnapshot,
|
||||
after: ComponentSnapshot,
|
||||
rule: MappingRule,
|
||||
tolerance: Decimal,
|
||||
) -> tuple[Issue, ...]:
|
||||
issues = list(_component_evidence_issues(before))
|
||||
issues.extend(_component_evidence_issues(after))
|
||||
if _part_identity(before.part_number) != _part_identity(rule.old_part_number):
|
||||
issues.append(_issue("source_part_number_mismatch", "Expected component does not have the rule source Part Number.", logical_key=before.logical_key))
|
||||
if _part_identity(after.part_number) != _part_identity(rule.new_part_number):
|
||||
issues.append(_issue("wrong_target_part_number", "Replaced component does not have the requested target Part Number.", logical_key=before.logical_key, actual=after.part_number, expected=rule.new_part_number))
|
||||
if before.refdes != after.refdes:
|
||||
issues.append(_issue("refdes_changed", "Component reference designator changed.", logical_key=before.logical_key))
|
||||
|
||||
before_units = {unit.unit_id: unit for unit in before.units}
|
||||
after_units = {unit.unit_id: unit for unit in after.units}
|
||||
if before_units.keys() != after_units.keys():
|
||||
issues.append(_issue("unit_set_changed", "Component gate or slot set changed.", logical_key=before.logical_key))
|
||||
return tuple(issues)
|
||||
for unit_id, before_unit in before_units.items():
|
||||
issues.extend(_compare_unit(before.logical_key, before_unit, after_units[unit_id], tolerance))
|
||||
if before.attributes != after.attributes:
|
||||
issues.append(_issue(
|
||||
"library_attribute_changed",
|
||||
"Library-controlled component attributes changed.",
|
||||
severity="info",
|
||||
logical_key=before.logical_key,
|
||||
))
|
||||
return tuple(issues)
|
||||
|
||||
|
||||
def verify_replacement(
|
||||
before: DesignSnapshot,
|
||||
after: DesignSnapshot,
|
||||
rule: MappingRule,
|
||||
expected_logical_keys: Sequence[str],
|
||||
coordinate_tolerance: Decimal = _DEFAULT_TOLERANCE,
|
||||
) -> VerificationResult:
|
||||
"""Verify that only the selected components changed under Library Wins rules."""
|
||||
issues: list[Issue] = []
|
||||
tolerance_error = _tolerance_issue(coordinate_tolerance)
|
||||
if tolerance_error is not None:
|
||||
issues.append(tolerance_error)
|
||||
tolerance = _DEFAULT_TOLERANCE
|
||||
else:
|
||||
tolerance = Decimal(str(coordinate_tolerance))
|
||||
|
||||
if not _valid_rule(rule):
|
||||
issues.append(_issue("invalid_mapping_rule", "Mapping rule has a blank Part Number."))
|
||||
if before.project_id != after.project_id:
|
||||
issues.append(_issue("project_id_changed", "Project identity changed between snapshots.", before=before.project_id, after=after.project_id))
|
||||
if before.project_path != after.project_path:
|
||||
issues.append(_issue("project_path_changed", "Project path changed between snapshots.", before=before.project_path, after=after.project_path))
|
||||
|
||||
before_index, _ = _component_index(before)
|
||||
after_index, _ = _component_index(after)
|
||||
issues.extend(_snapshot_ambiguity_issues(before))
|
||||
issues.extend(_snapshot_ambiguity_issues(after))
|
||||
|
||||
before_keys = set(before_index)
|
||||
after_keys = set(after_index)
|
||||
if len(before.components) != len(after.components):
|
||||
issues.append(_issue("component_count_changed", "Logical component count changed.", before=len(before.components), after=len(after.components)))
|
||||
for component in before.components:
|
||||
if component.logical_key not in after_keys:
|
||||
issues.append(_issue("component_removed", "Logical component was removed.", logical_key=component.logical_key))
|
||||
for component in after.components:
|
||||
if component.logical_key not in before_keys:
|
||||
issues.append(_issue("component_added", "Unexpected logical component was added.", logical_key=component.logical_key))
|
||||
|
||||
expected = tuple(expected_logical_keys)
|
||||
expected_set = set(expected)
|
||||
if len(expected) != len(expected_set):
|
||||
issues.append(_issue("duplicate_expected_logical_key", "Expected logical-component keys are not unique."))
|
||||
|
||||
for logical_key in expected:
|
||||
if logical_key not in before_index or logical_key not in after_index:
|
||||
issues.append(_issue("expected_logical_key_missing", "Expected logical component is missing from a snapshot.", logical_key=logical_key))
|
||||
continue
|
||||
issues.extend(_compare_expected_component(before_index[logical_key], after_index[logical_key], rule, tolerance))
|
||||
|
||||
changed_keys: list[str] = []
|
||||
for component in before.components:
|
||||
logical_key = component.logical_key
|
||||
if logical_key in after_index and _changed(component, after_index[logical_key]):
|
||||
if logical_key not in changed_keys:
|
||||
changed_keys.append(logical_key)
|
||||
if logical_key not in expected_set:
|
||||
issues.append(_issue("unexpected_changed_logical_key", "An unselected logical component changed.", logical_key=logical_key))
|
||||
issues.append(_issue("unrelated_component_changed", "An unrelated logical component changed.", logical_key=logical_key))
|
||||
|
||||
return VerificationResult(
|
||||
project_id=before.project_id,
|
||||
rule=rule,
|
||||
expected_logical_keys=expected,
|
||||
changed_logical_keys=tuple(changed_keys),
|
||||
issues=tuple(issues),
|
||||
passed=not any(issue.severity == "error" for issue in issues),
|
||||
)
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Qt-free domain and persistence services for the evaluation task center."""
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .models import ProjectRecord, ProjectStatus, RuleRecord, TaskRecord, TaskStatus
|
||||
from .store import TaskStore
|
||||
|
||||
__all__ = [
|
||||
"ProjectRecord",
|
||||
"ProjectStatus",
|
||||
"RuleRecord",
|
||||
"TaskCenterError",
|
||||
"TaskRecord",
|
||||
"TaskStatus",
|
||||
"TaskStore",
|
||||
]
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Desktop application bootstrap for DxDesigner part replacement."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import sys
|
||||
from typing import Sequence
|
||||
|
||||
from PySide6.QtCore import QTimer
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from dx_productivity.trial_task_center.logging_setup import LoggingContext, configure_logging, install_exception_hooks
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.version import VERSION
|
||||
|
||||
|
||||
_DEFAULT_HOME_PARTS = ("DxProductivity", "trial-task-center")
|
||||
|
||||
|
||||
def _load_window():
|
||||
"""Import Qt widgets only after diagnostics are ready for UI construction."""
|
||||
from dx_productivity.trial_task_center.ui import TrialTaskCenterWindow
|
||||
|
||||
return TrialTaskCenterWindow
|
||||
|
||||
|
||||
def _parse_arguments(argv: Sequence[str] | None) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(prog="DxPartReplace")
|
||||
parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS)
|
||||
parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS)
|
||||
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)
|
||||
return parser.parse_args(list(argv) if argv is not None else None)
|
||||
|
||||
|
||||
def _default_data_root() -> Path:
|
||||
if bool(getattr(sys, "frozen", False)):
|
||||
return Path(sys.executable).resolve().parent / "data"
|
||||
local_app_data = os.environ.get("LOCALAPPDATA")
|
||||
if local_app_data:
|
||||
return Path(local_app_data).joinpath(*_DEFAULT_HOME_PARTS)
|
||||
known_folder = _windows_local_app_data()
|
||||
if known_folder is not None:
|
||||
return known_folder.joinpath(*_DEFAULT_HOME_PARTS)
|
||||
return Path.home().joinpath("AppData", "Local", *_DEFAULT_HOME_PARTS)
|
||||
|
||||
|
||||
def _windows_local_app_data() -> Path | None:
|
||||
"""Resolve Local AppData without inheriting the caller's environment."""
|
||||
if os.name != "nt":
|
||||
return None
|
||||
import ctypes
|
||||
|
||||
buffer = ctypes.create_unicode_buffer(32_768)
|
||||
result = ctypes.windll.shell32.SHGetFolderPathW(None, 0x001C, None, 0, buffer)
|
||||
return Path(buffer.value) if result == 0 and buffer.value else None
|
||||
|
||||
|
||||
def resolve_data_root(cli_value: Path | None) -> Path:
|
||||
"""Choose the explicit command-line override, deployment override, or user default."""
|
||||
if cli_value is not None:
|
||||
return cli_value.expanduser().resolve()
|
||||
deployment_override = os.environ.get("DX_TASK_CENTER_HOME")
|
||||
if deployment_override:
|
||||
return Path(deployment_override).expanduser().resolve()
|
||||
return _default_data_root().resolve()
|
||||
|
||||
|
||||
def _log_startup(context: LoggingContext, data_root: Path, database_path: Path) -> None:
|
||||
context.logger.info(
|
||||
"application_start version=%s executable=%s os=%s data_root=%s database=%s application_log=%s",
|
||||
VERSION,
|
||||
sys.executable,
|
||||
platform.platform(),
|
||||
data_root,
|
||||
database_path,
|
||||
context.application_log_path,
|
||||
)
|
||||
|
||||
|
||||
def _flush(context: LoggingContext) -> None:
|
||||
for handler in context.logger.handlers:
|
||||
handler.flush()
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
"""Run the Qt shell, returning a conventional process status code."""
|
||||
arguments = _parse_arguments(argv)
|
||||
if arguments.native_helper:
|
||||
if arguments.snapshot is None:
|
||||
return 2
|
||||
from dx_productivity.trial_task_center.native_helper import run
|
||||
|
||||
return run(arguments.snapshot)
|
||||
data_root = resolve_data_root(arguments.data_root)
|
||||
if arguments.sceneos_cli:
|
||||
from dx_productivity.trial_task_center.sceneos_cli import run
|
||||
|
||||
return run(data_root)
|
||||
logging_context = configure_logging(data_root)
|
||||
install_exception_hooks(logging_context)
|
||||
store: TaskStore | None = None
|
||||
try:
|
||||
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)
|
||||
window.show()
|
||||
if arguments.smoke_test:
|
||||
QTimer.singleShot(0, lambda: (window.close(), qt_application.quit()))
|
||||
exit_code = qt_application.exec()
|
||||
logging_context.logger.info("application_clean_shutdown exit_code=%s", exit_code)
|
||||
_flush(logging_context)
|
||||
return int(exit_code)
|
||||
except Exception as error:
|
||||
logging_context.report_exception("startup", error)
|
||||
return 1
|
||||
finally:
|
||||
if store is not None:
|
||||
store.close()
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover - exercised by the frozen executable.
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,400 @@
|
||||
"""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
|
||||
from .models import TaskStatus
|
||||
from .quick_run import (
|
||||
BATCH_FAILED_STATE,
|
||||
BATCH_SAVED_UNVERIFIED_STATE,
|
||||
TERMINAL_STATES,
|
||||
QuickRunProgress,
|
||||
QuickRunStepResult,
|
||||
_path_key,
|
||||
_write_uncertain_flag,
|
||||
)
|
||||
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'
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BatchRunResult:
|
||||
progress: QuickRunProgress
|
||||
paused: bool
|
||||
last_result: QuickRunStepResult | None = None
|
||||
item_messages: tuple[str, ...] = ()
|
||||
unbacked_project_paths: tuple[Path, ...] = ()
|
||||
|
||||
|
||||
def execute_batch(
|
||||
service,
|
||||
task_id: str,
|
||||
*,
|
||||
expected_item,
|
||||
stop_event: Event,
|
||||
continue_after_backup_failure: bool = False,
|
||||
) -> BatchRunResult:
|
||||
preparer = service._quick_run_preparer
|
||||
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',
|
||||
','.join(retention.removed_entries), retention.removed_bytes,
|
||||
','.join(retention.skipped_entries),
|
||||
)
|
||||
task = service._store.get_task(task_id)
|
||||
projects = service._store.list_projects(task_id)
|
||||
rules = service._store.list_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)
|
||||
if progress.queue_complete:
|
||||
progress = service._synchronize_quick_run_progress(task_id, progress=progress)
|
||||
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():
|
||||
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,
|
||||
)
|
||||
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')
|
||||
]
|
||||
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
|
||||
|
||||
if session.progress.completed_items > initial_progress.completed_items:
|
||||
discovered_no_match = session.progress.completed_items - initial_progress.completed_items
|
||||
progress = service._synchronize_quick_run_progress(task_id, progress=session.progress)
|
||||
session.progress = progress
|
||||
append_task_event(
|
||||
service._logging,
|
||||
level='INFO',
|
||||
task_id=task_id,
|
||||
operation='quick_run_inventory_prefiltered',
|
||||
message=f'只读枚举确认 {discovered_no_match} 项未命中,已跳过重复打开工程。',
|
||||
details={
|
||||
'state': 'no_match',
|
||||
'prefiltered_items': discovered_no_match,
|
||||
'completed_items': progress.completed_items,
|
||||
'total_items': progress.total_items,
|
||||
'completed_projects': len(progress.completed_project_paths),
|
||||
},
|
||||
)
|
||||
service._logging.logger.info(
|
||||
'quick_run_inventory_prefiltered task_id=%s items=%s total=%s',
|
||||
task_id,
|
||||
discovered_no_match,
|
||||
progress.total_items,
|
||||
)
|
||||
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:
|
||||
while not progress.queue_complete:
|
||||
if stop_event.is_set():
|
||||
commit_prefetched_backup()
|
||||
return BatchRunResult(
|
||||
progress, True, last_result, tuple(item_messages), tuple(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)
|
||||
service._batch_feedback = (task_id, progress, f'正在处理 {current.name}')
|
||||
if stop_event.is_set():
|
||||
commit_prefetched_backup()
|
||||
return BatchRunResult(
|
||||
progress, True, last_result, tuple(item_messages), tuple(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)
|
||||
if 'NC synced:' in last_result.message or last_result.state in {
|
||||
BATCH_FAILED_STATE,
|
||||
BATCH_SAVED_UNVERIFIED_STATE,
|
||||
}:
|
||||
item_messages.append(last_result.message)
|
||||
if last_result.progress is None:
|
||||
raise TaskCenterError('quick_run_queue_progress', '批量执行器未返回增量进度,队列已停止。')
|
||||
candidate = last_result.progress
|
||||
project_completed = candidate.completed_project_paths != progress.completed_project_paths
|
||||
synchronize = (
|
||||
progress.completed_items == 0
|
||||
or project_completed
|
||||
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 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')
|
||||
raise TaskCenterError('quick_run_queue_progress', '执行器返回后队列进度异常,已停止,避免重复执行。')
|
||||
if project_completed or updated.queue_complete or 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)})
|
||||
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
|
||||
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)
|
||||
)
|
||||
|
||||
|
||||
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):
|
||||
try:
|
||||
_backup_project_root_once(data_root, project_path, destination)
|
||||
return
|
||||
except OSError as error:
|
||||
last_error = error
|
||||
if destination.exists():
|
||||
shutil.rmtree(destination, ignore_errors=True)
|
||||
if attempt < 2:
|
||||
time.sleep(0.4 * (2 ** attempt))
|
||||
except TaskCenterError:
|
||||
if destination.exists():
|
||||
shutil.rmtree(destination, ignore_errors=True)
|
||||
raise
|
||||
assert last_error is not None
|
||||
raise TaskCenterError(
|
||||
'quick_run_backup',
|
||||
f'工程备份失败,未打开工程、枚举图页或执行替换:{project_path};请关闭占用该工程的 DxDesigner 或其他程序后重试;{last_error}',
|
||||
) from last_error
|
||||
|
||||
|
||||
def _backup_project_root_once(data_root: Path, project_path: Path, destination: Path) -> None:
|
||||
create_schematic_backup(data_root, project_path, destination)
|
||||
@@ -0,0 +1,365 @@
|
||||
"""Fail-closed comparison of before/after menu-probe profiles."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import math
|
||||
from types import MappingProxyType
|
||||
from typing import Any
|
||||
|
||||
from dx_productivity.part_replace.models import MappingRule
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ComparisonIssue:
|
||||
code: str
|
||||
message: str
|
||||
logical_identity: str | None = None
|
||||
|
||||
def to_dict(self) -> dict[str, str | None]:
|
||||
return {
|
||||
"code": self.code,
|
||||
"logical_identity": self.logical_identity,
|
||||
"message": self.message,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ProjectComparison:
|
||||
passed: bool
|
||||
matched_logical_identities: Mapping[MappingRule, tuple[str, ...]]
|
||||
warnings: tuple[ComparisonIssue, ...] = ()
|
||||
issues: tuple[ComparisonIssue, ...] = ()
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "matched_logical_identities", MappingProxyType({
|
||||
rule: tuple(identities)
|
||||
for rule, identities in self.matched_logical_identities.items()
|
||||
}))
|
||||
object.__setattr__(self, "warnings", tuple(self.warnings))
|
||||
object.__setattr__(self, "issues", tuple(self.issues))
|
||||
|
||||
@property
|
||||
def matched(self) -> Mapping[MappingRule, tuple[str, ...]]:
|
||||
return self.matched_logical_identities
|
||||
|
||||
def to_json(self) -> str:
|
||||
matches = [
|
||||
{
|
||||
"logical_identities": list(identities),
|
||||
"new_part_number": rule.new_part_number,
|
||||
"old_part_number": rule.old_part_number,
|
||||
}
|
||||
for rule, identities in sorted(
|
||||
self.matched_logical_identities.items(),
|
||||
key=lambda item: (item[0].old_part_number.casefold(), item[0].new_part_number.casefold()),
|
||||
)
|
||||
]
|
||||
return json.dumps(
|
||||
{
|
||||
"issues": [issue.to_dict() for issue in _ordered_issues(self.issues)],
|
||||
"matches": matches,
|
||||
"passed": self.passed,
|
||||
"warnings": [warning.to_dict() for warning in _ordered_issues(self.warnings)],
|
||||
},
|
||||
ensure_ascii=True,
|
||||
separators=(",", ":"),
|
||||
sort_keys=True,
|
||||
)
|
||||
|
||||
def canonical_json(self) -> str:
|
||||
return self.to_json()
|
||||
|
||||
|
||||
_PROTECTED_INTERFACES = (
|
||||
"logical_identity", "part_number", "refdes", "hierarchy", "units",
|
||||
"origin_x", "origin_y", "position_x", "position_y", "rotation",
|
||||
"mirror", "pins", "nets",
|
||||
)
|
||||
_PROTECTED_FIELDS = (
|
||||
"refdes", "hierarchy", "units", "origin", "position", "rotation", "mirror", "nets",
|
||||
)
|
||||
_REQUIRED_COMPONENT_FIELDS = ("part_number", *_PROTECTED_FIELDS, "pins")
|
||||
_PRESENTATION_FIELDS = ("attributes", "parameter_probe")
|
||||
|
||||
|
||||
def _issue(code: str, message: str, identity: str | None = None) -> ComparisonIssue:
|
||||
return ComparisonIssue(code, message, identity)
|
||||
|
||||
|
||||
def _ordered_issues(issues: Sequence[ComparisonIssue]) -> tuple[ComparisonIssue, ...]:
|
||||
return tuple(sorted(issues, key=lambda issue: (issue.code, issue.logical_identity or "", issue.message)))
|
||||
|
||||
|
||||
def _part_identity(value: object) -> str | None:
|
||||
return value.strip().casefold() if isinstance(value, str) and value.strip() else None
|
||||
|
||||
|
||||
def _available(profile: Mapping[str, object], name: str) -> bool:
|
||||
interfaces = profile.get("interfaces")
|
||||
if not isinstance(interfaces, Mapping):
|
||||
return False
|
||||
entry = interfaces.get(name)
|
||||
return isinstance(entry, Mapping) and entry.get("available") is True
|
||||
|
||||
|
||||
def _components(profile: Mapping[str, object], side: str, issues: list[ComparisonIssue]) -> dict[str, Mapping[str, object]]:
|
||||
entries = profile.get("components")
|
||||
if not isinstance(entries, list):
|
||||
issues.append(_issue("missing_components", f"{side} profile does not contain component evidence."))
|
||||
return {}
|
||||
indexed: dict[str, Mapping[str, object]] = {}
|
||||
for entry in entries:
|
||||
if not isinstance(entry, Mapping):
|
||||
issues.append(_issue("invalid_component", f"{side} profile contains an invalid component record."))
|
||||
continue
|
||||
identity = entry.get("logical_identity")
|
||||
if not isinstance(identity, str) or not identity.strip():
|
||||
issues.append(_issue("missing_logical_identity", f"{side} profile contains a component without a logical identity."))
|
||||
continue
|
||||
if identity in indexed:
|
||||
issues.append(_issue("duplicate_logical_identity", f"{side} profile repeats a logical component identity.", identity))
|
||||
continue
|
||||
indexed[identity] = entry
|
||||
return indexed
|
||||
|
||||
|
||||
def _missing_evidence(component: Mapping[str, object], identity: str, issues: list[ComparisonIssue]) -> None:
|
||||
for field in _REQUIRED_COMPONENT_FIELDS:
|
||||
value = component.get(field)
|
||||
if value is None or (field == "part_number" and _part_identity(value) is None):
|
||||
issues.append(_issue("missing_protected_evidence", f"Protected field {field} is unavailable.", identity))
|
||||
for field in ("origin", "position"):
|
||||
value = component.get(field)
|
||||
if isinstance(value, Mapping) and (value.get("x") is None or value.get("y") is None):
|
||||
issues.append(_issue("missing_protected_evidence", f"Protected field {field} is incomplete.", identity))
|
||||
|
||||
|
||||
def _finite_number(value: object) -> bool:
|
||||
return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)
|
||||
|
||||
|
||||
def _nonempty_string(value: object) -> bool:
|
||||
return isinstance(value, str) and bool(value.strip())
|
||||
|
||||
|
||||
def _valid_point(value: object) -> bool:
|
||||
return isinstance(value, Mapping) and _finite_number(value.get("x")) and _finite_number(value.get("y"))
|
||||
|
||||
|
||||
def _valid_pins(value: object) -> bool:
|
||||
if not isinstance(value, list) or not value:
|
||||
return False
|
||||
numbers: set[str] = set()
|
||||
for pin in value:
|
||||
if not isinstance(pin, Mapping):
|
||||
return False
|
||||
if not _nonempty_string(pin.get("number")) or not _nonempty_string(pin.get("name")):
|
||||
return False
|
||||
if not _nonempty_string(pin.get("net_identity")):
|
||||
return False
|
||||
if not _finite_number(pin.get("x")) or not _finite_number(pin.get("y")):
|
||||
return False
|
||||
number = pin["number"].strip()
|
||||
if number in numbers:
|
||||
return False
|
||||
numbers.add(number)
|
||||
return True
|
||||
|
||||
|
||||
def _valid_component(component: Mapping[str, object]) -> bool:
|
||||
return (
|
||||
_nonempty_string(component.get("logical_identity"))
|
||||
and _nonempty_string(component.get("part_number"))
|
||||
and _nonempty_string(component.get("refdes"))
|
||||
and _nonempty_string(component.get("hierarchy"))
|
||||
and type(component.get("units")) is int
|
||||
and component["units"] > 0
|
||||
and _valid_point(component.get("origin"))
|
||||
and _valid_point(component.get("position"))
|
||||
and type(component.get("rotation")) is int
|
||||
and type(component.get("mirror")) is bool
|
||||
and _valid_pins(component.get("pins"))
|
||||
and isinstance(component.get("nets"), list)
|
||||
and all(_nonempty_string(net) for net in component["nets"])
|
||||
)
|
||||
|
||||
|
||||
def _validate_components(index: Mapping[str, Mapping[str, object]], issues: list[ComparisonIssue]) -> None:
|
||||
for identity, component in index.items():
|
||||
if not _valid_component(component):
|
||||
issues.append(_issue("invalid_protected_evidence", "Component protected evidence has an invalid schema.", identity))
|
||||
|
||||
|
||||
def _validate_enumeration(
|
||||
profile: Mapping[str, object],
|
||||
side: str,
|
||||
record_count: int,
|
||||
issues: list[ComparisonIssue],
|
||||
) -> None:
|
||||
enumeration = profile.get("enumeration")
|
||||
if not isinstance(enumeration, Mapping):
|
||||
issues.append(_issue("enumeration_unavailable", f"{side} profile has no full-project enumeration evidence."))
|
||||
return
|
||||
if enumeration.get("available") is not True:
|
||||
issues.append(_issue("enumeration_unavailable", f"{side} profile cannot enumerate the full project."))
|
||||
count = enumeration.get("component_count")
|
||||
if type(count) is not int or count < 0:
|
||||
issues.append(_issue("enumeration_invalid", f"{side} profile has an invalid component count."))
|
||||
elif count != record_count:
|
||||
issues.append(_issue("component_count_mismatch", f"{side} profile component count disagrees with its records."))
|
||||
if not _nonempty_string(enumeration.get("route")):
|
||||
issues.append(_issue("enumeration_invalid", f"{side} profile has no enumeration route."))
|
||||
|
||||
|
||||
def _pins_by_number(component: Mapping[str, object]) -> dict[str, Mapping[str, object]] | None:
|
||||
pins = component.get("pins")
|
||||
if not _valid_pins(pins):
|
||||
return None
|
||||
assert isinstance(pins, list)
|
||||
return {str(pin["number"]).strip(): pin for pin in pins if isinstance(pin, Mapping)}
|
||||
|
||||
|
||||
def _compare_pins(
|
||||
before: Mapping[str, object],
|
||||
after: Mapping[str, object],
|
||||
identity: str,
|
||||
issues: list[ComparisonIssue],
|
||||
warnings: list[ComparisonIssue],
|
||||
) -> None:
|
||||
before_pins = _pins_by_number(before)
|
||||
after_pins = _pins_by_number(after)
|
||||
if before_pins is None or after_pins is None:
|
||||
return
|
||||
if before_pins.keys() != after_pins.keys():
|
||||
issues.append(_issue("pins_changed", "Protected pin numbers changed.", identity))
|
||||
return
|
||||
hard_fields = ("net_identity", "x", "y")
|
||||
hard_changed = any(
|
||||
any(before_pins[number].get(field) != after_pins[number].get(field) for field in hard_fields)
|
||||
for number in before_pins
|
||||
)
|
||||
if hard_changed:
|
||||
issues.append(_issue("pins_changed", "Protected pin connectivity or coordinates changed.", identity))
|
||||
if any(before_pins[number].get("name") != after_pins[number].get("name") for number in before_pins):
|
||||
warnings.append(_issue("library_pin_name_changed", "Library-controlled pin name changed.", identity))
|
||||
|
||||
|
||||
def _without_presentation(component: Mapping[str, object]) -> dict[str, object]:
|
||||
return {key: value for key, value in component.items() if key not in _PRESENTATION_FIELDS}
|
||||
|
||||
|
||||
def _attribute_values(component: Mapping[str, object]) -> dict[str, object]:
|
||||
attributes = component.get("attributes")
|
||||
if not isinstance(attributes, list):
|
||||
return {}
|
||||
result: dict[str, object] = {}
|
||||
for attribute in attributes:
|
||||
if isinstance(attribute, Mapping) and isinstance(attribute.get("name"), str):
|
||||
result.setdefault(attribute["name"].strip().casefold(), attribute.get("value"))
|
||||
return result
|
||||
|
||||
|
||||
def _presentation_warnings(
|
||||
before: Mapping[str, object], after: Mapping[str, object], identity: str, *, parameter_available: bool
|
||||
) -> tuple[ComparisonIssue, ...]:
|
||||
warnings: list[ComparisonIssue] = []
|
||||
before_attributes = _attribute_values(before)
|
||||
after_attributes = _attribute_values(after)
|
||||
for name, code in (("part label", "part_label_changed"), ("value", "value_changed")):
|
||||
if before_attributes.get(name) != after_attributes.get(name):
|
||||
warnings.append(_issue(code, f"{name.title()} presentation changed.", identity))
|
||||
if parameter_available and before.get("parameter_probe") != after.get("parameter_probe"):
|
||||
warnings.append(_issue("parameter_probe_changed", "Parameter probe evidence changed.", identity))
|
||||
return tuple(warnings)
|
||||
|
||||
|
||||
def compare_profiles(
|
||||
before: Mapping[str, object],
|
||||
after: Mapping[str, object],
|
||||
rules: Sequence[MappingRule],
|
||||
) -> ProjectComparison:
|
||||
"""Compare profiles by logical identity and allow only requested Part Number changes."""
|
||||
issues: list[ComparisonIssue] = []
|
||||
warnings: list[ComparisonIssue] = []
|
||||
before_index = _components(before, "before", issues)
|
||||
after_index = _components(after, "after", issues)
|
||||
|
||||
before_entries = before.get("components")
|
||||
after_entries = after.get("components")
|
||||
_validate_enumeration(before, "before", len(before_entries) if isinstance(before_entries, list) else 0, issues)
|
||||
_validate_enumeration(after, "after", len(after_entries) if isinstance(after_entries, list) else 0, issues)
|
||||
|
||||
for profile, side in ((before, "before"), (after, "after")):
|
||||
for interface in _PROTECTED_INTERFACES:
|
||||
if not _available(profile, interface):
|
||||
issues.append(_issue("protected_interface_unavailable", f"{side} profile does not support {interface}."))
|
||||
if not _available(profile, "parameter_probe"):
|
||||
warnings.append(_issue("parameter_presentation_unavailable", f"{side} profile cannot capture parameter presentation."))
|
||||
|
||||
presentation_available = _available(before, "parameter_probe") and _available(after, "parameter_probe")
|
||||
|
||||
for identity, component in before_index.items():
|
||||
_missing_evidence(component, identity, issues)
|
||||
for identity, component in after_index.items():
|
||||
_missing_evidence(component, identity, issues)
|
||||
_validate_components(before_index, issues)
|
||||
_validate_components(after_index, issues)
|
||||
|
||||
matched: dict[MappingRule, tuple[str, ...]] = {}
|
||||
expected_identities: set[str] = set()
|
||||
for rule in rules:
|
||||
old = _part_identity(rule.old_part_number)
|
||||
target = _part_identity(rule.new_part_number)
|
||||
if old is None or target is None:
|
||||
issues.append(_issue("invalid_mapping_rule", "Mapping rule has a blank Part Number."))
|
||||
matched[rule] = ()
|
||||
continue
|
||||
identities = tuple(sorted(
|
||||
identity for identity, component in before_index.items()
|
||||
if _part_identity(component.get("part_number")) == old
|
||||
))
|
||||
matched[rule] = identities
|
||||
if not identities:
|
||||
warnings.append(_issue("no_matching_source_part", "No component matches the source Part Number."))
|
||||
for identity in identities:
|
||||
expected_identities.add(identity)
|
||||
after_component = after_index.get(identity)
|
||||
if after_component is None:
|
||||
issues.append(_issue("missing_logical_identity", "Matched component is absent after replacement.", identity))
|
||||
continue
|
||||
if _part_identity(after_component.get("part_number")) != target:
|
||||
issues.append(_issue("wrong_target_part_number", "Matched component does not have the target Part Number.", identity))
|
||||
before_component = before_index[identity]
|
||||
for field in _PROTECTED_FIELDS:
|
||||
if before_component.get(field) != after_component.get(field):
|
||||
code = "unit_count_changed" if field == "units" else f"{field}_changed"
|
||||
issues.append(_issue(code, f"Protected field {field} changed.", identity))
|
||||
_compare_pins(before_component, after_component, identity, issues, warnings)
|
||||
warnings.extend(_presentation_warnings(
|
||||
before_component, after_component, identity, parameter_available=presentation_available
|
||||
))
|
||||
|
||||
for identity in before_index.keys() - after_index.keys():
|
||||
issues.append(_issue("component_removed", "Logical component was removed.", identity))
|
||||
for identity in after_index.keys() - before_index.keys():
|
||||
issues.append(_issue("component_added", "Unexpected logical component was added.", identity))
|
||||
for identity in before_index.keys() & after_index.keys():
|
||||
if identity in expected_identities:
|
||||
continue
|
||||
before_component = before_index[identity]
|
||||
after_component = after_index[identity]
|
||||
if _without_presentation(before_component) != _without_presentation(after_component):
|
||||
issues.append(_issue("unrelated_component_changed", "An unrelated component changed.", identity))
|
||||
warnings.extend(_presentation_warnings(
|
||||
before_component, after_component, identity, parameter_available=presentation_available
|
||||
))
|
||||
|
||||
return ProjectComparison(
|
||||
passed=not issues,
|
||||
matched_logical_identities=matched,
|
||||
warnings=tuple(warnings),
|
||||
issues=tuple(issues),
|
||||
)
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Stable, user-facing errors for trial task-center operations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
import secrets
|
||||
|
||||
|
||||
class TaskCenterError(ValueError):
|
||||
"""An operation failure with a durable support identifier and safe user text."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
code: str,
|
||||
message: str,
|
||||
*,
|
||||
error_id: str | None = None,
|
||||
traceback_detail: str = "",
|
||||
) -> None:
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.error_id = error_id or self._new_error_id()
|
||||
self.traceback_detail = traceback_detail
|
||||
super().__init__(f"{self.error_id} {code}: {message}")
|
||||
|
||||
@staticmethod
|
||||
def _new_error_id() -> str:
|
||||
date = datetime.now(timezone.utc).strftime("%Y%m%d")
|
||||
return f"DXT-{date}-{secrets.token_hex(4).upper()}"
|
||||
@@ -0,0 +1,271 @@
|
||||
"""Immutable capture and validation of menu-probe profiles."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
import hashlib
|
||||
import json
|
||||
import ntpath
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
|
||||
|
||||
_WINDOWS_EVIDENCE_PUBLICATION = os.name == "nt"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ProbeStamp:
|
||||
size: int
|
||||
modified_ns: int
|
||||
sha256: str
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CapturedProfile:
|
||||
source: Path
|
||||
destination: Path
|
||||
stamp: ProbeStamp
|
||||
project_identity: str
|
||||
data: Mapping[str, object]
|
||||
|
||||
|
||||
def _snapshot(path: Path) -> tuple[bytes, ProbeStamp] | None:
|
||||
try:
|
||||
with Path(path).open("rb") as handle:
|
||||
data = handle.read()
|
||||
status = os.fstat(handle.fileno())
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
except OSError as error:
|
||||
raise TaskCenterError("profile_file", f"cannot read probe profile: {path}") from error
|
||||
return data, ProbeStamp(len(data), status.st_mtime_ns, hashlib.sha256(data).hexdigest())
|
||||
|
||||
|
||||
def profile_stamp(path: Path) -> ProbeStamp | None:
|
||||
"""Return a content-addressed stamp for one opened byte snapshot."""
|
||||
snapshot = _snapshot(path)
|
||||
return None if snapshot is None else snapshot[1]
|
||||
|
||||
|
||||
def load_captured_profile(
|
||||
path: Path,
|
||||
expected_project: Path,
|
||||
expected_stamp: ProbeStamp,
|
||||
) -> dict[str, object]:
|
||||
"""Revalidate persisted profile bytes before using them as trusted evidence."""
|
||||
snapshot = _snapshot(path)
|
||||
if snapshot is None:
|
||||
raise TaskCenterError("evidence_integrity", f"captured profile is missing: {path}")
|
||||
data, stamp = snapshot
|
||||
if stamp.size != expected_stamp.size or stamp.sha256 != expected_stamp.sha256:
|
||||
raise TaskCenterError("evidence_integrity", f"captured profile content changed after capture: {path}")
|
||||
profile = _parse_profile(data, path)
|
||||
project = profile["project"]
|
||||
assert isinstance(project, dict)
|
||||
identity = project["identity"]
|
||||
assert isinstance(identity, str)
|
||||
if _project_identity(identity) != _project_identity(expected_project):
|
||||
raise TaskCenterError("profile_project", "captured profile belongs to a different project")
|
||||
return profile
|
||||
|
||||
|
||||
def _reject_duplicates(pairs: list[tuple[str, object]]) -> dict[str, object]:
|
||||
result: dict[str, object] = {}
|
||||
for key, value in pairs:
|
||||
if key in result:
|
||||
raise TaskCenterError("profile_duplicate_key", f"probe profile repeats JSON key: {key}")
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
def _parse_profile(data: bytes, source: Path) -> dict[str, object]:
|
||||
try:
|
||||
loaded = json.loads(
|
||||
data.decode("utf-8"),
|
||||
object_pairs_hook=_reject_duplicates,
|
||||
parse_constant=lambda value: (_ for _ in ()).throw(
|
||||
TaskCenterError("profile_json", f"probe profile has non-finite JSON value: {value}")
|
||||
),
|
||||
)
|
||||
except TaskCenterError:
|
||||
raise
|
||||
except (UnicodeError, json.JSONDecodeError) as error:
|
||||
raise TaskCenterError("profile_json", f"probe profile is not valid JSON: {source}") from error
|
||||
if not isinstance(loaded, dict):
|
||||
raise TaskCenterError("profile_json", f"probe profile must be a JSON object: {source}")
|
||||
if type(loaded.get("format_version")) is not int or loaded["format_version"] != 1:
|
||||
raise TaskCenterError("profile_version", "probe profile format_version must be 1")
|
||||
project = loaded.get("project")
|
||||
if not isinstance(project, dict) or not isinstance(project.get("identity"), str):
|
||||
raise TaskCenterError("profile_project", "probe profile does not contain a project identity")
|
||||
return loaded
|
||||
|
||||
|
||||
def _project_identity(path: str | Path) -> str:
|
||||
text = str(path)
|
||||
if os.name == "nt":
|
||||
try:
|
||||
text = str(Path(text).resolve())
|
||||
except OSError as error:
|
||||
raise TaskCenterError("profile_project", f"cannot canonicalize project identity: {path}") from error
|
||||
return os.path.normcase(os.path.normpath(text))
|
||||
if ntpath.splitdrive(text)[0]:
|
||||
return ntpath.normcase(ntpath.normpath(text))
|
||||
try:
|
||||
return os.path.normpath(str(Path(text).resolve()))
|
||||
except OSError as error:
|
||||
raise TaskCenterError("profile_project", f"cannot canonicalize project identity: {path}") from error
|
||||
|
||||
|
||||
def _absolute_lexical(path: Path) -> Path:
|
||||
return Path(os.path.abspath(os.fspath(path)))
|
||||
|
||||
|
||||
def _reject_reparse_components(path: Path) -> None:
|
||||
absolute = _absolute_lexical(path)
|
||||
current = Path(absolute.anchor)
|
||||
for part in absolute.parts[1:]:
|
||||
current /= part
|
||||
try:
|
||||
details = current.lstat()
|
||||
except FileNotFoundError:
|
||||
return
|
||||
except OSError as error:
|
||||
raise TaskCenterError("profile_publish_path", f"cannot validate publication path: {current}") from error
|
||||
if stat.S_ISLNK(details.st_mode) or bool(
|
||||
getattr(details, "st_file_attributes", 0) & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
|
||||
):
|
||||
raise TaskCenterError("profile_publish_path", f"publication path contains a reparse point: {current}")
|
||||
|
||||
|
||||
def _parent_identity(parent: Path) -> tuple[int, int]:
|
||||
try:
|
||||
details = parent.lstat()
|
||||
except OSError as error:
|
||||
raise TaskCenterError("profile_publish_path", f"cannot identify publication directory: {parent}") from error
|
||||
if not stat.S_ISDIR(details.st_mode) or stat.S_ISLNK(details.st_mode):
|
||||
raise TaskCenterError("profile_publish_path", f"publication parent is not a regular directory: {parent}")
|
||||
return details.st_dev, details.st_ino
|
||||
|
||||
|
||||
def _prepare_destination_parent(destination: Path) -> tuple[int, int]:
|
||||
_reject_reparse_components(destination)
|
||||
try:
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as error:
|
||||
raise TaskCenterError("profile_publish", f"cannot create publication directory: {destination.parent}") from error
|
||||
_reject_reparse_components(destination)
|
||||
return _parent_identity(destination.parent)
|
||||
|
||||
|
||||
def _verify_destination_parent(destination: Path, expected: tuple[int, int]) -> None:
|
||||
_reject_reparse_components(destination)
|
||||
if _parent_identity(destination.parent) != expected:
|
||||
raise TaskCenterError("profile_publish_path", "publication directory identity changed during capture")
|
||||
|
||||
|
||||
def _publication_hook(destination: Path, temporary: Path) -> None:
|
||||
"""Test seam executed while the staged-file handle remains open."""
|
||||
del destination, temporary
|
||||
|
||||
|
||||
def _reject_source_destination_alias(source: Path, destination: Path) -> None:
|
||||
try:
|
||||
source_canonical = source.resolve()
|
||||
destination_canonical = destination.resolve()
|
||||
same_file = source.exists() and destination.exists() and os.path.samefile(source, destination)
|
||||
except OSError as error:
|
||||
raise TaskCenterError("profile_source_destination_alias", "cannot validate source and destination identity") from error
|
||||
if source_canonical == destination_canonical or same_file:
|
||||
raise TaskCenterError("profile_source_destination_alias", "probe source and capture destination must differ")
|
||||
|
||||
|
||||
def _publish_atomically(destination: Path, data: bytes) -> None:
|
||||
if not _WINDOWS_EVIDENCE_PUBLICATION:
|
||||
raise TaskCenterError(
|
||||
"unsupported_platform",
|
||||
"captured-profile publication requires Windows handle-relative security",
|
||||
)
|
||||
expected_parent = _prepare_destination_parent(destination)
|
||||
try:
|
||||
_publish_with_windows_handles(destination, data, expected_parent)
|
||||
except TaskCenterError:
|
||||
raise
|
||||
except OSError as error:
|
||||
raise TaskCenterError("profile_publish", f"cannot publish captured profile: {destination}") from error
|
||||
|
||||
|
||||
def _publish_with_windows_handles(destination: Path, data: bytes, expected_parent: tuple[int, int]) -> None:
|
||||
# Reuse the repository's hardened Windows handle primitives. The second
|
||||
# staged-file validation is Task2-specific: it rejects a path substitution
|
||||
# between staging and handle-relative publication.
|
||||
from dx_productivity.part_replace.compatibility_profile import (
|
||||
CompatibilityProfileError,
|
||||
_close_handle,
|
||||
_delete_staged_file,
|
||||
_locked_destination_parent,
|
||||
_open_staged_file,
|
||||
_publish_staged_file,
|
||||
_validate_staged_file,
|
||||
_write_staged_file,
|
||||
)
|
||||
|
||||
temporary = destination.parent / f".{destination.name}.{uuid4().hex}.tmp"
|
||||
staged_handle: int | None = None
|
||||
published = False
|
||||
try:
|
||||
with _locked_destination_parent(destination.parent) as parent_handle:
|
||||
_verify_destination_parent(destination, expected_parent)
|
||||
staged_handle = _open_staged_file(temporary)
|
||||
_write_staged_file(staged_handle, data)
|
||||
_validate_staged_file(staged_handle, temporary)
|
||||
_publication_hook(destination, temporary)
|
||||
_validate_staged_file(staged_handle, temporary)
|
||||
_verify_destination_parent(destination, expected_parent)
|
||||
_publish_staged_file(staged_handle, parent_handle, destination.name)
|
||||
published = True
|
||||
_verify_destination_parent(destination, expected_parent)
|
||||
except CompatibilityProfileError as error:
|
||||
raise TaskCenterError("profile_publish", error.message) from error
|
||||
except OSError as error:
|
||||
raise TaskCenterError("profile_publish", f"cannot publish captured profile: {destination}") from error
|
||||
finally:
|
||||
if staged_handle is not None:
|
||||
try:
|
||||
if not published:
|
||||
_delete_staged_file(staged_handle)
|
||||
except OSError:
|
||||
pass
|
||||
_close_handle(staged_handle)
|
||||
|
||||
|
||||
def capture_profile(
|
||||
source: Path,
|
||||
destination: Path,
|
||||
expected_project: Path,
|
||||
previous: ProbeStamp | None,
|
||||
) -> CapturedProfile:
|
||||
"""Validate changed probe evidence and atomically copy its exact bytes."""
|
||||
source = Path(source)
|
||||
destination = Path(destination)
|
||||
snapshot = _snapshot(source)
|
||||
if snapshot is None:
|
||||
raise TaskCenterError("profile_missing", f"probe profile does not exist: {source}")
|
||||
data, stamp = snapshot
|
||||
_reject_source_destination_alias(source, destination)
|
||||
if previous is not None and stamp.sha256 == previous.sha256 and stamp.modified_ns == previous.modified_ns:
|
||||
raise TaskCenterError("profile_unchanged", "probe profile did not change after operator action")
|
||||
profile = _parse_profile(data, source)
|
||||
project = profile["project"]
|
||||
assert isinstance(project, dict)
|
||||
identity = project["identity"]
|
||||
assert isinstance(identity, str)
|
||||
if _project_identity(identity) != _project_identity(expected_project):
|
||||
raise TaskCenterError("profile_project", "probe profile belongs to a different project")
|
||||
_publish_atomically(destination, data)
|
||||
return CapturedProfile(source, destination, stamp, identity, profile)
|
||||
@@ -0,0 +1,257 @@
|
||||
"""Application diagnostics and durable per-task JSON Lines events."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from logging.handlers import RotatingFileHandler
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from typing import Any, Mapping
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .retention import rotate_text_log
|
||||
|
||||
|
||||
_MAX_LOG_BYTES = 5 * 1024 * 1024
|
||||
_BACKUP_COUNT = 5
|
||||
_MAX_EVENT_LOG_BYTES = 5 * 1024 * 1024
|
||||
_EVENT_BACKUP_COUNT = 5
|
||||
_EVENT_KEYS = (
|
||||
"sequence",
|
||||
"timestamp_utc",
|
||||
"level",
|
||||
"task_id",
|
||||
"project_id",
|
||||
"operation",
|
||||
"state_before",
|
||||
"state_after",
|
||||
"error_id",
|
||||
"message",
|
||||
"details",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class LoggingContext:
|
||||
"""Paths, logger, and synchronization needed by diagnostic helpers."""
|
||||
|
||||
root: Path
|
||||
application_log_path: Path
|
||||
logger: logging.Logger
|
||||
_event_lock: threading.RLock = field(default_factory=threading.RLock, repr=False)
|
||||
|
||||
def report_exception(
|
||||
self,
|
||||
operation: str,
|
||||
error: BaseException,
|
||||
traceback_object: object | None = None,
|
||||
) -> TaskCenterError:
|
||||
"""Write an exception traceback and return its safe support identifier."""
|
||||
if isinstance(error, TaskCenterError):
|
||||
reported = error
|
||||
else:
|
||||
reported = TaskCenterError("unhandled_exception", "发生未处理异常")
|
||||
detail = "".join(
|
||||
traceback.format_exception(type(error), error, traceback_object or error.__traceback__)
|
||||
)
|
||||
self.logger.error(
|
||||
"error_id=%s operation=%s message=%s\n%s",
|
||||
reported.error_id,
|
||||
operation,
|
||||
reported.message,
|
||||
detail.rstrip(),
|
||||
)
|
||||
_flush_handlers(self.logger)
|
||||
return reported
|
||||
|
||||
|
||||
def configure_logging(root: Path) -> LoggingContext:
|
||||
"""Create storage directories and a UTF-8 rotating application log handler."""
|
||||
storage_root = Path(root).resolve()
|
||||
log_path = storage_root / "logs" / "application.log"
|
||||
log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
(storage_root / "tasks").mkdir(parents=True, exist_ok=True)
|
||||
logger_name = "dx_productivity.trial_task_center." + hashlib.sha256(
|
||||
str(storage_root.resolve()).encode("utf-8")
|
||||
).hexdigest()[:16]
|
||||
logger = logging.getLogger(logger_name)
|
||||
logger.setLevel(logging.DEBUG)
|
||||
logger.propagate = False
|
||||
if not any(
|
||||
isinstance(handler, RotatingFileHandler) and Path(handler.baseFilename) == log_path
|
||||
for handler in logger.handlers
|
||||
):
|
||||
handler = RotatingFileHandler(
|
||||
log_path,
|
||||
maxBytes=_MAX_LOG_BYTES,
|
||||
backupCount=_BACKUP_COUNT,
|
||||
encoding="utf-8",
|
||||
)
|
||||
formatter = logging.Formatter(
|
||||
"%(asctime)s %(levelname)s %(name)s %(message)s", datefmt="%Y-%m-%dT%H:%M:%SZ"
|
||||
)
|
||||
formatter.converter = time.gmtime
|
||||
handler.setFormatter(formatter)
|
||||
logger.addHandler(handler)
|
||||
logger.info("logging configured root=%s application_log=%s", storage_root, log_path)
|
||||
_flush_handlers(logger)
|
||||
return LoggingContext(storage_root, log_path, logger)
|
||||
|
||||
|
||||
def append_task_event(
|
||||
context: LoggingContext,
|
||||
*,
|
||||
level: str,
|
||||
task_id: str,
|
||||
operation: str,
|
||||
project_id: str | None = None,
|
||||
state_before: str | None = None,
|
||||
state_after: str | None = None,
|
||||
error_id: str | None = None,
|
||||
message: str = "",
|
||||
details: Mapping[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Durably append one canonical task event and return its decoded record."""
|
||||
task_directory = _task_directory(context, task_id)
|
||||
try:
|
||||
details_value = dict(details or {})
|
||||
json.dumps(details_value, ensure_ascii=False, allow_nan=False)
|
||||
except (TypeError, ValueError) as error:
|
||||
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)
|
||||
event = {
|
||||
"sequence": sequence,
|
||||
"timestamp_utc": _utc_now_text(),
|
||||
"level": str(level).upper(),
|
||||
"task_id": task_id,
|
||||
"project_id": project_id,
|
||||
"operation": str(operation),
|
||||
"state_before": state_before,
|
||||
"state_after": state_after,
|
||||
"error_id": error_id,
|
||||
"message": str(message),
|
||||
"details": details_value,
|
||||
}
|
||||
encoded = json.dumps(event, ensure_ascii=False, separators=(",", ":"), allow_nan=False) + "\n"
|
||||
try:
|
||||
rotate_text_log(
|
||||
path,
|
||||
max_bytes=_MAX_EVENT_LOG_BYTES,
|
||||
backup_count=_EVENT_BACKUP_COUNT,
|
||||
)
|
||||
with path.open("a", encoding="utf-8", newline="\n") as handle:
|
||||
handle.write(encoded)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
except OSError as error:
|
||||
raise TaskCenterError("event_write_failed", "cannot append task event") from error
|
||||
context.logger.log(
|
||||
_logging_level(event["level"]),
|
||||
"task_event task_id=%s project_id=%s operation=%s sequence=%s",
|
||||
task_id,
|
||||
project_id or "",
|
||||
operation,
|
||||
sequence,
|
||||
)
|
||||
_flush_handlers(context.logger)
|
||||
return event
|
||||
|
||||
|
||||
def capture_subprocess_output(
|
||||
context: LoggingContext,
|
||||
*,
|
||||
operation: str,
|
||||
returncode: int,
|
||||
stdout: str,
|
||||
stderr: str,
|
||||
) -> None:
|
||||
"""Record complete subprocess outcome and both output streams in application.log."""
|
||||
context.logger.info("operation=%s returncode=%s", operation, returncode)
|
||||
if stdout:
|
||||
context.logger.info("operation=%s stdout=%s", operation, stdout.rstrip())
|
||||
if stderr:
|
||||
context.logger.warning("operation=%s stderr=%s", operation, stderr.rstrip())
|
||||
_flush_handlers(context.logger)
|
||||
|
||||
|
||||
def install_exception_hooks(context: LoggingContext) -> None:
|
||||
"""Route uncaught main and worker exceptions to the application diagnostic log."""
|
||||
def main_exception_hook(
|
||||
exception_type: type[BaseException], exception: BaseException, traceback_object: object
|
||||
) -> None:
|
||||
del exception_type
|
||||
context.report_exception("uncaught_main_thread", exception, traceback_object)
|
||||
|
||||
def thread_exception_hook(arguments: threading.ExceptHookArgs) -> None:
|
||||
thread_name = arguments.thread.name if arguments.thread is not None else "unknown"
|
||||
context.report_exception(f"uncaught_worker_thread:{thread_name}", arguments.exc_value, arguments.exc_traceback)
|
||||
|
||||
sys.excepthook = main_exception_hook
|
||||
threading.excepthook = thread_exception_hook
|
||||
|
||||
|
||||
def _task_directory(context: LoggingContext, task_id: str) -> Path:
|
||||
if not task_id or Path(task_id).name != task_id or task_id in {".", ".."}:
|
||||
raise TaskCenterError("task_id", "task event requires a safe task identifier")
|
||||
path = context.root / "tasks" / task_id
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def _next_event_sequence(path: Path) -> int:
|
||||
try:
|
||||
for candidate in (path, path.with_name(f"{path.name}.1")):
|
||||
if not candidate.exists():
|
||||
continue
|
||||
lines = _tail_utf8_lines(candidate, 1)
|
||||
if lines:
|
||||
record = json.loads(lines[-1])
|
||||
return int(record["sequence"]) + 1
|
||||
return 1
|
||||
except (OSError, UnicodeError, ValueError, KeyError, TypeError) as error:
|
||||
raise TaskCenterError("event_sequence", "cannot determine the next task event sequence") from error
|
||||
|
||||
|
||||
def _tail_utf8_lines(path: Path, limit: int) -> tuple[str, ...]:
|
||||
if limit < 1:
|
||||
return ()
|
||||
with Path(path).open("rb") as handle:
|
||||
handle.seek(0, os.SEEK_END)
|
||||
cursor = handle.tell()
|
||||
chunks = []
|
||||
newline_count = 0
|
||||
while cursor > 0 and newline_count <= limit:
|
||||
size = min(8192, cursor)
|
||||
cursor -= size
|
||||
handle.seek(cursor)
|
||||
chunk = handle.read(size)
|
||||
chunks.append(chunk)
|
||||
newline_count += chunk.count(b"\n")
|
||||
payload = b"".join(reversed(chunks))
|
||||
if cursor > 0:
|
||||
separator = payload.find(b"\n")
|
||||
payload = payload[separator + 1:] if separator >= 0 else b""
|
||||
return tuple(payload.decode("utf-8").splitlines()[-limit:])
|
||||
|
||||
|
||||
def _utc_now_text() -> str:
|
||||
return datetime.now(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def _logging_level(level: str) -> int:
|
||||
return getattr(logging, level.upper(), logging.INFO)
|
||||
|
||||
|
||||
def _flush_handlers(logger: logging.Logger) -> None:
|
||||
for handler in logger.handlers:
|
||||
handler.flush()
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Immutable domain records used by the task-center service and UI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class TaskStatus(str, Enum):
|
||||
DRAFT = "draft"
|
||||
READY = "ready"
|
||||
RUNNING = "running"
|
||||
PAUSED = "paused"
|
||||
COMPLETED = "completed"
|
||||
FAILED = "failed"
|
||||
DELETED = "deleted"
|
||||
|
||||
|
||||
class ProjectStatus(str, Enum):
|
||||
PENDING = "pending"
|
||||
CAPTURING_BEFORE = "capturing_before"
|
||||
AWAITING_OPERATOR = "awaiting_operator"
|
||||
CAPTURING_AFTER = "capturing_after"
|
||||
VERIFYING = "verifying"
|
||||
COMPLETED = "completed"
|
||||
FAILED = "failed"
|
||||
SKIPPED = "skipped"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class TaskRecord:
|
||||
task_id: str
|
||||
name: str
|
||||
note: str
|
||||
discovery_root: Path | None
|
||||
status: TaskStatus
|
||||
created_utc: datetime
|
||||
updated_utc: datetime
|
||||
started_utc: datetime | None = None
|
||||
completed_utc: datetime | None = None
|
||||
deleted_utc: datetime | None = None
|
||||
status_before_delete: TaskStatus | None = None
|
||||
error_id: str | None = None
|
||||
summary: str = ""
|
||||
copy_part_number_to_value: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RuleRecord:
|
||||
rule_id: str
|
||||
task_id: str
|
||||
position: int
|
||||
old_part_number: str
|
||||
new_part_number: str
|
||||
enabled: bool
|
||||
custom_value_enabled: bool = False
|
||||
custom_value: str = ""
|
||||
sync_nc: bool = True
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ProjectRecord:
|
||||
project_id: str
|
||||
task_id: str
|
||||
display_name: str
|
||||
path: Path
|
||||
discovery_root: Path
|
||||
selected: bool
|
||||
available: bool
|
||||
status: ProjectStatus
|
||||
retry_count: int
|
||||
error_id: str | None = None
|
||||
summary: str = ""
|
||||
@@ -0,0 +1,627 @@
|
||||
"""Native current-sheet replacement adapter for the existing QuickPartReplace runner."""
|
||||
import argparse
|
||||
import ctypes
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
|
||||
|
||||
def decode(value):
|
||||
characters = []
|
||||
index = 0
|
||||
while index < len(value):
|
||||
match = re.match(r"%([0-9A-Fa-f]{4})", value[index:])
|
||||
if match is not None:
|
||||
characters.append(chr(int(match[1], 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 read_snapshot(path):
|
||||
rows = [[decode(field) for field in line.split("\t")]
|
||||
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:
|
||||
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 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):
|
||||
raise ValueError("Invalid component snapshot")
|
||||
if len({row[1] for row in components}) != len(components):
|
||||
raise ValueError("Duplicate snapshot UID")
|
||||
if metadata[0][2].casefold() == metadata[0][3].casefold():
|
||||
raise ValueError("Source and target must differ")
|
||||
return metadata[0], components
|
||||
|
||||
|
||||
def snapshot_value_mode(metadata):
|
||||
return metadata[5] if len(metadata) >= 6 else "part_label"
|
||||
|
||||
|
||||
def snapshot_sha256(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def transaction_binding(snapshot, metadata, records, library_row, symbol, slot_count=1):
|
||||
if len(library_row) < 6 or not str(library_row[4]).strip() or not str(library_row[5]).strip():
|
||||
raise ValueError("Library target has incomplete identity fields")
|
||||
slots = int(slot_count)
|
||||
if slots < 1:
|
||||
raise ValueError("Library target has no valid slots")
|
||||
return {
|
||||
"snapshot_sha256": snapshot_sha256(snapshot),
|
||||
"project_path": os.path.normcase(os.path.abspath(metadata[1])),
|
||||
"sheet_identity": metadata[4],
|
||||
"old_part_number": metadata[2],
|
||||
"new_part_number": metadata[3],
|
||||
"source_uids": sorted(row[1] for row in records),
|
||||
"library_row": [str(value) for value in library_row],
|
||||
"target_symbol": str(symbol),
|
||||
"slot_count": slots,
|
||||
}
|
||||
|
||||
|
||||
def require_resumable_transaction(snapshot, report, metadata, records):
|
||||
if report.get("stage") not in {
|
||||
"native_replace_started",
|
||||
"native_replace_applied",
|
||||
"pin_promotion_started",
|
||||
"native_replace_verified",
|
||||
}:
|
||||
raise ValueError("Cannot prove that the native replacement belongs to this job")
|
||||
binding = report.get("transaction")
|
||||
expected = {
|
||||
"snapshot_sha256": snapshot_sha256(snapshot),
|
||||
"project_path": os.path.normcase(os.path.abspath(metadata[1])),
|
||||
"sheet_identity": metadata[4],
|
||||
"old_part_number": metadata[2],
|
||||
"new_part_number": metadata[3],
|
||||
"source_uids": sorted(row[1] for row in records),
|
||||
}
|
||||
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")
|
||||
library_row = binding.get("library_row")
|
||||
if not isinstance(library_row, list) or len(library_row) < 6:
|
||||
raise ValueError("Native replacement evidence has no target library identity")
|
||||
return binding
|
||||
|
||||
|
||||
def exact_target(rows, target):
|
||||
matches = [row for row in rows if len(row[1]) >= 3 and row[1][1] == target]
|
||||
if len(matches) != 1:
|
||||
raise ValueError(f"Expected one exact library part/gate, found {len(matches)}: {target}")
|
||||
if not matches[0][1][2].strip():
|
||||
raise ValueError("Library target has no associated symbol")
|
||||
return matches[0]
|
||||
|
||||
|
||||
def wait_for(callback, description, timeout=15):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
result = callback()
|
||||
if result:
|
||||
return result
|
||||
time.sleep(0.15)
|
||||
raise TimeoutError(description)
|
||||
|
||||
|
||||
def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_interval=0.15):
|
||||
deadline = time.monotonic() + timeout
|
||||
previous = None
|
||||
stable_since = None
|
||||
latest = []
|
||||
while time.monotonic() < deadline:
|
||||
latest = callback()
|
||||
signature = tuple(tuple(str(value) for value in columns) for _, columns in latest)
|
||||
now = time.monotonic()
|
||||
if signature != previous:
|
||||
previous = signature
|
||||
stable_since = now
|
||||
exact = [row for row in latest if len(row[1]) >= 3 and row[1][1] == target]
|
||||
if exact and stable_since is not None and now - stable_since >= stable_for:
|
||||
return latest
|
||||
time.sleep(poll_interval)
|
||||
raise TimeoutError(f"Native DxDataBook did not finish loading target part: {target}")
|
||||
|
||||
|
||||
def target_symbol_matches(displayed, library_symbol, slot_count):
|
||||
actual = str(displayed).casefold()
|
||||
expected = str(library_symbol).casefold()
|
||||
if actual == expected:
|
||||
return True
|
||||
prefix = expected + "."
|
||||
if not actual.startswith(prefix):
|
||||
return False
|
||||
suffix = actual[len(prefix):]
|
||||
return suffix.isdigit() and 1 <= int(suffix) <= int(slot_count)
|
||||
|
||||
|
||||
def is_replace_symbol_title(title):
|
||||
normalized = str(title).replace("&", "").casefold()
|
||||
return "\u66ff\u6362\u7b26\u53f7" in normalized or "replace symbol" in normalized
|
||||
|
||||
|
||||
def replacement_command_from_resources(executable):
|
||||
import win32api
|
||||
import win32gui
|
||||
|
||||
if Path(executable).name.casefold() != "viewdraw.exe":
|
||||
raise ValueError("Replacement command must come from the attached Viewdraw executable")
|
||||
module = win32api.LoadLibraryEx(str(executable), 0, 0x22)
|
||||
commands = set()
|
||||
|
||||
def visit(menu):
|
||||
for index in range(win32gui.GetMenuItemCount(menu)):
|
||||
submenu = win32gui.GetSubMenu(menu, index)
|
||||
if submenu:
|
||||
visit(submenu)
|
||||
continue
|
||||
title = ctypes.create_unicode_buffer(512)
|
||||
ctypes.windll.user32.GetMenuStringW(menu, index, title, len(title), 0x400)
|
||||
if is_replace_symbol_title(title.value):
|
||||
command_id = win32gui.GetMenuItemID(menu, index)
|
||||
if 0 < command_id < 0xFFFF:
|
||||
commands.add(command_id)
|
||||
|
||||
try:
|
||||
for resource in win32api.EnumResourceNames(module, 4):
|
||||
menu = win32gui.LoadMenu(module, resource)
|
||||
try:
|
||||
visit(menu)
|
||||
finally:
|
||||
win32gui.DestroyMenu(menu)
|
||||
finally:
|
||||
win32api.FreeLibrary(module)
|
||||
if len(commands) != 1:
|
||||
raise ValueError("Cannot identify one native Replace Symbol command; no mouse fallback is allowed")
|
||||
return commands.pop()
|
||||
|
||||
|
||||
def attach():
|
||||
import win32com.client
|
||||
try:
|
||||
import viewdraw_api as api
|
||||
except ImportError:
|
||||
api = win32com.client.gencache.EnsureModule(
|
||||
"{4ADEF4E1-690A-11CE-9261-0020C5E26659}", 0, 1, 0)
|
||||
app = api.IVdApp(win32com.client.GetActiveObject("Viewdraw.Application")._oleobj_)
|
||||
return app, api
|
||||
|
||||
|
||||
def attribute_value(component, name):
|
||||
attribute = component.FindAttribute(name)
|
||||
if attribute is None:
|
||||
return ""
|
||||
return str(attribute.InstanceValue or attribute.Value)
|
||||
|
||||
|
||||
def selection(component, value):
|
||||
import win32com.client.dynamic
|
||||
item = win32com.client.dynamic.DumbDispatch(component._oleobj_)
|
||||
item.Selected = bool(value)
|
||||
|
||||
|
||||
def components_on_sheet(app, api):
|
||||
return [api.IVdComp(component._oleobj_) for component in app.ActiveView.Query(128, 0)]
|
||||
|
||||
|
||||
def check_active_context(app, metadata):
|
||||
if os.path.normcase(os.path.abspath(app.GetProjectData().GetProjectFilePath())) != os.path.normcase(os.path.abspath(metadata[1])):
|
||||
raise ValueError("Active project changed")
|
||||
if f"{app.ActiveView.GetName(0)}:{app.ActiveView.Block.SheetNum}" != metadata[4]:
|
||||
raise ValueError("Active sheet changed")
|
||||
|
||||
|
||||
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}")
|
||||
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 select_snapshot_batch(app, api, metadata, records):
|
||||
components = check_context(app, api, metadata, records, require_selection=False)
|
||||
wanted = {row[1] for row in records}
|
||||
for component in components:
|
||||
selection(component, str(component.UID) in wanted)
|
||||
return check_context(app, api, metadata, records)
|
||||
|
||||
|
||||
def existing_replacement_uids(components, records, target, binding, require_part_label=True):
|
||||
current_by_uid = {str(component.UID): component for component in components}
|
||||
target_key = target.casefold()
|
||||
current_by_refdes = {}
|
||||
for component in components:
|
||||
if attribute_value(component, "Part Number").casefold() == target_key:
|
||||
current_by_refdes.setdefault(str(component.Refdes), []).append(component)
|
||||
library_row = binding["library_row"]
|
||||
expected_part_name = str(library_row[4]).strip().casefold()
|
||||
expected_part_label = str(library_row[5]).strip().casefold()
|
||||
matches = []
|
||||
for record in records:
|
||||
candidate = current_by_uid.get(record[1])
|
||||
if candidate is None or attribute_value(candidate, "Part Number").casefold() != target_key:
|
||||
candidates = current_by_refdes.get(record[2], ())
|
||||
if len(candidates) != 1:
|
||||
raise ValueError("Source batch changed since snapshot")
|
||||
candidate = candidates[0]
|
||||
part_name = attribute_value(candidate, "Part Name").strip().casefold()
|
||||
part_label = attribute_value(candidate, "Part Label").strip().casefold()
|
||||
if part_name != expected_part_name or (require_part_label and part_label != expected_part_label):
|
||||
raise ValueError("Existing replacement does not match the recorded target library identity")
|
||||
matches.append(str(candidate.UID))
|
||||
if len(set(matches)) != len(records):
|
||||
raise ValueError("Duplicate replacement association")
|
||||
return matches
|
||||
|
||||
|
||||
def promote_pin_numbers(app, api, replacement_uids, slot_count=1):
|
||||
components = components_on_sheet(app, api)
|
||||
replacement_uids = set(replacement_uids)
|
||||
try:
|
||||
for component in components:
|
||||
selection(component, str(component.UID) in replacement_uids)
|
||||
for slot in range(1, int(slot_count) + 1):
|
||||
app.ActiveView.Block.PromoteSymbolNumbers(1, slot)
|
||||
promoted = []
|
||||
for item in app.ActiveView.Query(4096, 0):
|
||||
pin = api.IVdCmpPin(item._oleobj_)
|
||||
if str(pin.Component.UID) in replacement_uids:
|
||||
if not str(pin.Number).strip():
|
||||
raise ValueError("Native target-library pin number promotion failed")
|
||||
promoted.append({"uid": str(pin.Component.UID), "number": str(pin.Number)})
|
||||
if not promoted:
|
||||
raise ValueError("Replacement produced no pins")
|
||||
return promoted
|
||||
finally:
|
||||
for component in components:
|
||||
selection(component, False)
|
||||
|
||||
|
||||
def replacement_matches(components, records, target, require_part_label):
|
||||
current_by_uid = {str(component.UID): component for component in components}
|
||||
current_by_refdes = {}
|
||||
for component in components:
|
||||
current_by_refdes.setdefault(str(component.Refdes), []).append(component)
|
||||
matches = []
|
||||
for record in records:
|
||||
candidate = current_by_uid.get(record[1])
|
||||
if candidate is None:
|
||||
candidates = current_by_refdes.get(record[2], ())
|
||||
if len(candidates) != 1:
|
||||
raise ValueError("Native replacement lost component identity")
|
||||
candidate = candidates[0]
|
||||
if attribute_value(candidate, "Part Number").casefold() != target.casefold():
|
||||
return None
|
||||
identity = str(candidate.Refdes).strip() or f"UID={candidate.UID}"
|
||||
if not attribute_value(candidate, "Part Name"):
|
||||
raise ValueError(
|
||||
f"Native replacement Part Name readback failed; refdes={identity}; uid={candidate.UID}"
|
||||
)
|
||||
if require_part_label and not attribute_value(candidate, "Part Label"):
|
||||
raise ValueError(
|
||||
f"Native replacement Part Label readback failed; refdes={identity}; uid={candidate.UID}; "
|
||||
"Part Label is required by the selected Value policy"
|
||||
)
|
||||
matches.append(str(candidate.UID))
|
||||
if len(set(matches)) != len(records):
|
||||
raise ValueError("Duplicate replacement association")
|
||||
return matches
|
||||
|
||||
|
||||
def run_native(snapshot, report):
|
||||
import win32api
|
||||
import win32con
|
||||
import win32gui
|
||||
import win32process
|
||||
from pywinauto import Desktop
|
||||
|
||||
metadata, records = read_snapshot(snapshot)
|
||||
require_part_label = snapshot_value_mode(metadata) == "part_label"
|
||||
app, api = attach()
|
||||
check_active_context(app, metadata)
|
||||
components = components_on_sheet(app, api)
|
||||
wanted = {row[1] for row in records}
|
||||
source_uids = {
|
||||
str(component.UID)
|
||||
for component in components
|
||||
if attribute_value(component, "Part Number").casefold() == metadata[2].casefold()
|
||||
}
|
||||
if source_uids != wanted:
|
||||
binding = require_resumable_transaction(snapshot, report, metadata, records)
|
||||
report["replaced_uids"] = existing_replacement_uids(
|
||||
components, records, metadata[3], binding, require_part_label=require_part_label
|
||||
)
|
||||
if report.get("stage") == "native_replace_verified" and report.get("ok") is True:
|
||||
report["already_replaced"] = True
|
||||
return
|
||||
report["stage"] = "pin_promotion_started"
|
||||
save_report(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["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}
|
||||
view_handle = int(app.ActiveViewHandle)
|
||||
process_id = win32process.GetWindowThreadProcessId(view_handle)[1]
|
||||
main_handle = win32gui.GetAncestor(view_handle, 2)
|
||||
desktop = Desktop(backend="uia")
|
||||
|
||||
def owned_windows(include_hidden=False):
|
||||
handles = []
|
||||
roots = []
|
||||
def collect_root(handle, _):
|
||||
if win32process.GetWindowThreadProcessId(handle)[1] == process_id:
|
||||
roots.append(handle)
|
||||
if include_hidden or win32gui.IsWindowVisible(handle):
|
||||
handles.append(handle)
|
||||
def collect_child(handle, _):
|
||||
if include_hidden or win32gui.IsWindowVisible(handle):
|
||||
handles.append(handle)
|
||||
win32gui.EnumWindows(collect_root, None)
|
||||
for root in roots:
|
||||
win32gui.EnumChildWindows(root, collect_child, None)
|
||||
return list(dict.fromkeys(handles))
|
||||
|
||||
def dlg_item(handle, identifier):
|
||||
try:
|
||||
return win32gui.GetDlgItem(handle, identifier)
|
||||
except win32gui.error:
|
||||
return 0
|
||||
|
||||
def replacement_dialog():
|
||||
matches = [handle for handle in owned_windows() if win32gui.GetClassName(handle) == "#32770"
|
||||
and dlg_item(handle, 1695) and dlg_item(handle, 1701)]
|
||||
if len(matches) > 1:
|
||||
raise ValueError("Multiple replacement dialogs")
|
||||
return matches[0] if matches else None
|
||||
|
||||
def message(handle, code, wparam=0, lparam=0):
|
||||
return win32gui.SendMessageTimeout(handle, code, wparam, lparam, win32con.SMTO_ABORTIFHUNG, 15000)
|
||||
|
||||
def control_text(control):
|
||||
buffer = ctypes.create_unicode_buffer(2048)
|
||||
message(control, win32con.WM_GETTEXT, len(buffer), ctypes.addressof(buffer))
|
||||
return buffer.value
|
||||
|
||||
def click(control):
|
||||
if not control or not win32gui.IsWindowEnabled(control):
|
||||
raise ValueError("Required replacement control is unavailable")
|
||||
message(control, 0x00F5)
|
||||
|
||||
def check_radio(dialog, identifier):
|
||||
control = dlg_item(dialog, identifier)
|
||||
if not control:
|
||||
raise ValueError(f"Required native option {identifier} is unavailable")
|
||||
if win32gui.SendMessage(control, 0x00F0, 0, 0) != 1:
|
||||
click(control)
|
||||
if win32gui.SendMessage(control, 0x00F0, 0, 0) != 1:
|
||||
raise ValueError(f"Native option {identifier} was not enabled")
|
||||
report.setdefault("native_options", {})[str(identifier)] = {
|
||||
"text": control_text(control),
|
||||
"checked": True,
|
||||
}
|
||||
|
||||
if replacement_dialog():
|
||||
raise ValueError("Close the existing replacement dialog before starting this job")
|
||||
dialog = None
|
||||
try:
|
||||
process = win32api.OpenProcess(0x410, False, process_id)
|
||||
try:
|
||||
executable = Path(win32process.GetModuleFileNameEx(process, 0))
|
||||
finally:
|
||||
process.Close()
|
||||
command_id = replacement_command_from_resources(executable)
|
||||
check_context(app, api, metadata, records)
|
||||
report["native_command"] = {"id": command_id, "executable": str(executable), "trigger": "resource_command"}
|
||||
win32gui.PostMessage(main_handle, win32con.WM_COMMAND, command_id, 0)
|
||||
dialog = wait_for(replacement_dialog, "Native replacement dialog did not open; no mouse input was injected", timeout=8)
|
||||
check_radio(dialog, 1704)
|
||||
check_radio(dialog, 1105)
|
||||
check_radio(dialog, 1697)
|
||||
check_radio(dialog, 1700)
|
||||
report["databook"] = {
|
||||
"main_visible_before_browse": bool(win32gui.IsWindowVisible(main_handle)),
|
||||
"browse_button": int(dlg_item(dialog, 1366)),
|
||||
}
|
||||
click(dlg_item(dialog, 1366))
|
||||
|
||||
def part_list():
|
||||
report["databook"]["main_visible_during_wait"] = bool(
|
||||
win32gui.IsWindowVisible(main_handle)
|
||||
)
|
||||
for handle in owned_windows(include_hidden=True):
|
||||
if win32gui.GetClassName(handle) == "SysListView32" and win32gui.GetDlgCtrlID(handle) == 4000:
|
||||
return handle
|
||||
return None
|
||||
list_handle = wait_for(part_list, "Native DxDataBook part list did not open", timeout=30)
|
||||
report["databook"].update(
|
||||
list_handle=int(list_handle),
|
||||
list_visible=bool(win32gui.IsWindowVisible(list_handle)),
|
||||
main_visible_after_load=bool(win32gui.IsWindowVisible(main_handle)),
|
||||
)
|
||||
filter_handles = [handle for handle in owned_windows(include_hidden=True)
|
||||
if win32gui.GetDlgCtrlID(handle) == 4006 and win32gui.GetClassName(handle) == "Edit"]
|
||||
if len(filter_handles) != 1:
|
||||
raise ValueError("Cannot uniquely identify native Part Number filter")
|
||||
message(filter_handles[0], win32con.WM_SETTEXT, 0, metadata[3])
|
||||
def current_library_rows():
|
||||
return [(row, [text.window_text() for text in row.children(control_type="Text")])
|
||||
for row in desktop.window(handle=list_handle).descendants(control_type="ListItem")]
|
||||
rows = wait_for_library_rows(current_library_rows, metadata[3])
|
||||
row, columns = exact_target(rows, metadata[3])
|
||||
report["library_row"] = columns
|
||||
symbol_parts = columns[2].split(":", 1)
|
||||
if len(symbol_parts) != 2:
|
||||
raise ValueError("Library symbol has no partition")
|
||||
slot_count = int(app.GetProjectData().GetSlotsCount(symbol_parts[0], symbol_parts[1], metadata[3]))
|
||||
report["slot_count"] = slot_count
|
||||
if slot_count < 1:
|
||||
raise ValueError("Library target has no valid slots")
|
||||
rectangle = row.rectangle()
|
||||
list_rectangle = win32gui.GetWindowRect(list_handle)
|
||||
if rectangle.height() <= 0 or rectangle.top < list_rectangle[1] or rectangle.bottom > list_rectangle[3]:
|
||||
raise ValueError("Exact library row is not visible")
|
||||
point = win32gui.ScreenToClient(list_handle, (rectangle.left + 100, rectangle.top + 12))
|
||||
report["row_rectangle"] = [rectangle.left, rectangle.top, rectangle.right, rectangle.bottom]
|
||||
report["list_handle"] = list_handle
|
||||
position = (point[1] << 16) | (point[0] & 0xFFFF)
|
||||
for code, key in [(win32con.WM_LBUTTONDOWN, 1), (win32con.WM_LBUTTONUP, 0), (win32con.WM_LBUTTONDBLCLK, 1), (win32con.WM_LBUTTONUP, 0)]:
|
||||
win32gui.PostMessage(list_handle, code, key, position)
|
||||
def target_ready():
|
||||
control = dlg_item(dialog, 1703)
|
||||
inner = dlg_item(control, 1001)
|
||||
report["target_text"] = control_text(inner or control)
|
||||
report["symbol_text"] = control_text(dlg_item(dialog, 1701))
|
||||
return report["target_text"] == metadata[3]
|
||||
wait_for(target_ready, "Native target part did not update")
|
||||
symbol = control_text(dlg_item(dialog, 1701))
|
||||
if not target_symbol_matches(symbol, columns[2], slot_count):
|
||||
raise ValueError(f"Native symbol does not match library row: {symbol}")
|
||||
components = check_context(app, api, metadata, records, require_selection=False)
|
||||
for component in components:
|
||||
selection(component, str(component.UID) in wanted)
|
||||
for identifier in (1704, 1105, 1697, 1700):
|
||||
check_radio(dialog, identifier)
|
||||
check_context(app, api, metadata, records)
|
||||
report["transaction"] = transaction_binding(snapshot, metadata, records, columns, symbol, slot_count)
|
||||
report["stage"] = "native_replace_started"
|
||||
save_report(snapshot, report)
|
||||
click(dlg_item(dialog, 1695))
|
||||
|
||||
replacement_poll_count = 0
|
||||
|
||||
def selected_replaced():
|
||||
nonlocal replacement_poll_count
|
||||
replacement_poll_count += 1
|
||||
selected = [api.IVdComp(component._oleobj_) for component in app.ActiveView.Query(128, 1)]
|
||||
if len(selected) == len(records):
|
||||
matches = replacement_matches(selected, records, metadata[3], require_part_label)
|
||||
if matches is not None:
|
||||
return matches
|
||||
if replacement_poll_count % 7 == 0:
|
||||
return replacement_matches(
|
||||
components_on_sheet(app, api), records, metadata[3], require_part_label
|
||||
)
|
||||
return None
|
||||
|
||||
report["replaced_uids"] = wait_for(
|
||||
selected_replaced, "Native replacement did not complete", timeout=30
|
||||
)
|
||||
current = components_on_sheet(app, api)
|
||||
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:
|
||||
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"]):
|
||||
raise ValueError("Native replacement verification changed after completion")
|
||||
report["stage"] = "native_replace_applied"
|
||||
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["stage"] = "native_replace_verified"
|
||||
finally:
|
||||
if dialog and win32gui.IsWindow(dialog):
|
||||
close_button = dlg_item(dialog, 1696)
|
||||
if close_button and win32gui.IsWindowEnabled(close_button):
|
||||
click(close_button)
|
||||
|
||||
|
||||
def save_report(snapshot, report):
|
||||
report_path = Path(str(snapshot) + ".native.json")
|
||||
error_path = Path(str(snapshot) + ".native.error.txt")
|
||||
atomic_text(report_path, json.dumps(report, ensure_ascii=False, indent=2))
|
||||
if report.get("ok"):
|
||||
error_path.unlink(missing_ok=True)
|
||||
elif report.get("error"):
|
||||
atomic_text(error_path, str(report["error"]))
|
||||
|
||||
|
||||
def atomic_text(path, text):
|
||||
path = Path(path)
|
||||
temporary = path.with_name(f".{path.name}.{os.getpid()}.{threading.get_ident()}.tmp")
|
||||
try:
|
||||
with temporary.open("w", encoding="utf-8", newline="") as handle:
|
||||
handle.write(text)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def run(snapshot):
|
||||
snapshot = Path(snapshot)
|
||||
report_path = Path(str(snapshot) + ".native.json")
|
||||
report = {}
|
||||
if report_path.is_file():
|
||||
try:
|
||||
previous = json.loads(report_path.read_text(encoding="utf-8"))
|
||||
if isinstance(previous, dict):
|
||||
report.update(previous)
|
||||
except (OSError, UnicodeError, json.JSONDecodeError):
|
||||
pass
|
||||
report.setdefault("stage", "preflight")
|
||||
report.update(snapshot=str(snapshot), ok=False)
|
||||
report.pop("error", None)
|
||||
report.pop("traceback", None)
|
||||
def timeout():
|
||||
report.update(ok=False, error="Native helper timed out; inspect schematic before retrying")
|
||||
save_report(snapshot, report)
|
||||
os._exit(2)
|
||||
watchdog = threading.Timer(120, timeout)
|
||||
watchdog.daemon = True
|
||||
watchdog.start()
|
||||
try:
|
||||
run_native(snapshot, report)
|
||||
report["ok"] = True
|
||||
return 0
|
||||
except Exception as error:
|
||||
report["error"] = f"{type(error).__name__}: {error}"
|
||||
report["traceback"] = traceback.format_exc()
|
||||
return 1
|
||||
finally:
|
||||
watchdog.cancel()
|
||||
save_report(snapshot, report)
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--snapshot", required=True, type=Path)
|
||||
args = parser.parse_args(argv)
|
||||
return run(args.snapshot)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,215 @@
|
||||
"""Reconcile an interrupted queue without repeating a native replacement."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .native_helper import read_snapshot, require_resumable_transaction
|
||||
from .quick_run import (
|
||||
TERMINAL_STATES, IDLE_PROGRESS_TIMEOUT_SECONDS, QuickRunStepResult,
|
||||
_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,
|
||||
)
|
||||
from .retention import maintain_quick_run_storage
|
||||
from .schematic_backup import create_schematic_backup
|
||||
|
||||
|
||||
_REPARSE_POINT = getattr(stat, 'FILE_ATTRIBUTE_REPARSE_POINT', 0x400)
|
||||
|
||||
|
||||
def _is_link_or_reparse(path: Path) -> bool:
|
||||
details = path.lstat()
|
||||
return stat.S_ISLNK(details.st_mode) or bool(
|
||||
getattr(details, 'st_file_attributes', 0) & _REPARSE_POINT
|
||||
)
|
||||
|
||||
|
||||
def _hashes(
|
||||
root: Path,
|
||||
*,
|
||||
link_error_code: str = 'quick_run_recovery',
|
||||
link_error_message: str = '恢复备份中发现链接目录或文件,已停止。',
|
||||
) -> dict[str, str]:
|
||||
result = {}
|
||||
for path in sorted(root.rglob('*')):
|
||||
if _is_link_or_reparse(path):
|
||||
raise TaskCenterError(link_error_code, link_error_message)
|
||||
if path.is_file():
|
||||
with path.open('rb') as stream:
|
||||
result[path.relative_to(root).as_posix()] = hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
return result
|
||||
|
||||
|
||||
def _recovery_hashes(root: Path) -> dict[str, str]:
|
||||
try:
|
||||
return _hashes(root)
|
||||
except OSError as error:
|
||||
raise TaskCenterError(
|
||||
'quick_run_recovery',
|
||||
f'无法读取恢复范围:{root};工程仍被 DxDesigner 或其他程序占用。请关闭占用后重试,保护状态未解除。',
|
||||
) from error
|
||||
|
||||
|
||||
def _recovery_copytree(source: Path, destination: Path) -> None:
|
||||
try:
|
||||
shutil.copytree(source, destination)
|
||||
except OSError as error:
|
||||
raise TaskCenterError(
|
||||
'quick_run_recovery',
|
||||
f'无法建立恢复备份:{source};工程仍被 DxDesigner 或其他程序占用。请关闭占用后重试,保护状态未解除。',
|
||||
) from error
|
||||
|
||||
|
||||
def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=False, confirmed=False):
|
||||
if not confirmed:
|
||||
raise TaskCenterError('quick_run_recovery_confirmation', '核验恢复需要明确确认,不能作为自动重试执行。')
|
||||
maintain_quick_run_storage(preparer._data_root)
|
||||
root = preparer._data_root / 'quick-run'
|
||||
uncertain = root / 'uncertain.flag'
|
||||
if not preparer.has_interrupted(task_id):
|
||||
raise TaskCenterError('quick_run_recovery', '当前没有待核验的中断保护记录。')
|
||||
commands = _read_commands(root / 'command.tsv')
|
||||
before = _read_status_details(root / 'status.tsv')
|
||||
selected_projects = tuple(project for project in projects if project.selected and project.available)
|
||||
enabled_rules = tuple(rule for rule in rules if rule.enabled)
|
||||
mode = _queue_value_mode(root / 'command.tsv')
|
||||
if {command[0] for command in commands} != {task_id} or not _queue_matches_inputs(
|
||||
root / 'command.tsv', commands, selected_projects, enabled_rules):
|
||||
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)
|
||||
if selected is None:
|
||||
raise TaskCenterError('quick_run_recovery', '队列记录已完成但仍有保护锁,需要单独核对,未自动解除。')
|
||||
job_id = _safe_run_token(selected[1])
|
||||
selected_mode, selected_custom_value, selected_sync_nc, selected_base_mode = _read_command_options(
|
||||
root / 'command.tsv'
|
||||
)[job_id]
|
||||
sheet_targets = _read_command_sheet_targets(root / 'command.tsv')
|
||||
selected_sheet = sheet_targets.get(job_id) if sheet_targets is not None else None
|
||||
latest = {entry[0]: entry[1] for entry in before}
|
||||
if any(state not in TERMINAL_STATES for other, state in latest.items() if other != job_id):
|
||||
raise TaskCenterError('quick_run_recovery', '存在多个未确认步骤,不能只核验一项后解除全局保护。')
|
||||
snapshot = root / f'snapshot-{job_id}.tsv'
|
||||
try:
|
||||
metadata, components = read_snapshot(snapshot)
|
||||
snapshot_options = (
|
||||
(metadata[5], metadata[6], metadata[7])
|
||||
if len(metadata) == 8
|
||||
else (metadata[5], '', '1')
|
||||
)
|
||||
if len(metadata) not in {6, 8} 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')
|
||||
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]
|
||||
if any(not value or any(character in value for character in '\t\r\n') for value in identity):
|
||||
raise ValueError('invalid library identity')
|
||||
except (OSError, ValueError, KeyError, TypeError) as error:
|
||||
raise TaskCenterError('quick_run_recovery', '快照或原生替换证据无法与此任务绑定,保护状态保持不变。') from error
|
||||
if not uncertain.is_file():
|
||||
_write_uncertain_flag(uncertain, 'recovery_in_progress')
|
||||
try:
|
||||
project = Path(selected[2]).resolve(strict=True)
|
||||
except OSError as error:
|
||||
raise TaskCenterError('quick_run_recovery', '中断队列对应的工程不存在或无法访问,保护状态未解除。') from error
|
||||
if root.resolve().is_relative_to(project.parent):
|
||||
raise TaskCenterError('quick_run_recovery', '工程目录包含任务数据目录,无法安全建立恢复备份。')
|
||||
audit = preparer._data_root / 'quick-run-history' / ('recovery-' + uuid4().hex)
|
||||
worker = audit / 'worker'
|
||||
worker.mkdir(parents=True, exist_ok=False)
|
||||
evidence_before = _recovery_hashes(root)
|
||||
_recovery_copytree(root, audit / 'evidence-before')
|
||||
try:
|
||||
project_backup = create_schematic_backup(
|
||||
preparer._data_root,
|
||||
project,
|
||||
audit / 'project-backup',
|
||||
error_code='quick_run_recovery',
|
||||
)
|
||||
except OSError as error:
|
||||
raise TaskCenterError(
|
||||
'quick_run_recovery',
|
||||
f'无法建立原理图精简恢复备份:{project};请关闭占用后重试,保护状态未解除。',
|
||||
) from error
|
||||
project_before = project_backup.fingerprints
|
||||
if _recovery_hashes(audit / 'evidence-before') != evidence_before or _recovery_hashes(root) != evidence_before:
|
||||
raise TaskCenterError('quick_run_recovery', '备份期间执行证据变化,已停止。')
|
||||
script = worker / 'QuickPartReplace.vbs'
|
||||
shutil.copyfile(preparer._required_script_source(), script)
|
||||
shutil.copyfile(snapshot, worker / snapshot.name)
|
||||
(worker / 'recovery.request').write_text(job_id, encoding='ascii')
|
||||
option_fields = (selected_mode, selected_custom_value, '1' if selected_sync_nc else '0', selected_base_mode)
|
||||
if selected_sheet is None:
|
||||
header = 'task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode\trecovery_part_name\trecovery_part_label'
|
||||
row = (*selected, *option_fields, *identity)
|
||||
else:
|
||||
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')
|
||||
(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),
|
||||
*_native_helper_launch_arguments(), job_id)
|
||||
try:
|
||||
result = preparer._process_runner(launch, IDLE_PROGRESS_TIMEOUT_SECONDS)
|
||||
except (OSError, subprocess.SubprocessError) as error:
|
||||
raise TaskCenterError('quick_run_recovery', '恢复执行未能确认结束,原保护锁仍在;不要重新替换或删除证据。') from error
|
||||
(audit / 'worker-output.txt').write_text(result.stdout + '\n' + result.stderr, encoding='utf-8')
|
||||
after = _read_status_details(worker / 'status.tsv')
|
||||
if result.returncode != 0 or len(after) != 1 or after[0][0] != job_id or after[0][1] not in {'restored_ok', 'retry_ready'}:
|
||||
detail = result.stderr.strip() or result.stdout.strip() or (after[-1][3] if after else '没有返回匹配的核验结果')
|
||||
raise TaskCenterError('quick_run_recovery', '恢复未通过,保护状态保留:' + detail[-2000:])
|
||||
if _recovery_hashes(root) != evidence_before or (worker / snapshot.name).read_bytes() != snapshot.read_bytes():
|
||||
raise TaskCenterError('quick_run_recovery', '核验期间原始证据变化,未提交恢复结果。')
|
||||
state = after[0][1]
|
||||
command_bytes = (root / 'command.tsv').read_bytes()
|
||||
status_bytes = (root / 'status.tsv').read_bytes()
|
||||
recovery_record = {'task_id': task_id, 'job_id': job_id, 'state': state, 'worker_result': after[0],
|
||||
'snapshot_sha256': binding['snapshot_sha256'], 'evidence_before': evidence_before,
|
||||
'project_before': project_before, 'native_replacement_called': False}
|
||||
(audit / 'recovery.json').write_text(json.dumps(recovery_record, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
try:
|
||||
if state == 'retry_ready':
|
||||
lines = (root / 'command.tsv').read_text(encoding='utf-8-sig').splitlines()
|
||||
column = lines[0].split('\t').index('job_id')
|
||||
retry_id = uuid4().hex + '_retry'
|
||||
for index in range(1, len(lines)):
|
||||
fields = lines[index].split('\t')
|
||||
if fields[column] == job_id:
|
||||
fields[column] = retry_id
|
||||
lines[index] = '\t'.join(fields)
|
||||
temporary = root / ('command-' + uuid4().hex + '.tmp')
|
||||
temporary.write_text('\n'.join(lines) + '\n', encoding='utf-8')
|
||||
os.replace(temporary, root / 'command.tsv')
|
||||
_write_status_details(root / 'status.tsv', tuple(entry for entry in before if entry[0] != job_id))
|
||||
else:
|
||||
_write_status_details(root / 'status.tsv', (*before, after[0]))
|
||||
os.replace(uncertain, audit / 'resolved-uncertain.flag')
|
||||
except Exception:
|
||||
(root / 'command.tsv').write_bytes(command_bytes)
|
||||
(root / 'status.tsv').write_bytes(status_bytes)
|
||||
if not uncertain.exists():
|
||||
uncertain.write_text('recovery commit interrupted; reconciliation required', encoding='ascii')
|
||||
raise
|
||||
progress = preparer.progress(task_id, projects, rules, copy_part_number_to_value=copy_part_number_to_value)
|
||||
message = ('磁盘工程与替换前快照一致,只读核验工程已关闭,已准备新的执行编号;尚未再次替换,请确认后执行。'
|
||||
if state == 'retry_ready' 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,
|
||||
progress.next_schematic_name, progress.next_sheet_number)
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Bounded retention for quick-run logs and generated history."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
|
||||
|
||||
QUICK_RUN_LOG_MAX_BYTES = 5 * 1024 * 1024
|
||||
QUICK_RUN_LOG_BACKUPS = 3
|
||||
HISTORY_MAX_AGE_DAYS = 30
|
||||
HISTORY_MAX_ENTRIES = 100
|
||||
HISTORY_MAX_BYTES = 5 * 1024 * 1024 * 1024
|
||||
HISTORY_MIN_ENTRIES = 10
|
||||
_HISTORY_NAME = re.compile(r"(?:batch|recovery|sheet-discovery|obsolete)-[A-Za-z0-9-]+\Z")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RetentionResult:
|
||||
removed_entries: tuple[str, ...] = ()
|
||||
removed_bytes: int = 0
|
||||
skipped_entries: tuple[str, ...] = ()
|
||||
|
||||
|
||||
def rotate_text_log(
|
||||
path: Path,
|
||||
*,
|
||||
max_bytes: int = QUICK_RUN_LOG_MAX_BYTES,
|
||||
backup_count: int = QUICK_RUN_LOG_BACKUPS,
|
||||
) -> bool:
|
||||
path = Path(path)
|
||||
if max_bytes < 1 or backup_count < 1:
|
||||
raise ValueError("log retention limits must be positive")
|
||||
if not path.exists() or path.stat().st_size <= max_bytes:
|
||||
return False
|
||||
if _is_link(path):
|
||||
raise OSError(f"refusing to rotate linked log: {path}")
|
||||
oldest = path.with_name(f"{path.name}.{backup_count}")
|
||||
if oldest.exists():
|
||||
if _is_link(oldest):
|
||||
raise OSError(f"refusing to rotate linked log backup: {oldest}")
|
||||
oldest.unlink()
|
||||
for index in range(backup_count - 1, 0, -1):
|
||||
source = path.with_name(f"{path.name}.{index}")
|
||||
destination = path.with_name(f"{path.name}.{index + 1}")
|
||||
if not source.exists():
|
||||
continue
|
||||
if _is_link(source):
|
||||
raise OSError(f"refusing to rotate linked log backup: {source}")
|
||||
os.replace(source, destination)
|
||||
os.replace(path, path.with_name(f"{path.name}.1"))
|
||||
return True
|
||||
|
||||
|
||||
def maintain_quick_run_storage(
|
||||
data_root: Path,
|
||||
*,
|
||||
now: float | None = None,
|
||||
max_age_days: int = HISTORY_MAX_AGE_DAYS,
|
||||
max_entries: int = HISTORY_MAX_ENTRIES,
|
||||
max_bytes: int = HISTORY_MAX_BYTES,
|
||||
min_entries: int = HISTORY_MIN_ENTRIES,
|
||||
) -> RetentionResult:
|
||||
if min_entries < 0 or max_entries < min_entries or max_bytes < 0 or max_age_days < 0:
|
||||
raise ValueError("invalid quick-run history retention limits")
|
||||
root = Path(data_root)
|
||||
rotate_text_log(root / "quick-run" / "quick-part-replace.log")
|
||||
history = root / "quick-run-history"
|
||||
if not history.is_dir() or _is_link(history):
|
||||
return RetentionResult()
|
||||
|
||||
canonical_history = history.resolve()
|
||||
entries: list[tuple[Path, int, int]] = []
|
||||
skipped: list[str] = []
|
||||
for candidate in history.iterdir():
|
||||
if not candidate.is_dir() or _HISTORY_NAME.fullmatch(candidate.name) is None:
|
||||
continue
|
||||
try:
|
||||
if _is_link(candidate) or candidate.resolve().parent != canonical_history:
|
||||
raise OSError("linked or redirected history entry")
|
||||
entries.append((candidate, candidate.stat().st_mtime_ns, _tree_size(candidate)))
|
||||
except OSError:
|
||||
skipped.append(candidate.name)
|
||||
|
||||
entries.sort(key=lambda entry: (entry[1], entry[0].name))
|
||||
remaining_count = len(entries)
|
||||
remaining_bytes = sum(entry[2] for entry in entries)
|
||||
cutoff_ns = int(((time.time() if now is None else now) - max_age_days * 86400) * 1_000_000_000)
|
||||
removed: list[str] = []
|
||||
removed_bytes = 0
|
||||
for candidate, modified_ns, size in entries:
|
||||
if remaining_count <= min_entries:
|
||||
break
|
||||
if not (
|
||||
modified_ns < cutoff_ns
|
||||
or remaining_count > max_entries
|
||||
or remaining_bytes > max_bytes
|
||||
):
|
||||
break
|
||||
try:
|
||||
if _is_link(candidate) or candidate.resolve().parent != canonical_history:
|
||||
raise OSError("history entry changed during retention")
|
||||
shutil.rmtree(candidate)
|
||||
except OSError:
|
||||
skipped.append(candidate.name)
|
||||
continue
|
||||
removed.append(candidate.name)
|
||||
removed_bytes += size
|
||||
remaining_count -= 1
|
||||
remaining_bytes -= size
|
||||
return RetentionResult(tuple(removed), removed_bytes, tuple(dict.fromkeys(skipped)))
|
||||
|
||||
|
||||
def _tree_size(root: Path) -> int:
|
||||
total = 0
|
||||
for path in root.rglob("*"):
|
||||
if _is_link(path):
|
||||
raise OSError(f"linked history content: {path}")
|
||||
if path.is_file():
|
||||
total += path.stat().st_size
|
||||
return total
|
||||
|
||||
|
||||
def _is_link(path: Path) -> bool:
|
||||
return path.is_symlink() or bool(getattr(path, "is_junction", lambda: False)())
|
||||
@@ -0,0 +1,777 @@
|
||||
"""Durable, one-project-at-a-time execution for replacement trials."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from dx_productivity.part_replace.models import MappingRule
|
||||
|
||||
from .comparison import ProjectComparison, compare_profiles
|
||||
from .errors import TaskCenterError
|
||||
from .evidence import ProbeStamp, capture_profile, load_captured_profile, profile_stamp
|
||||
from .logging_setup import LoggingContext, append_task_event
|
||||
from .models import ProjectRecord, ProjectStatus, RuleRecord, TaskRecord, TaskStatus
|
||||
from .store import AttemptContext, TaskStore
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class OperatorRule:
|
||||
"""One verified source-to-target replacement instruction."""
|
||||
|
||||
old_part_number: str
|
||||
new_part_number: str
|
||||
match_count: int
|
||||
logical_identities: tuple[str, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class OperatorInstruction:
|
||||
"""The native DxDesigner action the operator must perform next."""
|
||||
|
||||
project_id: str
|
||||
project_path: Path
|
||||
rules: tuple[OperatorRule, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RunnerSnapshot:
|
||||
"""Immutable state passed from a worker to the UI."""
|
||||
|
||||
task: TaskRecord
|
||||
projects: tuple[ProjectRecord, ...]
|
||||
active_project: ProjectRecord | None
|
||||
instruction: OperatorInstruction | None
|
||||
evidence_directory: Path | None
|
||||
|
||||
|
||||
class TrialRunner:
|
||||
"""State machine that makes machine comparison the sole success path."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
store: TaskStore,
|
||||
logging_context: LoggingContext,
|
||||
*,
|
||||
probe_source_resolver: Callable[[TaskRecord, ProjectRecord], Path] | None = None,
|
||||
) -> None:
|
||||
self._store = store
|
||||
self._logging = logging_context
|
||||
self._probe_source_resolver = probe_source_resolver or self._default_probe_source
|
||||
migration_recoveries = self._store.pending_migration_recoveries()
|
||||
for recovery in migration_recoveries:
|
||||
self._event_transition(
|
||||
recovery.task_id,
|
||||
recovery.project_id,
|
||||
"recover_v1_attemptless_work",
|
||||
recovery.project_before.value,
|
||||
recovery.project_after.value,
|
||||
"recording v1 migration recovery",
|
||||
recovery.error_id,
|
||||
"before",
|
||||
recovery_event_id=f"v1-attemptless:{recovery.project_id}:project:before",
|
||||
)
|
||||
for recovery in migration_recoveries:
|
||||
if recovery.task_before is not None and recovery.task_after is not None:
|
||||
self._event_transition(
|
||||
recovery.task_id,
|
||||
None,
|
||||
"recover_v1_attemptless_work",
|
||||
recovery.task_before.value,
|
||||
recovery.task_after.value,
|
||||
"recording v1 migration task recovery",
|
||||
recovery.error_id,
|
||||
"before",
|
||||
recovery_event_id=f"v1-attemptless:{recovery.project_id}:task:before",
|
||||
)
|
||||
for recovery in migration_recoveries:
|
||||
self._event_transition(
|
||||
recovery.task_id,
|
||||
recovery.project_id,
|
||||
"recover_v1_attemptless_work",
|
||||
recovery.project_before.value,
|
||||
recovery.project_after.value,
|
||||
recovery.project_summary,
|
||||
recovery.error_id,
|
||||
"after",
|
||||
recovery_event_id=f"v1-attemptless:{recovery.project_id}:project:after",
|
||||
)
|
||||
for recovery in migration_recoveries:
|
||||
if recovery.task_before is not None and recovery.task_after is not None:
|
||||
self._event_transition(
|
||||
recovery.task_id,
|
||||
None,
|
||||
"recover_v1_attemptless_work",
|
||||
recovery.task_before.value,
|
||||
recovery.task_after.value,
|
||||
recovery.task_summary or "migration interrupted active project; retry the project",
|
||||
recovery.error_id,
|
||||
"after",
|
||||
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
|
||||
)
|
||||
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(
|
||||
project.task_id,
|
||||
project.project_id,
|
||||
"recover_interrupted_work",
|
||||
project.status.value,
|
||||
ProjectStatus.FAILED.value,
|
||||
"recovering interrupted project",
|
||||
None,
|
||||
"before",
|
||||
)
|
||||
for task_id in running_task_ids:
|
||||
self._event_transition(
|
||||
task_id,
|
||||
None,
|
||||
"recover_interrupted_work",
|
||||
TaskStatus.RUNNING.value,
|
||||
TaskStatus.PAUSED.value,
|
||||
"recovering interrupted task",
|
||||
None,
|
||||
"before",
|
||||
)
|
||||
recovered_project_ids = self._store.recover_interrupted_work()
|
||||
for project_id in recovered_project_ids:
|
||||
project = self._project(project_id)
|
||||
self._event_transition(
|
||||
project.task_id,
|
||||
project_id,
|
||||
"recover_interrupted_work",
|
||||
next(item.status.value for item in interrupted if item.project_id == project_id),
|
||||
ProjectStatus.FAILED.value,
|
||||
project.summary,
|
||||
project.error_id,
|
||||
"after",
|
||||
)
|
||||
for task_id in running_task_ids:
|
||||
task = self._store.get_task(task_id)
|
||||
self._event_transition(
|
||||
task_id,
|
||||
None,
|
||||
"recover_interrupted_work",
|
||||
TaskStatus.RUNNING.value,
|
||||
task.status.value,
|
||||
task.summary,
|
||||
task.error_id,
|
||||
"after",
|
||||
)
|
||||
for task in self._store.list_tasks(TaskStatus.RUNNING):
|
||||
self._complete_if_terminal(task.task_id)
|
||||
|
||||
def start_task(self, task_id: str, *, disposable_copy_confirmed: bool) -> RunnerSnapshot:
|
||||
if not disposable_copy_confirmed:
|
||||
raise TaskCenterError("disposable_copy_required", "confirm that selected projects are disposable copies")
|
||||
task = self._store.get_task(task_id)
|
||||
selected = self._selected_available(task_id)
|
||||
if not selected:
|
||||
raise TaskCenterError("selected_project_required", "select at least one available project")
|
||||
if not any(rule.enabled for rule in self._store.list_rules(task_id)):
|
||||
raise TaskCenterError("enabled_rule_required", "add at least one enabled mapping rule")
|
||||
if task.status is not TaskStatus.RUNNING and self._store.has_active_project():
|
||||
raise TaskCenterError("active_project_exists", "another project is already active")
|
||||
if task.status is not TaskStatus.RUNNING:
|
||||
self._set_task(task_id, TaskStatus.RUNNING, "start_task", "trial started")
|
||||
self._activate_next(task_id)
|
||||
return self.snapshot(task_id)
|
||||
|
||||
def capture_before(self, task_id: str, project_id: str, probe_path: Path) -> RunnerSnapshot:
|
||||
project = self._active_project(task_id, project_id, ProjectStatus.CAPTURING_BEFORE)
|
||||
try:
|
||||
context = self._require_attempt(project)
|
||||
captured = capture_profile(
|
||||
probe_path,
|
||||
self._evidence_directory(project) / "before.json",
|
||||
project.path,
|
||||
self._probe_stamp(context.baseline_size, context.baseline_sha256, context.baseline_modified_ns),
|
||||
)
|
||||
profile = dict(captured.data)
|
||||
if not compare_profiles(profile, profile, ()).passed:
|
||||
raise TaskCenterError("before_profile_invalid", "before profile contains invalid protected evidence")
|
||||
instruction = OperatorInstruction(
|
||||
project_id=project_id,
|
||||
project_path=project.path,
|
||||
rules=self._operator_rules(profile, self._attempt_rules(context)),
|
||||
)
|
||||
self._event_transition(
|
||||
task_id,
|
||||
project_id,
|
||||
"save_attempt_before",
|
||||
ProjectStatus.CAPTURING_BEFORE.value,
|
||||
ProjectStatus.CAPTURING_BEFORE.value,
|
||||
"persisting before evidence and operator instruction",
|
||||
None,
|
||||
"before",
|
||||
)
|
||||
self._store.save_attempt_before(
|
||||
project_id,
|
||||
before_path=captured.destination,
|
||||
before_size=captured.stamp.size,
|
||||
before_sha256=captured.stamp.sha256,
|
||||
before_modified_ns=captured.stamp.modified_ns,
|
||||
instruction_json=self._instruction_json(instruction),
|
||||
)
|
||||
self._event_transition(
|
||||
task_id,
|
||||
project_id,
|
||||
"save_attempt_before",
|
||||
ProjectStatus.CAPTURING_BEFORE.value,
|
||||
ProjectStatus.CAPTURING_BEFORE.value,
|
||||
"persisted before evidence and operator instruction",
|
||||
None,
|
||||
"after",
|
||||
)
|
||||
self._set_project(project, ProjectStatus.AWAITING_OPERATOR, "capture_before", "before profile captured")
|
||||
except TaskCenterError as error:
|
||||
self._fail_project(task_id, project, "capture_before", error)
|
||||
raise
|
||||
return self.snapshot(task_id)
|
||||
|
||||
def confirm_native_attempt(self, task_id: str, project_id: str) -> RunnerSnapshot:
|
||||
project = self._active_project(task_id, project_id, ProjectStatus.AWAITING_OPERATOR)
|
||||
append_task_event(
|
||||
self._logging,
|
||||
level="INFO",
|
||||
task_id=task_id,
|
||||
project_id=project_id,
|
||||
operation="confirm_native_attempt",
|
||||
state_before=project.status.value,
|
||||
state_after=project.status.value,
|
||||
message="operator asserted that native replacement was attempted",
|
||||
)
|
||||
return self.snapshot(task_id)
|
||||
|
||||
def capture_after(self, task_id: str, project_id: str, probe_path: Path) -> RunnerSnapshot:
|
||||
project = self._active_project(task_id, project_id, ProjectStatus.AWAITING_OPERATOR, allow_paused=True)
|
||||
try:
|
||||
context = self._require_attempt(project, require_before=True)
|
||||
self._set_project(project, ProjectStatus.CAPTURING_AFTER, "capture_after", "capturing after profile")
|
||||
project = self._project(project_id)
|
||||
captured = capture_profile(
|
||||
probe_path,
|
||||
self._evidence_directory(project) / "after.json",
|
||||
project.path,
|
||||
self._probe_stamp(context.before_size, context.before_sha256, context.before_modified_ns),
|
||||
)
|
||||
self._set_project(project, ProjectStatus.VERIFYING, "capture_after", "verifying captured profiles")
|
||||
project = self._project(project_id)
|
||||
before_profile = load_captured_profile(
|
||||
context.before_path,
|
||||
project.path,
|
||||
self._probe_stamp(context.before_size, context.before_sha256, context.before_modified_ns),
|
||||
)
|
||||
comparison = compare_profiles(
|
||||
before_profile,
|
||||
captured.data,
|
||||
self._attempt_rules(context),
|
||||
)
|
||||
self._write_comparison(project, comparison)
|
||||
if not comparison.passed:
|
||||
raise TaskCenterError("comparison_failed", "captured profiles did not pass verification")
|
||||
self._set_project(project, ProjectStatus.COMPLETED, "compare_profiles", "comparison passed")
|
||||
except TaskCenterError as error:
|
||||
current = self._project(project_id)
|
||||
if current.status not in {ProjectStatus.FAILED, ProjectStatus.COMPLETED, ProjectStatus.SKIPPED}:
|
||||
self._fail_project(task_id, current, "capture_after", error)
|
||||
if current.status is ProjectStatus.COMPLETED:
|
||||
self._reconcile_task(task_id)
|
||||
raise
|
||||
if self._store.get_task(task_id).status is TaskStatus.RUNNING:
|
||||
self._activate_next(task_id)
|
||||
self._complete_if_terminal(task_id)
|
||||
return self.snapshot(task_id)
|
||||
|
||||
def pause_task(self, task_id: str) -> RunnerSnapshot:
|
||||
task = self._store.get_task(task_id)
|
||||
if task.status is not TaskStatus.RUNNING:
|
||||
raise TaskCenterError("task_not_running", "only a running task can be paused")
|
||||
self._set_task(task_id, TaskStatus.PAUSED, "pause_task", "trial paused")
|
||||
return self.snapshot(task_id)
|
||||
|
||||
def resume_task(self, task_id: str) -> RunnerSnapshot:
|
||||
task = self._store.get_task(task_id)
|
||||
if task.status is not TaskStatus.PAUSED:
|
||||
raise TaskCenterError("task_not_paused", "only a paused task can be resumed")
|
||||
projects = self._store.list_projects(task_id)
|
||||
active = next((project for project in projects if project.status in self._active_project_states()), None)
|
||||
pending = next(
|
||||
(project for project in projects if project.selected and project.available and project.status is ProjectStatus.PENDING),
|
||||
None,
|
||||
)
|
||||
if active is not None:
|
||||
self._set_task(task_id, TaskStatus.RUNNING, "resume_task", "trial resumed")
|
||||
elif pending is not None:
|
||||
self._claim_attempt(task, pending, "resume_task", "trial resumed", "project selected after resume")
|
||||
else:
|
||||
self._set_task(task_id, TaskStatus.RUNNING, "resume_task", "trial resumed")
|
||||
self._complete_if_terminal(task_id)
|
||||
return self.snapshot(task_id)
|
||||
|
||||
def retry_project(self, task_id: str, project_id: str) -> RunnerSnapshot:
|
||||
project = self._require_project(task_id, project_id)
|
||||
if project.status is not ProjectStatus.FAILED:
|
||||
raise TaskCenterError("project_not_retryable", "only a failed project can be retried")
|
||||
task = self._store.get_task(task_id)
|
||||
if task.status not in {TaskStatus.FAILED, TaskStatus.PAUSED, TaskStatus.RUNNING}:
|
||||
raise TaskCenterError("task_not_retryable", "task cannot start a retry from its current state")
|
||||
self._claim_attempt(task, project, "retry_project", "retry started", "project selected for retry")
|
||||
return self.snapshot(task_id)
|
||||
|
||||
def skip_project(self, task_id: str, project_id: str) -> RunnerSnapshot:
|
||||
project = self._require_project(task_id, project_id)
|
||||
if project.status in {ProjectStatus.COMPLETED, ProjectStatus.SKIPPED}:
|
||||
raise TaskCenterError("project_not_skippable", "a terminal project cannot be skipped")
|
||||
task = self._store.get_task(task_id)
|
||||
if task.status is TaskStatus.FAILED:
|
||||
self._set_task(task_id, TaskStatus.PAUSED, "skip_project", "resolving failed project")
|
||||
self._set_task(task_id, TaskStatus.RUNNING, "skip_project", "finishing queue")
|
||||
if project.status is not ProjectStatus.PENDING and project.status is not ProjectStatus.FAILED:
|
||||
# The persisted state graph requires an audit-visible failure before a live capture can be skipped.
|
||||
self._set_project(project, ProjectStatus.FAILED, "skip_project", "operator stopped project before verification")
|
||||
project = self._project(project_id)
|
||||
self._set_project(project, ProjectStatus.SKIPPED, "skip_project", "project skipped by operator")
|
||||
if self._store.get_task(task_id).status is TaskStatus.RUNNING:
|
||||
self._activate_next(task_id)
|
||||
self._complete_if_terminal(task_id)
|
||||
return self.snapshot(task_id)
|
||||
|
||||
def set_project_selected(self, task_id: str, project_id: str, selected: bool) -> RunnerSnapshot:
|
||||
project = self._require_project(task_id, project_id)
|
||||
if not selected and project.status in {
|
||||
ProjectStatus.CAPTURING_BEFORE,
|
||||
ProjectStatus.AWAITING_OPERATOR,
|
||||
ProjectStatus.CAPTURING_AFTER,
|
||||
ProjectStatus.VERIFYING,
|
||||
}:
|
||||
raise TaskCenterError("active_project_selection", "pause or finish the active project before clearing selection")
|
||||
self._store.set_project_selected(project_id, selected)
|
||||
self._reconcile_task(task_id)
|
||||
return self.snapshot(task_id)
|
||||
|
||||
def set_projects_selected(
|
||||
self,
|
||||
task_id: str,
|
||||
selected: bool,
|
||||
*,
|
||||
available_only: bool = False,
|
||||
) -> RunnerSnapshot:
|
||||
projects = self._store.list_projects(task_id)
|
||||
if not selected and any(
|
||||
project.status in self._active_project_states()
|
||||
and (not available_only or project.available)
|
||||
for project in projects
|
||||
):
|
||||
raise TaskCenterError("active_project_selection", "pause or finish the active project before clearing selection")
|
||||
self._store.set_projects_selected(task_id, selected, available_only=available_only)
|
||||
self._reconcile_task(task_id)
|
||||
return self.snapshot(task_id)
|
||||
|
||||
def snapshot(self, task_id: str) -> RunnerSnapshot:
|
||||
task = self._store.get_task(task_id)
|
||||
projects = self._store.list_projects(task_id)
|
||||
active = next(
|
||||
(
|
||||
project
|
||||
for project in projects
|
||||
if project.status in {
|
||||
ProjectStatus.CAPTURING_BEFORE,
|
||||
ProjectStatus.AWAITING_OPERATOR,
|
||||
ProjectStatus.CAPTURING_AFTER,
|
||||
ProjectStatus.VERIFYING,
|
||||
}
|
||||
),
|
||||
None,
|
||||
)
|
||||
if task.status is TaskStatus.PAUSED:
|
||||
active = None
|
||||
return RunnerSnapshot(
|
||||
task=task,
|
||||
projects=projects,
|
||||
active_project=active,
|
||||
instruction=self._attempt_instruction(active) if active is not None else None,
|
||||
evidence_directory=self._evidence_directory(active) if active is not None else None,
|
||||
)
|
||||
|
||||
def expected_probe_path(self, task: TaskRecord, project: ProjectRecord) -> Path:
|
||||
"""Expose the configured read-only menu probe source to the service/UI."""
|
||||
return self._probe_source_resolver(task, project)
|
||||
|
||||
def _activate_next(self, task_id: str) -> None:
|
||||
if self._store.get_task(task_id).status is not TaskStatus.RUNNING:
|
||||
return
|
||||
projects = self._store.list_projects(task_id)
|
||||
if any(project.status in {ProjectStatus.CAPTURING_BEFORE, ProjectStatus.AWAITING_OPERATOR, ProjectStatus.CAPTURING_AFTER, ProjectStatus.VERIFYING} for project in projects):
|
||||
return
|
||||
next_project = next((project for project in projects if project.selected and project.available and project.status is ProjectStatus.PENDING), None)
|
||||
if next_project is not None:
|
||||
task = self._store.get_task(task_id)
|
||||
baseline_path = self._probe_source_resolver(task, next_project)
|
||||
baseline = profile_stamp(baseline_path)
|
||||
if baseline is None:
|
||||
error = TaskCenterError("probe_baseline_missing", "menu probe baseline does not exist at task start")
|
||||
self._fail_project(task_id, next_project, "activate_project", error)
|
||||
raise error
|
||||
rules_json = json.dumps(
|
||||
[
|
||||
{"old_part_number": rule.old_part_number, "new_part_number": rule.new_part_number}
|
||||
for rule in self._enabled_rules(task_id)
|
||||
],
|
||||
ensure_ascii=True,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
self._event_transition(
|
||||
task_id,
|
||||
next_project.project_id,
|
||||
"activate_project",
|
||||
ProjectStatus.PENDING.value,
|
||||
ProjectStatus.CAPTURING_BEFORE.value,
|
||||
"project selected for capture",
|
||||
None,
|
||||
"before",
|
||||
)
|
||||
started = self._store.begin_project_attempt(
|
||||
task_id,
|
||||
next_project.project_id,
|
||||
probe_source=baseline_path,
|
||||
baseline_size=baseline.size,
|
||||
baseline_sha256=baseline.sha256,
|
||||
baseline_modified_ns=baseline.modified_ns,
|
||||
rules_json=rules_json,
|
||||
)
|
||||
self._event_transition(
|
||||
task_id,
|
||||
started.project_id,
|
||||
"activate_project",
|
||||
ProjectStatus.PENDING.value,
|
||||
ProjectStatus.CAPTURING_BEFORE.value,
|
||||
"project selected for capture",
|
||||
None,
|
||||
"after",
|
||||
)
|
||||
|
||||
def _claim_attempt(
|
||||
self,
|
||||
task: TaskRecord,
|
||||
project: ProjectRecord,
|
||||
operation: str,
|
||||
task_message: str,
|
||||
project_message: str,
|
||||
) -> None:
|
||||
baseline_path = self._probe_source_resolver(task, project)
|
||||
baseline = profile_stamp(baseline_path)
|
||||
if baseline is None:
|
||||
raise TaskCenterError("probe_baseline_missing", "menu probe baseline does not exist at task start")
|
||||
rules_json = json.dumps(
|
||||
[
|
||||
{"old_part_number": rule.old_part_number, "new_part_number": rule.new_part_number}
|
||||
for rule in self._enabled_rules(task.task_id)
|
||||
],
|
||||
ensure_ascii=True,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
self._event_transition(
|
||||
task.task_id,
|
||||
None,
|
||||
operation,
|
||||
task.status.value,
|
||||
TaskStatus.RUNNING.value,
|
||||
"claiming task for a new attempt",
|
||||
None,
|
||||
"before",
|
||||
)
|
||||
self._event_transition(
|
||||
task.task_id,
|
||||
project.project_id,
|
||||
operation,
|
||||
project.status.value,
|
||||
ProjectStatus.CAPTURING_BEFORE.value,
|
||||
"claiming project for a new attempt",
|
||||
None,
|
||||
"before",
|
||||
)
|
||||
started_task, started_project = self._store.claim_project_attempt(
|
||||
task.task_id,
|
||||
project.project_id,
|
||||
expected_task_status=task.status,
|
||||
expected_project_status=project.status,
|
||||
probe_source=baseline_path,
|
||||
baseline_size=baseline.size,
|
||||
baseline_sha256=baseline.sha256,
|
||||
baseline_modified_ns=baseline.modified_ns,
|
||||
rules_json=rules_json,
|
||||
task_summary=task_message,
|
||||
project_summary=project_message,
|
||||
)
|
||||
self._event_transition(
|
||||
task.task_id,
|
||||
None,
|
||||
operation,
|
||||
task.status.value,
|
||||
started_task.status.value,
|
||||
task_message,
|
||||
None,
|
||||
"after",
|
||||
)
|
||||
self._event_transition(
|
||||
task.task_id,
|
||||
project.project_id,
|
||||
operation,
|
||||
project.status.value,
|
||||
started_project.status.value,
|
||||
project_message,
|
||||
None,
|
||||
"after",
|
||||
)
|
||||
|
||||
def _complete_if_terminal(self, task_id: str) -> None:
|
||||
task = self._store.get_task(task_id)
|
||||
if task.status is not TaskStatus.RUNNING:
|
||||
return
|
||||
terminal = {ProjectStatus.COMPLETED, ProjectStatus.SKIPPED}
|
||||
selected = self._selected_available(task_id)
|
||||
if selected and all(project.status in terminal for project in selected):
|
||||
self._set_task(task_id, TaskStatus.COMPLETED, "complete_task", "all selected projects reached terminal state")
|
||||
|
||||
def _reconcile_task(self, task_id: str) -> None:
|
||||
task = self._store.get_task(task_id)
|
||||
selected = self._selected_available(task_id)
|
||||
terminal = {ProjectStatus.COMPLETED, ProjectStatus.SKIPPED}
|
||||
if task.status is TaskStatus.FAILED:
|
||||
if not selected:
|
||||
self._set_task(task_id, TaskStatus.PAUSED, "reconcile_task", "no selected projects remain")
|
||||
return
|
||||
if all(project.status in terminal for project in selected):
|
||||
self._set_task(task_id, TaskStatus.PAUSED, "reconcile_task", "resolving selected terminal projects")
|
||||
self._set_task(task_id, TaskStatus.RUNNING, "reconcile_task", "completing selected terminal projects")
|
||||
self._complete_if_terminal(task_id)
|
||||
return
|
||||
if task.status is TaskStatus.RUNNING:
|
||||
self._activate_next(task_id)
|
||||
self._complete_if_terminal(task_id)
|
||||
|
||||
def _fail_project(self, task_id: str, project: ProjectRecord, operation: str, error: TaskCenterError) -> None:
|
||||
if project.status is not ProjectStatus.FAILED:
|
||||
self._set_project(project, ProjectStatus.FAILED, operation, error.message, error.error_id)
|
||||
task = self._store.get_task(task_id)
|
||||
if task.status in {TaskStatus.RUNNING, TaskStatus.PAUSED}:
|
||||
self._set_task(task_id, TaskStatus.FAILED, operation, error.message, error.error_id)
|
||||
|
||||
def _set_task(self, task_id: str, status: TaskStatus, operation: str, message: str, error_id: str | None = None) -> None:
|
||||
current = self._store.get_task(task_id)
|
||||
self._event_transition(task_id, None, operation, current.status.value, status.value, message, error_id, "before")
|
||||
self._store.set_task_status(task_id, status, error_id=error_id, summary=message)
|
||||
self._event_transition(task_id, None, operation, current.status.value, status.value, message, error_id, "after")
|
||||
|
||||
def _set_project(self, project: ProjectRecord, status: ProjectStatus, operation: str, message: str, error_id: str | None = None) -> None:
|
||||
self._event_transition(project.task_id, project.project_id, operation, project.status.value, status.value, message, error_id, "before")
|
||||
self._store.set_project_status(project.project_id, status, error_id=error_id, summary=message)
|
||||
self._event_transition(project.task_id, project.project_id, operation, project.status.value, status.value, message, error_id, "after")
|
||||
|
||||
def _event_transition(
|
||||
self,
|
||||
task_id: str,
|
||||
project_id: str | None,
|
||||
operation: str,
|
||||
before: str,
|
||||
after: str,
|
||||
message: str,
|
||||
error_id: str | None,
|
||||
phase: str,
|
||||
*,
|
||||
recovery_event_id: str | None = None,
|
||||
) -> None:
|
||||
details = {"phase": phase}
|
||||
if recovery_event_id is not None:
|
||||
details["recovery_event_id"] = recovery_event_id
|
||||
with self._logging._event_lock:
|
||||
if recovery_event_id is not None and self._recovery_event_is_durable(task_id, recovery_event_id):
|
||||
return
|
||||
append_task_event(
|
||||
self._logging,
|
||||
level="ERROR" if error_id else "INFO",
|
||||
task_id=task_id,
|
||||
project_id=project_id,
|
||||
operation=operation,
|
||||
state_before=before,
|
||||
state_after=after,
|
||||
error_id=error_id,
|
||||
message=message,
|
||||
details=details,
|
||||
)
|
||||
|
||||
def _recovery_event_is_durable(self, task_id: str, recovery_event_id: str) -> bool:
|
||||
path = self._logging.root / "tasks" / task_id / "events.jsonl"
|
||||
if not path.exists():
|
||||
return False
|
||||
try:
|
||||
events = (json.loads(line) for line in path.read_text(encoding="utf-8").splitlines())
|
||||
return any(
|
||||
isinstance(event.get("details"), dict)
|
||||
and event["details"].get("recovery_event_id") == recovery_event_id
|
||||
for event in events
|
||||
)
|
||||
except (OSError, UnicodeError, ValueError, TypeError) as error:
|
||||
raise TaskCenterError("event_sequence", "cannot determine prior migration recovery events") from error
|
||||
|
||||
def _active_project(self, task_id: str, project_id: str, expected: ProjectStatus, *, allow_paused: bool = False) -> ProjectRecord:
|
||||
task = self._store.get_task(task_id)
|
||||
if task.status is not TaskStatus.RUNNING and not (allow_paused and task.status is TaskStatus.PAUSED):
|
||||
raise TaskCenterError("task_not_running", "task is not accepting this action")
|
||||
project = self._require_project(task_id, project_id)
|
||||
if project.status is not expected:
|
||||
raise TaskCenterError("project_not_active", "project is not at the required trial step")
|
||||
return project
|
||||
|
||||
def _require_project(self, task_id: str, project_id: str) -> ProjectRecord:
|
||||
project = self._project(project_id)
|
||||
if project.task_id != task_id:
|
||||
raise TaskCenterError("project_task_mismatch", "project does not belong to the task")
|
||||
return project
|
||||
|
||||
def _project(self, project_id: str) -> ProjectRecord:
|
||||
return self._store.get_project(project_id)
|
||||
|
||||
def _selected_available(self, task_id: str) -> tuple[ProjectRecord, ...]:
|
||||
return tuple(project for project in self._store.list_projects(task_id) if project.selected and project.available)
|
||||
|
||||
@staticmethod
|
||||
def _active_project_states() -> frozenset[ProjectStatus]:
|
||||
return frozenset({
|
||||
ProjectStatus.CAPTURING_BEFORE,
|
||||
ProjectStatus.AWAITING_OPERATOR,
|
||||
ProjectStatus.CAPTURING_AFTER,
|
||||
ProjectStatus.VERIFYING,
|
||||
})
|
||||
|
||||
def _enabled_rules(self, task_id: str) -> tuple[RuleRecord, ...]:
|
||||
return tuple(rule for rule in self._store.list_rules(task_id) if rule.enabled)
|
||||
|
||||
def _evidence_directory(self, project: ProjectRecord) -> Path:
|
||||
path = self._logging.root / "tasks" / project.task_id / "evidence" / project.project_id / f"attempt-{project.retry_count + 1}"
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
def _require_attempt(self, project: ProjectRecord, *, require_before: bool = False) -> AttemptContext:
|
||||
context = self._store.current_attempt(project.project_id)
|
||||
if context is None:
|
||||
raise TaskCenterError("attempt_missing", "attempt context is missing; retry the project")
|
||||
if require_before and (
|
||||
context.before_path is None
|
||||
or context.before_size is None
|
||||
or context.before_sha256 is None
|
||||
or context.before_modified_ns is None
|
||||
or context.instruction_json is None
|
||||
):
|
||||
raise TaskCenterError("attempt_before_missing", "before evidence is missing; retry the project")
|
||||
return context
|
||||
|
||||
@staticmethod
|
||||
def _probe_stamp(size: int | None, sha256: str | None, modified_ns: int | None) -> ProbeStamp:
|
||||
if size is None or sha256 is None or modified_ns is None:
|
||||
raise TaskCenterError("attempt_before_missing", "attempt probe stamp is missing; retry the project")
|
||||
return ProbeStamp(int(size), int(modified_ns), str(sha256))
|
||||
|
||||
@staticmethod
|
||||
def _attempt_rules(context: AttemptContext) -> tuple[MappingRule, ...]:
|
||||
try:
|
||||
values = json.loads(context.rules_json)
|
||||
if not isinstance(values, list) or not all(isinstance(item, dict) for item in values):
|
||||
raise ValueError
|
||||
rules = tuple(MappingRule(str(item["old_part_number"]), str(item["new_part_number"])) for item in values)
|
||||
if not rules or any(not rule.old_part_number.strip() or not rule.new_part_number.strip() for rule in rules):
|
||||
raise ValueError
|
||||
return rules
|
||||
except (KeyError, TypeError, ValueError, json.JSONDecodeError) as error:
|
||||
raise TaskCenterError("attempt_rules", "attempt rule snapshot is invalid; retry the project") from error
|
||||
|
||||
@staticmethod
|
||||
def _instruction_json(instruction: OperatorInstruction) -> str:
|
||||
return json.dumps(
|
||||
{
|
||||
"project_id": instruction.project_id,
|
||||
"project_path": str(instruction.project_path),
|
||||
"rules": [
|
||||
{
|
||||
"old_part_number": rule.old_part_number,
|
||||
"new_part_number": rule.new_part_number,
|
||||
"match_count": rule.match_count,
|
||||
"logical_identities": list(rule.logical_identities),
|
||||
}
|
||||
for rule in instruction.rules
|
||||
],
|
||||
},
|
||||
ensure_ascii=True,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
|
||||
def _attempt_instruction(self, project: ProjectRecord) -> OperatorInstruction | None:
|
||||
context = self._store.current_attempt(project.project_id)
|
||||
if context is None or context.instruction_json is None:
|
||||
return None
|
||||
try:
|
||||
value = json.loads(context.instruction_json)
|
||||
rules = tuple(
|
||||
OperatorRule(
|
||||
str(rule["old_part_number"]),
|
||||
str(rule["new_part_number"]),
|
||||
int(rule["match_count"]),
|
||||
tuple(str(identity) for identity in rule["logical_identities"]),
|
||||
)
|
||||
for rule in value["rules"]
|
||||
)
|
||||
return OperatorInstruction(str(value["project_id"]), Path(str(value["project_path"])), rules)
|
||||
except (KeyError, TypeError, ValueError, json.JSONDecodeError) as error:
|
||||
raise TaskCenterError("attempt_instruction", "attempt instruction is invalid; retry the project") from error
|
||||
|
||||
def _default_probe_source(self, _task: TaskRecord, _project: ProjectRecord) -> Path:
|
||||
return self._logging.root / "runs" / "menu-compatibility-profile.json"
|
||||
|
||||
@staticmethod
|
||||
def _operator_rules(profile: dict[str, object], rules: tuple[RuleRecord, ...]) -> tuple[OperatorRule, ...]:
|
||||
components = profile.get("components", ())
|
||||
matches: list[OperatorRule] = []
|
||||
for rule in rules:
|
||||
identities: list[str] = []
|
||||
if isinstance(components, list):
|
||||
for component in components:
|
||||
if not isinstance(component, dict):
|
||||
continue
|
||||
part_number = component.get("part_number")
|
||||
identity = component.get("logical_identity")
|
||||
if isinstance(part_number, str) and isinstance(identity, str) and part_number.strip().casefold() == rule.old_part_number.strip().casefold():
|
||||
identities.append(identity)
|
||||
if identities:
|
||||
matches.append(OperatorRule(rule.old_part_number, rule.new_part_number, len(identities), tuple(sorted(identities))))
|
||||
return tuple(matches)
|
||||
|
||||
@staticmethod
|
||||
def _load_profile(path: Path) -> dict[str, object]:
|
||||
try:
|
||||
loaded = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as error:
|
||||
raise TaskCenterError("evidence_read", "cannot read captured before profile") from error
|
||||
if not isinstance(loaded, dict):
|
||||
raise TaskCenterError("evidence_read", "captured before profile is invalid")
|
||||
return loaded
|
||||
|
||||
def _write_comparison(self, project: ProjectRecord, comparison: ProjectComparison) -> None:
|
||||
path = self._evidence_directory(project) / "comparison.json"
|
||||
try:
|
||||
path.write_text(comparison.to_json(), encoding="utf-8")
|
||||
except OSError as error:
|
||||
raise TaskCenterError("comparison_write", "cannot write comparison evidence") from error
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Read-only project discovery for the trial task center."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
|
||||
from .errors import TaskCenterError
|
||||
|
||||
|
||||
def _path_identity(path: Path) -> str:
|
||||
normalized = os.path.normpath(str(path))
|
||||
return os.path.normcase(normalized) if os.name == "nt" else normalized
|
||||
|
||||
|
||||
_REPARSE_POINT = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
|
||||
_PROJECT_HEADER_LIMIT = 256 * 1024
|
||||
_DXD_FRONT_END = re.compile(rb'^\s*KEY\s+FrontEndSnapshot\s+"DxD"\s*$', re.IGNORECASE | re.MULTILINE)
|
||||
_ICDB_DIRECTORY = re.compile(rb'^\s*KEY\s+iCDBDir\s+"[^"]+"\s*$', re.IGNORECASE | re.MULTILINE)
|
||||
|
||||
|
||||
def _is_schematic_project(path: Path) -> bool:
|
||||
with path.open("rb") as project_file:
|
||||
contents = project_file.read(_PROJECT_HEADER_LIMIT)
|
||||
return bool(_DXD_FRONT_END.search(contents) and _ICDB_DIRECTORY.search(contents))
|
||||
|
||||
|
||||
def _reject_reparse(details: os.stat_result, path: Path) -> None:
|
||||
if stat.S_ISLNK(details.st_mode) or bool(getattr(details, "st_file_attributes", 0) & _REPARSE_POINT):
|
||||
raise TaskCenterError("discovery_reparse", f"discovery path contains a reparse point: {path}")
|
||||
|
||||
|
||||
def _contained(root: Path, candidate: Path) -> bool:
|
||||
try:
|
||||
candidate.relative_to(root)
|
||||
except ValueError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _lexical_path(path: Path) -> str:
|
||||
return _path_identity(Path(os.path.abspath(path)))
|
||||
|
||||
|
||||
def scan_projects(root: Path, *, excluded_roots: tuple[Path, ...] = ()) -> tuple[Path, ...]:
|
||||
"""Discover DxDesigner schematic projects without selecting or modifying them."""
|
||||
root = Path(root)
|
||||
try:
|
||||
if not root.exists() or not root.is_dir():
|
||||
raise TaskCenterError("discovery_root", f"discovery root is not a directory: {root}")
|
||||
root_details = root.lstat()
|
||||
_reject_reparse(root_details, root)
|
||||
canonical_root = root.resolve()
|
||||
excluded = tuple(_lexical_path(Path(path)) for path in excluded_roots)
|
||||
root_key = _lexical_path(root)
|
||||
if any(root_key == blocked or root_key.startswith(blocked + os.sep) for blocked in excluded):
|
||||
raise TaskCenterError("discovery_root", f"discovery root is inside task data: {root}")
|
||||
|
||||
def is_excluded(path: Path) -> bool:
|
||||
key = _lexical_path(path)
|
||||
return any(key == blocked or key.startswith(blocked + os.sep) for blocked in excluded)
|
||||
|
||||
candidates: dict[str, Path] = {}
|
||||
visited: set[tuple[int, int]] = set()
|
||||
|
||||
def read_entries(directory: Path) -> tuple[tuple[Path, os.stat_result], ...]:
|
||||
with os.scandir(directory) as entries:
|
||||
result: list[tuple[Path, os.stat_result]] = []
|
||||
for entry in sorted(entries, key=lambda item: item.name.casefold()):
|
||||
candidate = Path(entry.path)
|
||||
if is_excluded(candidate):
|
||||
continue
|
||||
entry_details = entry.stat(follow_symlinks=False)
|
||||
_reject_reparse(entry_details, candidate)
|
||||
result.append((candidate, entry_details))
|
||||
return tuple(result)
|
||||
|
||||
root_entries = read_entries(root)
|
||||
for candidate, entry_details in root_entries:
|
||||
if (
|
||||
stat.S_ISREG(entry_details.st_mode)
|
||||
and candidate.suffix.casefold() == ".prj"
|
||||
and _is_schematic_project(candidate)
|
||||
):
|
||||
canonical = candidate.resolve()
|
||||
candidates.setdefault(_path_identity(canonical), canonical)
|
||||
|
||||
if candidates:
|
||||
return tuple(sorted(candidates.values(), key=lambda path: str(path).casefold()))
|
||||
|
||||
def visit(
|
||||
directory: Path,
|
||||
directory_entries: tuple[tuple[Path, os.stat_result], ...] | None = None,
|
||||
) -> None:
|
||||
canonical_directory = directory.resolve()
|
||||
if not _contained(canonical_root, canonical_directory):
|
||||
raise TaskCenterError("discovery_containment", f"discovery path escapes its root: {directory}")
|
||||
details = directory.lstat()
|
||||
_reject_reparse(details, directory)
|
||||
identity = details.st_dev, details.st_ino
|
||||
if identity in visited:
|
||||
return
|
||||
visited.add(identity)
|
||||
entries = directory_entries if directory_entries is not None else read_entries(directory)
|
||||
for candidate, entry_details in entries:
|
||||
if stat.S_ISDIR(entry_details.st_mode):
|
||||
visit(candidate)
|
||||
elif (
|
||||
stat.S_ISREG(entry_details.st_mode)
|
||||
and candidate.suffix.casefold() == ".prj"
|
||||
and _is_schematic_project(candidate)
|
||||
):
|
||||
canonical = candidate.resolve()
|
||||
if not _contained(canonical_root, canonical):
|
||||
raise TaskCenterError("discovery_containment", f"project path escapes its root: {candidate}")
|
||||
candidates.setdefault(_path_identity(canonical), canonical)
|
||||
|
||||
visit(root, root_entries)
|
||||
return tuple(sorted(candidates.values(), key=lambda path: str(path).casefold()))
|
||||
except TaskCenterError:
|
||||
raise
|
||||
except OSError as error:
|
||||
raise TaskCenterError("discovery_access", f"cannot scan discovery root: {root}") from error
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Bounded SceneOS JSON bridge for creating and scanning Replace tasks."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from typing import Any, TextIO
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .logging_setup import configure_logging
|
||||
from .service import TaskCenterService
|
||||
from .store import TaskStore
|
||||
|
||||
|
||||
_MAX_REQUEST_CHARS = 256 * 1024
|
||||
_SOURCE = "sceneos-cli/v1"
|
||||
|
||||
|
||||
def run(data_root: Path, input_stream: TextIO | None = None, output_stream: TextIO | None = None) -> int:
|
||||
source = input_stream or sys.stdin
|
||||
target = output_stream or sys.stdout
|
||||
if source is None or target is None:
|
||||
return 2
|
||||
logging_context = configure_logging(data_root)
|
||||
store: TaskStore | None = None
|
||||
try:
|
||||
payload_text = source.read(_MAX_REQUEST_CHARS + 1)
|
||||
if len(payload_text) > _MAX_REQUEST_CHARS:
|
||||
raise TaskCenterError("sceneos_request_size", "SceneOS request is too large")
|
||||
payload = _request(json.loads(payload_text))
|
||||
input_value = payload["input"]
|
||||
context = payload["context"]
|
||||
request_hash = hashlib.sha256(
|
||||
json.dumps(input_value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
||||
).hexdigest()
|
||||
project_root = Path(input_value["projectRoot"])
|
||||
if not project_root.is_absolute():
|
||||
raise TaskCenterError("sceneos_project_root", "projectRoot must be an absolute path")
|
||||
store = TaskStore(Path(data_root) / "task-center.db")
|
||||
service = TaskCenterService(store, logging_context)
|
||||
task, projects, created = service.create_scanned_task(
|
||||
source=_SOURCE,
|
||||
idempotency_key=context["idempotencyKey"],
|
||||
request_hash=request_hash,
|
||||
name=input_value["taskName"],
|
||||
note="Created by SceneOS. Replacement rules and execution remain in DxPartReplace.",
|
||||
root=project_root,
|
||||
)
|
||||
response = {
|
||||
"taskId": task.task_id,
|
||||
"taskName": task.name,
|
||||
"status": task.status.value,
|
||||
"projectRoot": str(task.discovery_root),
|
||||
"projectCount": len(projects),
|
||||
"availableProjectCount": sum(project.available for project in projects),
|
||||
"created": created,
|
||||
}
|
||||
target.write(json.dumps(response, ensure_ascii=False, separators=(",", ":")))
|
||||
target.flush()
|
||||
return 0
|
||||
except (TaskCenterError, json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
|
||||
reported = logging_context.report_exception("sceneos_cli", error)
|
||||
target.write(json.dumps({
|
||||
"error": reported.code,
|
||||
"message": reported.message,
|
||||
"errorId": reported.error_id,
|
||||
}, ensure_ascii=False, separators=(",", ":")))
|
||||
target.flush()
|
||||
return 2
|
||||
finally:
|
||||
if store is not None:
|
||||
store.close()
|
||||
|
||||
|
||||
def _request(value: Any) -> dict[str, Any]:
|
||||
if not isinstance(value, dict) or set(value) != {"protocol", "input", "context"}:
|
||||
raise TaskCenterError("sceneos_request", "SceneOS request must contain protocol, input, and context")
|
||||
if value["protocol"] != _SOURCE:
|
||||
raise TaskCenterError("sceneos_protocol", "SceneOS CLI protocol is unsupported")
|
||||
input_value = value["input"]
|
||||
context = value["context"]
|
||||
if not isinstance(input_value, dict) or set(input_value) != {"taskName", "projectRoot"}:
|
||||
raise TaskCenterError("sceneos_input", "SceneOS input must contain taskName and projectRoot")
|
||||
if not isinstance(context, dict) or set(context) != {"runId", "stepId", "idempotencyKey"}:
|
||||
raise TaskCenterError("sceneos_context", "SceneOS context is invalid")
|
||||
for key, limit in (("taskName", 120), ("projectRoot", 2048)):
|
||||
if not isinstance(input_value[key], str) or not input_value[key].strip() or len(input_value[key]) > limit:
|
||||
raise TaskCenterError("sceneos_input", f"{key} is invalid")
|
||||
input_value[key] = input_value[key].strip()
|
||||
for key in ("runId", "stepId", "idempotencyKey"):
|
||||
if not isinstance(context[key], str) or not context[key].strip() or len(context[key]) > 256:
|
||||
raise TaskCenterError("sceneos_context", f"{key} is invalid")
|
||||
context[key] = context[key].strip()
|
||||
return value
|
||||
|
||||
|
||||
def main() -> int:
|
||||
from .application import resolve_data_root
|
||||
|
||||
return run(resolve_data_root(None))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,134 @@
|
||||
"""Verified backups limited to files needed by DxDesigner schematics."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import stat
|
||||
|
||||
from .errors import TaskCenterError
|
||||
|
||||
|
||||
BACKUP_MANIFEST_NAME = '.dxpartreplace-backup.json'
|
||||
EXCLUDED_DIRECTORY_NAMES = frozenset({
|
||||
'.git', '.hg', '.svn', '__pycache__', 'backups', 'ces', 'log files', 'pcb', 'projectbackup',
|
||||
})
|
||||
EXCLUDED_DIRECTORY_PATHS = frozenset({
|
||||
'database/cdbback', 'database/cdbsvr',
|
||||
})
|
||||
_REPARSE_POINT = getattr(stat, 'FILE_ATTRIBUTE_REPARSE_POINT', 0x400)
|
||||
|
||||
|
||||
def _is_link_or_reparse(path: Path) -> bool:
|
||||
details = path.lstat()
|
||||
return stat.S_ISLNK(details.st_mode) or bool(
|
||||
getattr(details, 'st_file_attributes', 0) & _REPARSE_POINT
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SchematicBackupResult:
|
||||
fingerprints: dict[str, tuple[int, str]]
|
||||
excluded_directories: tuple[str, ...]
|
||||
|
||||
@property
|
||||
def included_bytes(self) -> int:
|
||||
return sum(size for size, _digest in self.fingerprints.values())
|
||||
|
||||
|
||||
def create_schematic_backup(
|
||||
data_root: Path,
|
||||
project_path: Path,
|
||||
destination: Path,
|
||||
*,
|
||||
error_code: str = 'quick_run_backup',
|
||||
) -> SchematicBackupResult:
|
||||
project_root = project_path.resolve(strict=True).parent
|
||||
if data_root.resolve().is_relative_to(project_root):
|
||||
raise TaskCenterError(error_code, '工程目录包含任务数据,无法安全备份。')
|
||||
relative_paths, excluded_paths = _selected_paths(project_root, error_code=error_code)
|
||||
before = _fingerprint_paths(project_root, relative_paths, error_code=error_code)
|
||||
destination.mkdir(parents=True)
|
||||
for relative_path in relative_paths:
|
||||
target = destination / relative_path
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(project_root / relative_path, target)
|
||||
copied_paths, _ = _selected_paths(destination, error_code=error_code)
|
||||
source_after_paths, _ = _selected_paths(project_root, error_code=error_code)
|
||||
if (
|
||||
copied_paths != relative_paths
|
||||
or source_after_paths != relative_paths
|
||||
or _fingerprint_paths(destination, copied_paths, error_code=error_code) != before
|
||||
or _fingerprint_paths(project_root, source_after_paths, error_code=error_code) != before
|
||||
):
|
||||
raise TaskCenterError(error_code, '备份期间工程发生变化,未开始图页枚举或替换。')
|
||||
result = SchematicBackupResult(before, excluded_paths)
|
||||
manifest = {
|
||||
'format_version': 1,
|
||||
'scope': 'dxdesigner_schematic_essentials',
|
||||
'project_path': str(project_path.resolve(strict=True)),
|
||||
'source_root': str(project_root),
|
||||
'included_file_count': len(before),
|
||||
'included_bytes': result.included_bytes,
|
||||
'excluded_directories': list(excluded_paths),
|
||||
'files': [
|
||||
{'path': path, 'size': size, 'sha256': digest}
|
||||
for path, (size, digest) in before.items()
|
||||
],
|
||||
}
|
||||
(destination / BACKUP_MANIFEST_NAME).write_text(
|
||||
json.dumps(manifest, ensure_ascii=False, indent=2), encoding='utf-8'
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def _selected_paths(root: Path, *, error_code: str) -> tuple[tuple[Path, ...], tuple[str, ...]]:
|
||||
selected: list[Path] = []
|
||||
excluded: list[str] = []
|
||||
for current, directory_names, file_names in os.walk(root):
|
||||
current_path = Path(current)
|
||||
relative_root = current_path.relative_to(root)
|
||||
kept_directories: list[str] = []
|
||||
for directory_name in sorted(directory_names, key=str.casefold):
|
||||
relative_path = relative_root / directory_name
|
||||
normalized = relative_path.as_posix().casefold()
|
||||
if directory_name.casefold() in EXCLUDED_DIRECTORY_NAMES or normalized in EXCLUDED_DIRECTORY_PATHS:
|
||||
excluded.append(relative_path.as_posix())
|
||||
continue
|
||||
directory_path = current_path / directory_name
|
||||
if _is_link_or_reparse(directory_path):
|
||||
raise TaskCenterError(error_code, '工程精简备份范围中发现链接目录,已停止。')
|
||||
kept_directories.append(directory_name)
|
||||
directory_names[:] = kept_directories
|
||||
for file_name in sorted(file_names, key=str.casefold):
|
||||
if file_name.casefold() == BACKUP_MANIFEST_NAME.casefold():
|
||||
continue
|
||||
path = current_path / file_name
|
||||
if _is_link_or_reparse(path):
|
||||
raise TaskCenterError(error_code, '工程精简备份范围中发现链接文件,已停止。')
|
||||
if path.is_file():
|
||||
selected.append(path.relative_to(root))
|
||||
selected.sort(key=lambda path: path.as_posix().casefold())
|
||||
excluded.sort(key=str.casefold)
|
||||
return tuple(selected), tuple(excluded)
|
||||
|
||||
|
||||
def _fingerprint_paths(
|
||||
root: Path,
|
||||
relative_paths: tuple[Path, ...],
|
||||
*,
|
||||
error_code: str,
|
||||
) -> dict[str, tuple[int, str]]:
|
||||
result: dict[str, tuple[int, str]] = {}
|
||||
for relative_path in relative_paths:
|
||||
path = root / relative_path
|
||||
if _is_link_or_reparse(path):
|
||||
raise TaskCenterError(error_code, '工程精简备份范围中发现链接文件,已停止。')
|
||||
with path.open('rb') as stream:
|
||||
digest = hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
result[relative_path.as_posix()] = (path.stat().st_size, digest)
|
||||
return result
|
||||
@@ -0,0 +1,746 @@
|
||||
"""Qt-free application facade for the trial task center UI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime
|
||||
import os
|
||||
from pathlib import Path
|
||||
import threading
|
||||
from typing import TypeVar
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .logging_setup import LoggingContext, _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
|
||||
|
||||
|
||||
_Result = TypeVar("_Result")
|
||||
_QUICK_RUN_THREAD_LOCK = threading.Lock()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _quick_run_lease(root: Path):
|
||||
if not _QUICK_RUN_THREAD_LOCK.acquire(blocking=False):
|
||||
raise TaskCenterError("quick_run_busy", "another quick-run operation is already executing")
|
||||
handle = None
|
||||
locked = False
|
||||
try:
|
||||
lock_path = root / ".quick-run.execution.lock"
|
||||
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
handle = lock_path.open("a+b")
|
||||
if handle.seek(0, os.SEEK_END) == 0:
|
||||
handle.write(b"\0")
|
||||
handle.flush()
|
||||
handle.seek(0)
|
||||
try:
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
|
||||
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except OSError as error:
|
||||
raise TaskCenterError("quick_run_busy", "another application instance is executing quick-run") from error
|
||||
locked = True
|
||||
yield
|
||||
finally:
|
||||
if handle is not None:
|
||||
if locked:
|
||||
handle.seek(0)
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
|
||||
msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
|
||||
handle.close()
|
||||
_QUICK_RUN_THREAD_LOCK.release()
|
||||
|
||||
|
||||
def _default_path_opener(path: Path) -> None:
|
||||
if os.name != "nt":
|
||||
raise TaskCenterError("path_opener", "opening evidence folders requires Windows")
|
||||
os.startfile(path) # type: ignore[attr-defined]
|
||||
|
||||
|
||||
class TaskCenterService:
|
||||
"""The only API used by UI workers and widgets."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
store: TaskStore,
|
||||
logging_context: LoggingContext,
|
||||
*,
|
||||
path_opener: Callable[[Path], None] = _default_path_opener,
|
||||
clock: Callable[[], datetime] = datetime.now,
|
||||
probe_source_resolver: Callable[[TaskRecord, ProjectRecord], Path] | None = None,
|
||||
quick_run_preparer: QuickRunPreparer | 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._quick_run_preparer = quick_run_preparer or QuickRunPreparer(logging_context.root)
|
||||
self._batch_feedback = None
|
||||
|
||||
def create_task(self, name: str, *, note: str = "") -> TaskRecord:
|
||||
return self._operation("create_task", None, lambda: self._store.create_task(name, note))
|
||||
|
||||
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 update_task(self, task_id: str, *, name: str, note: str) -> TaskRecord:
|
||||
return self._idle_quick_run_operation(
|
||||
"update_task", task_id, lambda: self._store.update_task(task_id, name=name, note=note)
|
||||
)
|
||||
|
||||
def delete_task(self, task_id: str) -> TaskRecord:
|
||||
return self._idle_quick_run_operation("delete_task", task_id, lambda: self._store.soft_delete_task(task_id))
|
||||
|
||||
def restore_task(self, task_id: str) -> TaskRecord:
|
||||
return self._idle_quick_run_operation("restore_task", task_id, lambda: self._store.restore_task(task_id))
|
||||
|
||||
def purge_task(self, task_id: str, *, confirmed: bool = False) -> str:
|
||||
def purge() -> str:
|
||||
if confirmed is not True:
|
||||
raise TaskCenterError("permanent_delete_confirmation", "permanent task deletion requires explicit confirmation")
|
||||
if self._store.get_task(task_id).status is not TaskStatus.DELETED:
|
||||
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)
|
||||
|
||||
def rules(self, task_id: str) -> tuple[RuleRecord, ...]:
|
||||
return self._operation("list_rules", task_id, lambda: self._store.list_rules(task_id))
|
||||
|
||||
def add_rule(
|
||||
self,
|
||||
task_id: str,
|
||||
old_part_number: str,
|
||||
new_part_number: str,
|
||||
*,
|
||||
enabled: bool = True,
|
||||
custom_value_enabled: bool = False,
|
||||
custom_value: str = "",
|
||||
sync_nc: bool = True,
|
||||
) -> RuleRecord:
|
||||
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,
|
||||
enabled=enabled,
|
||||
custom_value_enabled=custom_value_enabled,
|
||||
custom_value=custom_value,
|
||||
sync_nc=sync_nc,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
def update_rule(
|
||||
self,
|
||||
rule_id: str,
|
||||
*,
|
||||
old_part_number: str,
|
||||
new_part_number: str,
|
||||
enabled: bool,
|
||||
custom_value_enabled: bool | None = None,
|
||||
custom_value: str | None = None,
|
||||
sync_nc: bool | None = None,
|
||||
) -> RuleRecord:
|
||||
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,
|
||||
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,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
def delete_rule(self, rule_id: str) -> None:
|
||||
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)),
|
||||
)
|
||||
|
||||
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)),
|
||||
)
|
||||
|
||||
def projects(self, task_id: str) -> tuple[ProjectRecord, ...]:
|
||||
return self._operation("list_projects", task_id, lambda: self._store.list_projects(task_id))
|
||||
|
||||
def scan_projects(self, task_id: str, root: Path) -> tuple[ProjectRecord, ...]:
|
||||
def scan_and_sync() -> tuple[ProjectRecord, ...]:
|
||||
task = self._store.get_task(task_id)
|
||||
if self._has_current_quick_run_evidence(task_id):
|
||||
raise TaskCenterError(
|
||||
"quick_run_options_locked",
|
||||
"cannot rescan projects while automatic queue evidence exists",
|
||||
)
|
||||
if (
|
||||
task.discovery_root is not None
|
||||
and _path_key(task.discovery_root) != _path_key(root)
|
||||
and self._has_current_quick_run_evidence(task_id)
|
||||
):
|
||||
raise TaskCenterError(
|
||||
"discovery_root_locked",
|
||||
"cannot change the discovery root while automatic queue evidence exists",
|
||||
)
|
||||
paths = scan_projects(root, excluded_roots=(self._logging.root,))
|
||||
return self._store.sync_projects(task_id, root, paths)
|
||||
|
||||
return self._idle_quick_run_operation("scan_projects", task_id, scan_and_sync)
|
||||
|
||||
def create_scanned_task(
|
||||
self,
|
||||
*,
|
||||
source: str,
|
||||
idempotency_key: str,
|
||||
request_hash: str,
|
||||
name: str,
|
||||
note: str,
|
||||
root: Path,
|
||||
) -> tuple[TaskRecord, tuple[ProjectRecord, ...], bool]:
|
||||
def create_and_scan() -> tuple[TaskRecord, tuple[ProjectRecord, ...], bool]:
|
||||
paths = scan_projects(root, excluded_roots=(self._logging.root,))
|
||||
return self._store.create_scanned_task_for_request(
|
||||
source=source,
|
||||
idempotency_key=idempotency_key,
|
||||
request_hash=request_hash,
|
||||
name=name,
|
||||
note=note,
|
||||
discovery_root=root,
|
||||
paths=paths,
|
||||
)
|
||||
|
||||
return self._idle_quick_run_operation("create_scanned_task", None, create_and_scan)
|
||||
|
||||
def set_project_selected(self, project_id: str, selected: bool) -> ProjectRecord:
|
||||
def set_selected() -> ProjectRecord:
|
||||
project = self._project_owner(project_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)
|
||||
return next(item for item in snapshot.projects if item.project_id == project_id)
|
||||
|
||||
return self._idle_quick_run_operation("set_project_selected", None, set_selected)
|
||||
|
||||
def select_all_projects(self, task_id: str) -> tuple[ProjectRecord, ...]:
|
||||
def select() -> tuple[ProjectRecord, ...]:
|
||||
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,
|
||||
True,
|
||||
available_only=True,
|
||||
).projects
|
||||
|
||||
return self._idle_quick_run_operation("select_all_projects", task_id, select)
|
||||
|
||||
def clear_project_selection(self, task_id: str) -> tuple[ProjectRecord, ...]:
|
||||
def clear() -> tuple[ProjectRecord, ...]:
|
||||
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
|
||||
|
||||
return self._idle_quick_run_operation("clear_project_selection", task_id, clear)
|
||||
|
||||
def start_task(self, task_id: str, *, disposable_copy_confirmed: bool) -> RunnerSnapshot:
|
||||
return self._manual_operation(
|
||||
"start_task",
|
||||
task_id,
|
||||
lambda: self._runner.start_task(task_id, disposable_copy_confirmed=disposable_copy_confirmed),
|
||||
)
|
||||
|
||||
def capture_before(self, task_id: str, project_id: str, probe_path: Path) -> RunnerSnapshot:
|
||||
return self._manual_operation(
|
||||
"capture_before", task_id, lambda: self._runner.capture_before(task_id, project_id, probe_path)
|
||||
)
|
||||
|
||||
def confirm_native_attempt(self, task_id: str, project_id: str) -> RunnerSnapshot:
|
||||
return self._manual_operation(
|
||||
"confirm_native_attempt", task_id, lambda: self._runner.confirm_native_attempt(task_id, project_id)
|
||||
)
|
||||
|
||||
def capture_after(self, task_id: str, project_id: str, probe_path: Path) -> RunnerSnapshot:
|
||||
return self._manual_operation(
|
||||
"capture_after", task_id, lambda: self._runner.capture_after(task_id, project_id, probe_path)
|
||||
)
|
||||
|
||||
def pause_task(self, task_id: str) -> RunnerSnapshot:
|
||||
return self._manual_operation("pause_task", task_id, lambda: self._runner.pause_task(task_id))
|
||||
|
||||
def resume_task(self, task_id: str) -> RunnerSnapshot:
|
||||
return self._manual_operation("resume_task", task_id, lambda: self._runner.resume_task(task_id))
|
||||
|
||||
def retry_project(self, task_id: str, project_id: str) -> RunnerSnapshot:
|
||||
return self._manual_operation("retry_project", task_id, lambda: self._runner.retry_project(task_id, project_id))
|
||||
|
||||
def skip_project(self, task_id: str, project_id: str) -> RunnerSnapshot:
|
||||
return self._manual_operation("skip_project", task_id, lambda: self._runner.skip_project(task_id, project_id))
|
||||
|
||||
def snapshot(self, task_id: str) -> RunnerSnapshot:
|
||||
return self._operation("snapshot", task_id, lambda: self._runner.snapshot(task_id))
|
||||
|
||||
def current_instruction(self, task_id: str) -> OperatorInstruction | None:
|
||||
return self._operation("current_instruction", task_id, lambda: self._runner.snapshot(task_id).instruction)
|
||||
|
||||
def expected_probe_path(self, task_id: str, project_id: str | None = None) -> Path:
|
||||
def expected_path() -> Path:
|
||||
task = self._store.get_task(task_id)
|
||||
if project_id is None:
|
||||
return self._logging.root / "runs" / "menu-compatibility-profile.json"
|
||||
project = self._project_owner(project_id)
|
||||
if project.task_id != task_id:
|
||||
raise TaskCenterError("project_task_mismatch", "project does not belong to the task")
|
||||
return self._runner.expected_probe_path(task, project)
|
||||
|
||||
return self._operation("expected_probe_path", task_id, expected_path)
|
||||
|
||||
def prepare_quick_run(self, task_id: str) -> QuickRunResult:
|
||||
"""Create the legacy VBS handoff without starting a task-center trial."""
|
||||
def prepare() -> QuickRunResult:
|
||||
task = self._store.get_task(task_id)
|
||||
result = self._quick_run_preparer.prepare(
|
||||
task_id,
|
||||
self._store.list_projects(task_id),
|
||||
self._store.list_rules(task_id),
|
||||
copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
)
|
||||
append_task_event(
|
||||
self._logging,
|
||||
level="INFO",
|
||||
task_id=task_id,
|
||||
operation="quick_run_prepared",
|
||||
message="quick-run script prepared",
|
||||
details={
|
||||
"script_path": str(result.script_path),
|
||||
"command_path": str(result.command_path),
|
||||
"status_path": str(result.status_path),
|
||||
"log_path": str(result.log_path),
|
||||
"vbs_root_compatible": result.vbs_root_compatible,
|
||||
},
|
||||
)
|
||||
self._logging.logger.info("quick_run_prepared task_id=%s script_path=%s", task_id, result.script_path)
|
||||
if not result.vbs_root_compatible:
|
||||
self._logging.logger.warning(
|
||||
"quick_run_vbs_root_mismatch task_id=%s data_root=%s expected_root=%s",
|
||||
task_id,
|
||||
result.script_path.parent.parent,
|
||||
self._quick_run_preparer.vbs_data_root,
|
||||
)
|
||||
return result
|
||||
|
||||
with _quick_run_lease(self._logging.root):
|
||||
return self._operation("prepare_quick_run", task_id, prepare)
|
||||
|
||||
@property
|
||||
def layout_settings_path(self) -> Path:
|
||||
return self._logging.root / "ui-layout.ini"
|
||||
|
||||
def can_edit_value_options(self, task_id: str) -> bool:
|
||||
task = self._store.get_task(task_id)
|
||||
return (
|
||||
task.status in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.FAILED}
|
||||
and not self._has_current_quick_run_evidence(task_id)
|
||||
) or self._retryable_quick_run(task_id)
|
||||
|
||||
def set_copy_part_number_to_value(self, task_id: str, enabled: bool) -> TaskRecord:
|
||||
def update() -> TaskRecord:
|
||||
if not self.can_edit_value_options(task_id):
|
||||
raise TaskCenterError("quick_run_options_locked", "queue Value policy is frozen; create a new task to change it")
|
||||
task = self._store.set_copy_part_number_to_value(task_id, enabled)
|
||||
append_task_event(self._logging, level="INFO", task_id=task_id, operation="value_policy_changed",
|
||||
details={"copy_part_label_to_value": enabled})
|
||||
return task
|
||||
|
||||
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."""
|
||||
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),
|
||||
copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
**({"expected_item": expected_item} if expected_item is not None else {}),
|
||||
)
|
||||
self._synchronize_quick_run_progress(task_id)
|
||||
append_task_event(
|
||||
self._logging,
|
||||
level="INFO",
|
||||
task_id=task_id,
|
||||
operation="quick_run_executed",
|
||||
message=result.message,
|
||||
details={"state": result.state, "status_path": str(result.status_path), "log_path": str(result.log_path)},
|
||||
)
|
||||
self._logging.logger.info("quick_run_executed task_id=%s state=%s", task_id, result.state)
|
||||
return result
|
||||
|
||||
with _quick_run_lease(self._logging.root):
|
||||
return self._operation("execute_quick_run", task_id, execute)
|
||||
|
||||
def execute_quick_run_queue(
|
||||
self,
|
||||
task_id: str,
|
||||
*,
|
||||
expected_item,
|
||||
stop_event: threading.Event,
|
||||
continue_after_backup_failure: bool = False,
|
||||
):
|
||||
from .batch import execute_batch
|
||||
|
||||
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,
|
||||
task_id,
|
||||
expected_item=expected_item,
|
||||
stop_event=stop_event,
|
||||
continue_after_backup_failure=continue_after_backup_failure,
|
||||
),
|
||||
)
|
||||
if result.paused:
|
||||
self._pause_quick_run_queue(task_id, 'queue paused at item boundary')
|
||||
return result
|
||||
except Exception:
|
||||
self._pause_quick_run_queue(task_id, 'queue stopped after execution error')
|
||||
raise
|
||||
finally:
|
||||
self._batch_feedback = None
|
||||
|
||||
def prepare_failed_quick_run(self, task_id: str) -> QuickRunProgress:
|
||||
"""Reset only failed projects and discard the finished queue handoff."""
|
||||
def prepare_retry() -> QuickRunProgress:
|
||||
task = self._store.get_task(task_id)
|
||||
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),
|
||||
copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
)
|
||||
failed_paths = {
|
||||
_path_key(path)
|
||||
for path, _summary in getattr(progress, "failed_project_summaries", ())
|
||||
}
|
||||
failed_projects = tuple(
|
||||
project for project in self._store.list_projects(task_id)
|
||||
if project.status is ProjectStatus.FAILED
|
||||
and project.selected
|
||||
and project.available
|
||||
and (not failed_paths or _path_key(project.path) in failed_paths)
|
||||
)
|
||||
if not failed_projects:
|
||||
raise TaskCenterError("quick_run_complete", "当前队列没有可重试的失败工程")
|
||||
self._quick_run_preparer.archive_current_handoff(task_id)
|
||||
for project in failed_projects:
|
||||
self._store.set_project_status(
|
||||
project.project_id,
|
||||
ProjectStatus.PENDING,
|
||||
summary="project queued for retry",
|
||||
)
|
||||
append_task_event(
|
||||
self._logging,
|
||||
level="INFO",
|
||||
task_id=task_id,
|
||||
operation="quick_run_retry_prepared",
|
||||
message="失败工程已重新加入队列",
|
||||
details={"project_ids": [project.project_id for project in failed_projects]},
|
||||
)
|
||||
self._quick_run_preparer.ensure_batch_handoff(
|
||||
task_id,
|
||||
self._store.list_projects(task_id),
|
||||
self._store.list_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),
|
||||
copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
)
|
||||
|
||||
with _quick_run_lease(self._logging.root):
|
||||
return self._operation("prepare_failed_quick_run", task_id, prepare_retry)
|
||||
|
||||
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)
|
||||
append_task_event(self._logging, level='INFO', task_id=task_id,
|
||||
operation='quick_run_queue_paused', message=message)
|
||||
|
||||
def batch_feedback(self):
|
||||
return self._batch_feedback
|
||||
|
||||
def quick_run_phase(self, task_id: str) -> str:
|
||||
"""Read the current task's local quick-run phase without executing COM work."""
|
||||
def read_phase() -> str:
|
||||
self._store.get_task(task_id)
|
||||
if self._retryable_quick_run(task_id):
|
||||
return "retry"
|
||||
progress = self._synchronize_quick_run_progress(task_id)
|
||||
if progress.queue_complete:
|
||||
return "retry" if getattr(progress, "failed_items", 0) else "complete"
|
||||
return "selection"
|
||||
|
||||
return self._operation("quick_run_phase", task_id, read_phase)
|
||||
|
||||
def has_interrupted_quick_run(self, task_id: str) -> bool:
|
||||
return self._quick_run_preparer.has_interrupted(task_id)
|
||||
|
||||
def recover_quick_run(self, task_id: str, *, confirmed: bool = False) -> QuickRunStepResult:
|
||||
from .recovery import recover
|
||||
|
||||
def reconcile() -> QuickRunStepResult:
|
||||
task = self._store.get_task(task_id)
|
||||
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):
|
||||
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,
|
||||
confirmed=confirmed)
|
||||
if task.status in {TaskStatus.PAUSED, TaskStatus.FAILED}:
|
||||
self._store.set_task_status(task_id, TaskStatus.READY, summary="interrupted quick-run reconciled")
|
||||
self._synchronize_quick_run_progress(task_id)
|
||||
append_task_event(self._logging, level="INFO", task_id=task_id, operation="quick_run_recovered",
|
||||
message=result.message, details={"state": result.state, "evidence": str(result.log_path.parent)})
|
||||
return result
|
||||
|
||||
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:
|
||||
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
|
||||
|
||||
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"
|
||||
|
||||
def tail_log(self, task_id: str, *, limit: int = 100) -> tuple[str, ...]:
|
||||
if limit < 1:
|
||||
raise TaskCenterError("log_limit", "log line limit must be positive")
|
||||
path = self._logging.root / "tasks" / task_id / "events.jsonl"
|
||||
try:
|
||||
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 open_task_log(self, task_id: str) -> Path:
|
||||
def open_path() -> Path:
|
||||
self._store.get_task(task_id)
|
||||
path = self._logging.root / "tasks" / task_id / "events.jsonl"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not path.exists():
|
||||
path.touch()
|
||||
self._path_opener(path)
|
||||
return path
|
||||
|
||||
return self._operation("open_task_log", task_id, open_path)
|
||||
|
||||
def report_ui_error(self, error: BaseException) -> TaskCenterError:
|
||||
"""Record an unexpected presentation-layer failure with a stable support ID."""
|
||||
return self._logging.report_exception("ui", error)
|
||||
|
||||
def open_evidence(self, task_id: str, project_id: str) -> Path:
|
||||
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:
|
||||
raise TaskCenterError("unknown_project", "project does not belong to the task")
|
||||
quick_run_path = self._quick_run_preparer.evidence_path(task_id, project.path)
|
||||
if quick_run_path is not None:
|
||||
self._path_opener(quick_run_path)
|
||||
return quick_run_path
|
||||
path = self._logging.root / "tasks" / task_id / "evidence" / project_id / f"attempt-{project.retry_count + 1}"
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
self._path_opener(path)
|
||||
return path
|
||||
|
||||
return self._operation("open_evidence", task_id, open_path)
|
||||
|
||||
def open_quick_run_evidence(self, task_id: str) -> Path:
|
||||
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")
|
||||
self._path_opener(path)
|
||||
return path
|
||||
|
||||
return self._operation("open_quick_run_evidence", task_id, open_path)
|
||||
|
||||
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 TaskCenterError as error:
|
||||
self._logging.report_exception(name, error)
|
||||
raise
|
||||
except Exception as error:
|
||||
raise self._logging.report_exception(name, error) from error
|
||||
completed_timestamp = self._clock().isoformat()
|
||||
self._logging.logger.info("operation_complete=%s task_id=%s at=%s", name, task_id or "", completed_timestamp)
|
||||
return result
|
||||
|
||||
def _idle_quick_run_operation(
|
||||
self,
|
||||
name: str,
|
||||
task_id: str | None,
|
||||
action: Callable[[], _Result],
|
||||
) -> _Result:
|
||||
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:
|
||||
raise TaskCenterError('quick_run_manual_operation', '此任务属于自动队列,不能混用人工采集、跳过或重试。请使用继续队列或核验恢复。')
|
||||
return action()
|
||||
|
||||
return self._idle_quick_run_operation(name, task_id, checked_action)
|
||||
|
||||
def _synchronize_quick_run_progress(
|
||||
self,
|
||||
task_id: str,
|
||||
*,
|
||||
progress: QuickRunProgress | None = None,
|
||||
) -> QuickRunProgress:
|
||||
task = self._store.get_task(task_id)
|
||||
projects = self._store.list_projects(task_id)
|
||||
if progress is None:
|
||||
progress = self._quick_run_preparer.progress(
|
||||
task_id,
|
||||
projects,
|
||||
self._store.list_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}
|
||||
project_by_id = {project.project_id: project for project in projects}
|
||||
summary_by_id = {
|
||||
by_path[_path_key(path)]: summary
|
||||
for path, summary in (
|
||||
*progress.project_summaries,
|
||||
*getattr(progress, "failed_project_summaries", ()),
|
||||
)
|
||||
if _path_key(path) in by_path
|
||||
}
|
||||
failed_project_ids = tuple(
|
||||
project_id
|
||||
for project_id, summary in summary_by_id.items()
|
||||
if summary.partition("|")[0].rsplit(":", 1)[-1] == "failed"
|
||||
)
|
||||
completed_project_ids = tuple(
|
||||
by_path[path_key]
|
||||
for path in progress.completed_project_paths
|
||||
if (path_key := os.path.normcase(os.path.abspath(str(path)))) in by_path
|
||||
and by_path[path_key] not in failed_project_ids
|
||||
)
|
||||
changed_project_ids = tuple(
|
||||
project_id
|
||||
for project_id in completed_project_ids
|
||||
if (
|
||||
project_by_id[project_id].status is not ProjectStatus.COMPLETED
|
||||
or project_by_id[project_id].summary != summary_by_id.get(
|
||||
project_id,
|
||||
"current-sheet quick-run queue completed",
|
||||
)
|
||||
)
|
||||
)
|
||||
changed_failed_project_ids = tuple(
|
||||
project_id
|
||||
for project_id in failed_project_ids
|
||||
if (
|
||||
project_by_id[project_id].status is not ProjectStatus.FAILED
|
||||
or project_by_id[project_id].summary != summary_by_id.get(project_id, "")
|
||||
)
|
||||
)
|
||||
retry_summary = "current-sheet quick-run queue completed with retryable failures"
|
||||
task_state_changed = (
|
||||
progress.completed_items > 0 and task.status in {TaskStatus.DRAFT, TaskStatus.READY}
|
||||
) or (
|
||||
progress.queue_complete
|
||||
and (
|
||||
(bool(failed_project_ids) and (task.status is not TaskStatus.RUNNING or task.summary != retry_summary))
|
||||
or (not failed_project_ids and task.status is not TaskStatus.COMPLETED)
|
||||
)
|
||||
)
|
||||
if task.status is not TaskStatus.DELETED and (changed_project_ids or changed_failed_project_ids or task_state_changed):
|
||||
self._store.record_quick_run_progress(
|
||||
task_id,
|
||||
changed_project_ids,
|
||||
failed_project_ids=changed_failed_project_ids,
|
||||
has_progress=progress.completed_items > 0,
|
||||
queue_complete=progress.queue_complete,
|
||||
project_summaries={
|
||||
project_id: summary_by_id[project_id]
|
||||
for project_id in (*changed_project_ids, *changed_failed_project_ids)
|
||||
if project_id in summary_by_id
|
||||
},
|
||||
)
|
||||
return progress
|
||||
|
||||
def _editable_rules(self, task_id: str, action: Callable[[], _Result]) -> _Result:
|
||||
if (
|
||||
self._store.get_task(task_id).status in {TaskStatus.RUNNING, TaskStatus.PAUSED}
|
||||
or self._has_current_quick_run_evidence(task_id)
|
||||
) and not self._retryable_quick_run(task_id):
|
||||
raise TaskCenterError("rules_locked", "mapping rules cannot change while a task attempt is active")
|
||||
return action()
|
||||
|
||||
def _retryable_quick_run(self, task_id: str) -> bool:
|
||||
task = self._store.get_task(task_id)
|
||||
return (
|
||||
task.status is TaskStatus.RUNNING
|
||||
and task.summary == "current-sheet quick-run queue completed with retryable failures"
|
||||
and any(project.status is ProjectStatus.FAILED for project in self._store.list_projects(task_id))
|
||||
)
|
||||
|
||||
def _project_owner(self, project_id: str) -> ProjectRecord:
|
||||
return self._store.get_project(project_id)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,5 @@
|
||||
"""PySide6 task-center presentation layer."""
|
||||
|
||||
from .main_window import TrialTaskCenterWindow
|
||||
|
||||
__all__ = ["TrialTaskCenterWindow"]
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,62 @@
|
||||
"""Ordered Part Number mapping table."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Iterable
|
||||
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import QAbstractItemView, QCheckBox, QHBoxLayout, QHeaderView, QTableWidget, QTableWidgetItem, QWidget
|
||||
|
||||
|
||||
class MappingTable(QTableWidget):
|
||||
def __init__(self, on_enabled_changed: Callable[[str, bool], None] | None = None) -> None:
|
||||
super().__init__(0, 6)
|
||||
self.setObjectName("mappingTable")
|
||||
self.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
|
||||
self.setHorizontalHeaderLabels(("旧物料编码", "新物料编码", "自定义 Value", "同步 NC", "启用", "顺序"))
|
||||
header = self.horizontalHeader()
|
||||
for section, width in ((0, 220), (1, 220), (2, 180), (3, 80), (4, 70), (5, 65)):
|
||||
header.setSectionResizeMode(section, QHeaderView.ResizeMode.Interactive)
|
||||
header.resizeSection(section, width)
|
||||
header.setStretchLastSection(True)
|
||||
self._on_enabled_changed = on_enabled_changed
|
||||
self._rules_editable = True
|
||||
|
||||
def set_rules_editable(self, editable: bool) -> None:
|
||||
self._rules_editable = editable
|
||||
for row in range(self.rowCount()):
|
||||
cell = self.cellWidget(row, 4)
|
||||
if cell is not None:
|
||||
for check in cell.findChildren(QCheckBox):
|
||||
check.setEnabled(editable)
|
||||
|
||||
def populate(self, rules: Iterable[object]) -> None:
|
||||
self.setRowCount(0)
|
||||
for row, rule in enumerate(rules):
|
||||
self.insertRow(row)
|
||||
first = QTableWidgetItem(str(getattr(rule, "old_part_number")))
|
||||
first.setData(32, str(getattr(rule, "rule_id")))
|
||||
self.setItem(row, 0, first)
|
||||
self.setItem(row, 1, QTableWidgetItem(str(getattr(rule, "new_part_number"))))
|
||||
custom_value = str(getattr(rule, "custom_value", "")) if bool(getattr(rule, "custom_value_enabled", False)) else "不写入"
|
||||
self.setItem(row, 2, QTableWidgetItem(custom_value))
|
||||
self.setItem(row, 3, QTableWidgetItem("是" if bool(getattr(rule, "sync_nc", True)) else "否"))
|
||||
enabled = QCheckBox()
|
||||
enabled.setChecked(bool(getattr(rule, "enabled")))
|
||||
enabled.setEnabled(self._rules_editable)
|
||||
enabled.setToolTip("启用或停用此替换规则")
|
||||
if self._on_enabled_changed is not None:
|
||||
rule_id = str(getattr(rule, "rule_id"))
|
||||
enabled.toggled.connect(lambda checked, item_id=rule_id: self._on_enabled_changed(item_id, checked))
|
||||
enabled_cell = QWidget()
|
||||
enabled_layout = QHBoxLayout(enabled_cell)
|
||||
enabled_layout.setContentsMargins(0, 0, 0, 0)
|
||||
enabled_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
enabled_layout.addWidget(enabled)
|
||||
self.setCellWidget(row, 4, enabled_cell)
|
||||
self.setItem(row, 5, QTableWidgetItem(str(getattr(rule, "position") + 1)))
|
||||
self.resizeRowsToContents()
|
||||
|
||||
def current_rule_id(self) -> str | None:
|
||||
item = self.item(self.currentRow(), 0)
|
||||
return str(item.data(32)) if item is not None else None
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Project selection table used by the task workspace."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Iterable
|
||||
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtGui import QColor
|
||||
from PySide6.QtWidgets import QAbstractItemView, QCheckBox, QHeaderView, QTableWidget, QTableWidgetItem
|
||||
|
||||
|
||||
PROJECT_STATUS_TEXT = {
|
||||
"pending": "待处理",
|
||||
"capturing_before": "采集替换前",
|
||||
"awaiting_operator": "等待人工替换",
|
||||
"capturing_after": "采集替换后",
|
||||
"verifying": "正在核验",
|
||||
"completed": "已完成",
|
||||
"failed": "失败",
|
||||
"skipped": "已跳过",
|
||||
}
|
||||
|
||||
PROJECT_RESULT_TEXT = {
|
||||
"project selected for capture": "工程已进入替换前采集",
|
||||
"before profile captured": "替换前数据已采集",
|
||||
"capturing after profile": "正在采集替换后数据",
|
||||
"verifying captured profiles": "正在核验替换前后数据",
|
||||
"comparison passed": "替换核验通过",
|
||||
"project selected after resume": "继续处理此工程",
|
||||
"project selected for retry": "工程已进入重试",
|
||||
"project queued for retry": "工程已加入重试队列",
|
||||
"project skipped by operator": "工程已由操作员跳过",
|
||||
"operator stopped project before verification": "工程在核验前被操作员停止",
|
||||
"current-sheet quick-run queue completed": "图页替换队列已校验,尚未保存",
|
||||
}
|
||||
|
||||
PROJECT_STATUS_COLORS = {
|
||||
"completed": "#245b35",
|
||||
"failed": "#84251e",
|
||||
"skipped": "#5a4600",
|
||||
}
|
||||
|
||||
|
||||
class ProjectTable(QTableWidget):
|
||||
def __init__(self, on_selection_changed: Callable[[str, bool], None]) -> None:
|
||||
super().__init__(0, 5)
|
||||
self.setObjectName("projectTable")
|
||||
self.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
|
||||
self.setHorizontalHeaderLabels(("选择", "工程", "路径", "状态", "结果"))
|
||||
header = self.horizontalHeader()
|
||||
header.setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed)
|
||||
header.resizeSection(0, 58)
|
||||
for section, width in ((1, 150), (2, 360), (3, 90), (4, 210)):
|
||||
header.setSectionResizeMode(section, QHeaderView.ResizeMode.Interactive)
|
||||
header.resizeSection(section, width)
|
||||
header.setStretchLastSection(True)
|
||||
self._on_selection_changed = on_selection_changed
|
||||
self._selection_enabled = True
|
||||
|
||||
def set_selection_enabled(self, enabled: bool) -> None:
|
||||
self._selection_enabled = enabled
|
||||
for row in range(self.rowCount()):
|
||||
check = self.cellWidget(row, 0)
|
||||
if check is not None:
|
||||
check.setEnabled(enabled and bool(check.property('projectAvailable')))
|
||||
|
||||
def populate(self, projects: Iterable[object]) -> None:
|
||||
vertical_position = self.verticalScrollBar().value()
|
||||
horizontal_position = self.horizontalScrollBar().value()
|
||||
current_project_id = self.current_project_id()
|
||||
self.setRowCount(0)
|
||||
current_row = -1
|
||||
for row, project in enumerate(projects):
|
||||
self.insertRow(row)
|
||||
check = QCheckBox()
|
||||
check.setChecked(bool(getattr(project, "selected")))
|
||||
check.setProperty('projectAvailable', bool(getattr(project, 'available')))
|
||||
check.setEnabled(self._selection_enabled and bool(check.property('projectAvailable')))
|
||||
project_id = str(getattr(project, "project_id"))
|
||||
check.toggled.connect(lambda checked, item_id=project_id: self._on_selection_changed(item_id, checked))
|
||||
self.setCellWidget(row, 0, check)
|
||||
name = QTableWidgetItem(str(getattr(project, "display_name")))
|
||||
name.setData(Qt.ItemDataRole.UserRole, project_id)
|
||||
self.setItem(row, 1, name)
|
||||
if project_id == current_project_id:
|
||||
current_row = row
|
||||
self.setItem(row, 2, QTableWidgetItem(str(getattr(project, "path"))))
|
||||
status = str(getattr(project, "status").value)
|
||||
status_item = QTableWidgetItem(PROJECT_STATUS_TEXT.get(status, status))
|
||||
self.setItem(row, 3, status_item)
|
||||
raw_detail = str(getattr(project, "summary"))
|
||||
detail = PROJECT_RESULT_TEXT.get(raw_detail, raw_detail)
|
||||
if raw_detail.startswith("quick_run_result:"):
|
||||
try:
|
||||
_, replaced, missed, result_detail = raw_detail.split(":", 3)
|
||||
saved, _, failure_detail = result_detail.partition("|")
|
||||
if saved == "failed":
|
||||
status = "failed"
|
||||
status_item.setText("失败")
|
||||
detail = failure_detail or "工程失败,失败原因请查看任务日志"
|
||||
elif int(replaced) == 0:
|
||||
status = "skipped"
|
||||
status_item.setText("未命中跳过")
|
||||
detail = f"未命中 {int(missed)} 项,未作替换"
|
||||
else:
|
||||
detail = f"替换校验 {int(replaced)} 项,未命中 {int(missed)} 项;" + ("已保存" if saved == "saved" else "尚未确认保存")
|
||||
except ValueError:
|
||||
detail = "结果记录格式异常,请查看证据"
|
||||
error_id = getattr(project, "error_id")
|
||||
color = PROJECT_STATUS_COLORS.get(status)
|
||||
if color is not None:
|
||||
status_item.setForeground(QColor(color))
|
||||
self.setItem(row, 4, QTableWidgetItem(f"{error_id or ''} {detail}".strip()))
|
||||
self.resizeRowsToContents()
|
||||
if current_row >= 0:
|
||||
self.setCurrentCell(current_row, 1)
|
||||
self.verticalScrollBar().setValue(vertical_position)
|
||||
self.horizontalScrollBar().setValue(horizontal_position)
|
||||
|
||||
def current_project_id(self) -> str | None:
|
||||
item = self.item(self.currentRow(), 1)
|
||||
return str(item.data(Qt.ItemDataRole.UserRole)) if item is not None else None
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Operator guidance, commands, and read-only task log widgets."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from PySide6.QtWidgets import QCheckBox, QHBoxLayout, QLabel, QProgressBar, QPushButton, QTextEdit, QToolButton, QVBoxLayout, QWidget
|
||||
|
||||
|
||||
class RunPanel(QWidget):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.operator_band = QLabel("请选择任务,并扫描工程目录。", objectName="operatorBand")
|
||||
self.operator_band.setWordWrap(True)
|
||||
self.queue_summary = QLabel("未选择任务", objectName="queueSummary")
|
||||
self.execution_status = QLabel("空闲", objectName="executionStatus")
|
||||
self.execution_status.setWordWrap(True)
|
||||
self.busy_indicator = QProgressBar(objectName="quickRunBusyIndicator")
|
||||
self.busy_indicator.setRange(0, 0)
|
||||
self.busy_indicator.setTextVisible(False)
|
||||
self.busy_indicator.setFixedHeight(4)
|
||||
self.busy_indicator.hide()
|
||||
self.start_button = QPushButton("开始任务", objectName="startTaskButton")
|
||||
self.quick_run_button = QPushButton("确认并执行替换", objectName="quickRunButton")
|
||||
self.stop_queue_button = QPushButton("完成当前项后暂停", objectName="stopQueueButton")
|
||||
self.stop_queue_button.hide()
|
||||
self.continue_without_backup_button = QPushButton(
|
||||
"忽略备份失败并继续", objectName="continueWithoutBackupButton"
|
||||
)
|
||||
self.continue_without_backup_button.setToolTip(
|
||||
"仅在精简原理图备份失败后启用。继续执行将无法保证该工程可从本工具备份回滚。"
|
||||
)
|
||||
self.continue_without_backup_button.hide()
|
||||
self.recover_button = QPushButton("核验并恢复中断任务", objectName="recoverQuickRunButton")
|
||||
self.recover_button.setToolTip("先备份并核验已保存工程;不重复调用原生替换。混合状态或连接异常时保留保护。")
|
||||
self.pause_button = QPushButton("暂停", objectName="pauseTaskButton")
|
||||
self.resume_button = QPushButton("继续", objectName="resumeTaskButton")
|
||||
self.capture_before_button = QPushButton("采集替换前结果", objectName="captureBeforeButton")
|
||||
self.confirm_attempt_button = QPushButton("已完成原生替换", objectName="confirmNativeAttemptButton")
|
||||
self.capture_after_button = QPushButton("采集替换后结果", objectName="captureAfterButton")
|
||||
self.copy_value_check = QCheckBox("替换后将 Part Label 写入 Value", objectName="copyPartNumberToValue")
|
||||
self.copy_value_check.setToolTip("勾选:将替换后目标器件的 Part Label 写入 Value。未勾选:保留原生替换后的 Value,不创建缺失字段。两种模式均继承已有 Value 的位置、字体等显示样式。队列生成后不可更改。")
|
||||
self.toggle_log_button = QToolButton(objectName="toggleLogButton")
|
||||
self.toggle_log_button.setText("显示日志")
|
||||
self.toggle_log_button.setCheckable(True)
|
||||
self.reset_layout_button = QToolButton(objectName="resetLayoutButton")
|
||||
self.reset_layout_button.setText("重置布局")
|
||||
self.log_view = QTextEdit(objectName="logView")
|
||||
self.log_view.setReadOnly(True)
|
||||
self.log_view.setMinimumHeight(40)
|
||||
self.log_view.hide()
|
||||
self.toggle_log_button.toggled.connect(self.log_view.setVisible)
|
||||
self.toggle_log_button.toggled.connect(lambda checked: self.toggle_log_button.setText("收起日志" if checked else "显示日志"))
|
||||
commands = QHBoxLayout()
|
||||
for button in (
|
||||
self.quick_run_button,
|
||||
self.stop_queue_button,
|
||||
self.continue_without_backup_button,
|
||||
self.recover_button,
|
||||
):
|
||||
commands.addWidget(button)
|
||||
commands.addStretch(1)
|
||||
commands.addWidget(self.toggle_log_button)
|
||||
commands.addWidget(self.reset_layout_button)
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addWidget(self.queue_summary)
|
||||
layout.addWidget(self.execution_status)
|
||||
layout.addWidget(self.busy_indicator)
|
||||
layout.addWidget(self.operator_band)
|
||||
layout.addWidget(self.copy_value_check)
|
||||
layout.addLayout(commands)
|
||||
layout.addWidget(self.log_view, 1)
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Restrained, work-focused styling for the trial task center."""
|
||||
|
||||
APP_STYLESHEET = """
|
||||
QWidget { background: #f4f6f8; color: #17212b; font-size: 13px; }
|
||||
QWidget#taskNavigation, QWidget#workspace, QTextEdit { background: #ffffff; border: 1px solid #cbd5df; }
|
||||
QPushButton, QComboBox, QLineEdit, QTableWidget { border: 1px solid #aebdca; border-radius: 4px; background: #ffffff; }
|
||||
QPushButton { min-height: 30px; padding: 2px 9px; }
|
||||
QPushButton:hover { background: #edf4fa; }
|
||||
QPushButton:disabled { color: #81909c; background: #e8edf1; }
|
||||
QPushButton#quickRunButton { background: #1769aa; color: white; border-color: #1769aa; font-weight: 600; }
|
||||
QPushButton#quickRunButton:hover { background: #12588f; }
|
||||
QPushButton#quickRunButton:disabled { background: #d9e2e9; color: #667784; border-color: #cbd5df; }
|
||||
QPushButton#deleteTaskButton, QPushButton#deleteMappingButton { color: #9f2018; border-color: #d5a29d; }
|
||||
QPushButton#deleteTaskButton:hover, QPushButton#deleteMappingButton:hover { background: #fff0ee; }
|
||||
QPushButton#deleteTaskButton:disabled, QPushButton#deleteMappingButton:disabled { color: #81909c; border-color: #cbd5df; background: #e8edf1; }
|
||||
QLineEdit, QComboBox { min-height: 28px; padding: 0 6px; }
|
||||
QTableWidget { gridline-color: #d8e0e7; selection-background-color: #dbeeff; selection-color: #17212b; }
|
||||
QHeaderView::section { background: #e8edf1; border: 0; border-bottom: 1px solid #cbd5df; padding: 5px; font-weight: 600; }
|
||||
QListWidget { background: #ffffff; border: 1px solid #cbd5df; }
|
||||
QListWidget::item { padding: 6px; }
|
||||
QListWidget::item:selected { background: #dbeeff; color: #17212b; }
|
||||
QLabel#operatorBand { background: #fff8d9; border: 1px solid #dfbf4b; padding: 7px; color: #5a4600; }
|
||||
QLabel#operatorBand[state="success"] { background: #edf8f1; border-color: #71a982; color: #245b35; }
|
||||
QLabel#operatorBand[state="error"] { background: #fff0ee; border-color: #d58b84; color: #84251e; }
|
||||
QLabel#operatorBand[state="busy"] { background: #edf4fa; border-color: #83abc9; color: #234f70; }
|
||||
QLabel#operatorBand[state="info"] { background: #edf4fa; border-color: #83abc9; color: #234f70; }
|
||||
QLabel#operatorBand[state="warning"] { background: #fff8d9; border-color: #dfbf4b; color: #5a4600; }
|
||||
QLabel#queueSummary { color: #263b49; font-weight: 600; }
|
||||
QLabel#executionStatus { color: #49616f; }
|
||||
QProgressBar#quickRunBusyIndicator { border: 0; background: #dbe4ea; }
|
||||
QProgressBar#quickRunBusyIndicator::chunk { background: #1769aa; }
|
||||
QSplitter::handle { background: #bccbd8; border: 1px solid #e7edf2; }
|
||||
QSplitter::handle:hover { background: #83abc9; }
|
||||
QToolButton { background: #ffffff; border: 1px solid #aebdca; border-radius: 4px; padding: 4px 7px; }
|
||||
QToolButton:hover { background: #edf4fa; }
|
||||
QLabel#statusLabel { color: #49616f; }
|
||||
QTextEdit { padding: 5px; font-family: Consolas, "Courier New", monospace; }
|
||||
"""
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Task navigation widget with Active, Completed, and Deleted filters."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import Iterable
|
||||
|
||||
from PySide6.QtCore import Qt, QSignalBlocker
|
||||
from PySide6.QtWidgets import QComboBox, QGridLayout, QListWidget, QListWidgetItem, QPushButton, QVBoxLayout, QWidget
|
||||
|
||||
|
||||
class TaskList(QWidget):
|
||||
def __init__(self, on_open: Callable[[str], None]) -> None:
|
||||
super().__init__()
|
||||
self.setObjectName("taskNavigation")
|
||||
self.filter = QComboBox(objectName="taskFilter")
|
||||
self.filter.addItems(("进行中", "已完成", "已删除"))
|
||||
self.list = QListWidget(objectName="taskList")
|
||||
self.new_button = QPushButton("新建", objectName="newTaskButton")
|
||||
self.edit_button = QPushButton("编辑", objectName="editTaskButton")
|
||||
self.delete_button = QPushButton("删除", objectName="deleteTaskButton")
|
||||
self.restore_button = QPushButton("恢复", objectName="restoreTaskButton")
|
||||
actions = QGridLayout()
|
||||
actions.addWidget(self.new_button, 0, 0)
|
||||
actions.addWidget(self.edit_button, 0, 1)
|
||||
actions.addWidget(self.delete_button, 1, 0)
|
||||
actions.addWidget(self.restore_button, 1, 1)
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(8, 8, 8, 8)
|
||||
layout.addWidget(self.filter)
|
||||
layout.addWidget(self.list, 1)
|
||||
layout.addLayout(actions)
|
||||
self.list.itemSelectionChanged.connect(lambda: on_open(self.current_task_id() or ""))
|
||||
|
||||
def current_task_id(self) -> str | None:
|
||||
item = self.list.currentItem()
|
||||
return str(item.data(Qt.ItemDataRole.UserRole)) if item is not None else None
|
||||
|
||||
def populate(self, tasks: Iterable[object]) -> None:
|
||||
selected = self.current_task_id()
|
||||
with QSignalBlocker(self.list):
|
||||
self.list.clear()
|
||||
for task in tasks:
|
||||
item = QListWidgetItem(str(getattr(task, "name")))
|
||||
item.setData(Qt.ItemDataRole.UserRole, str(getattr(task, "task_id")))
|
||||
self.list.addItem(item)
|
||||
if getattr(task, "task_id") == selected:
|
||||
self.list.setCurrentItem(item)
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Reusable QThreadPool wrappers for service calls that perform I/O."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import QObject, QRunnable, Signal, Slot
|
||||
|
||||
|
||||
class WorkerSignals(QObject):
|
||||
"""Signals emitted for a single background callable."""
|
||||
|
||||
succeeded = Signal(object)
|
||||
failed = Signal(object)
|
||||
finished = Signal()
|
||||
|
||||
|
||||
class ServiceWorker(QRunnable):
|
||||
"""Run one service callable without blocking the Qt event loop."""
|
||||
|
||||
def __init__(self, action: Callable[[], Any]) -> None:
|
||||
super().__init__()
|
||||
self.action = action
|
||||
self.signals = WorkerSignals()
|
||||
|
||||
@Slot()
|
||||
def run(self) -> None:
|
||||
try:
|
||||
self.signals.succeeded.emit(self.action())
|
||||
except Exception as error: # Service converts unexpected errors to stable TaskCenterError values.
|
||||
self.signals.failed.emit(error)
|
||||
finally:
|
||||
self.signals.finished.emit()
|
||||
@@ -0,0 +1 @@
|
||||
VERSION = "1.0.0"
|
||||
@@ -0,0 +1,229 @@
|
||||
"""Monitor correlated work progress and request cancellation before escalation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import queue
|
||||
import re
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
class WorkerMonitorError(subprocess.SubprocessError):
|
||||
pass
|
||||
|
||||
|
||||
class ProgressWatch:
|
||||
def __init__(self, token: str, job_id: str, idle_timeout: float, started: float) -> None:
|
||||
if idle_timeout <= 0:
|
||||
raise ValueError('Idle timeout must be positive')
|
||||
self.token = token
|
||||
self.job_id = job_id
|
||||
self.idle_timeout = idle_timeout
|
||||
self.last_progress = started
|
||||
self.sequence = 0
|
||||
self.stop_requested = False
|
||||
self.stage = 'starting'
|
||||
self.done = 0
|
||||
self.total = 0
|
||||
self.safe_stop = True
|
||||
|
||||
def accept(self, line: bytes, now: float) -> bool:
|
||||
try:
|
||||
fields = line.decode('ascii').strip().split('\t')
|
||||
if len(fields) != 8 or fields[:3] != ['DX_PROGRESS', self.token, self.job_id]:
|
||||
return False
|
||||
sequence, done, total, safe = (int(fields[index]) for index in (3, 5, 6, 7))
|
||||
if not self.sequence < sequence <= 2**31 - 1 or not re.fullmatch('[a-z_]{1,64}', fields[4]):
|
||||
return False
|
||||
if done < 0 or total < 0 or (total and done > total) or safe not in {0, 1}:
|
||||
return False
|
||||
except (ValueError, UnicodeError):
|
||||
return False
|
||||
self.sequence = sequence
|
||||
self.last_progress = now
|
||||
self.stage, self.done, self.total, self.safe_stop = fields[4], done, total, bool(safe)
|
||||
return True
|
||||
|
||||
def action(self, now: float) -> str | None:
|
||||
idle = now - self.last_progress
|
||||
if not self.stop_requested and idle >= self.idle_timeout:
|
||||
self.stop_requested = True
|
||||
return 'request_stop'
|
||||
if self.stop_requested and idle >= self.idle_timeout * 2:
|
||||
return 'unresponsive'
|
||||
return None
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
return {name: getattr(self, name) for name in ('token', 'job_id', 'sequence', 'stage', 'done', 'total', 'safe_stop', 'stop_requested')}
|
||||
|
||||
|
||||
def _atomic_text(path: Path, text: str) -> None:
|
||||
temporary = path.with_name(path.name + '.tmp')
|
||||
temporary.write_text(text, encoding='utf-8')
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
def _publish_progress(path: Path, snapshot: dict) -> None:
|
||||
try:
|
||||
_atomic_text(path, json.dumps(snapshot, ensure_ascii=False))
|
||||
except OSError as error:
|
||||
if not isinstance(error, PermissionError) and getattr(error, 'winerror', None) not in {5, 32, 33}:
|
||||
raise
|
||||
|
||||
|
||||
def _decode(data: bytes) -> str:
|
||||
try:
|
||||
return data.decode('utf-8')
|
||||
except UnicodeError:
|
||||
return data.decode('mbcs' if os.name == 'nt' else 'utf-8', errors='replace')
|
||||
|
||||
|
||||
class _OwnedWorkers:
|
||||
def __init__(self, token: str, allowed: set[str]) -> None:
|
||||
import win32job
|
||||
|
||||
self.job = win32job.CreateJobObject(None, 'DxPartReplace-monitor-' + token)
|
||||
self.allowed = {os.path.normcase(os.path.abspath(value)) for value in allowed}
|
||||
|
||||
def assign(self, process: subprocess.Popen) -> None:
|
||||
import win32job
|
||||
|
||||
win32job.AssignProcessToJobObject(self.job, process._handle)
|
||||
|
||||
def stop_workers(self, process: subprocess.Popen) -> list[str]:
|
||||
import win32api
|
||||
import win32job
|
||||
|
||||
failures = []
|
||||
query_name = ctypes.WinDLL('kernel32', use_last_error=True).QueryFullProcessImageNameW
|
||||
query_name.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_wchar_p, ctypes.POINTER(ctypes.c_ulong)]
|
||||
query_name.restype = ctypes.c_int
|
||||
try:
|
||||
process_ids = win32job.QueryInformationJobObject(self.job, win32job.JobObjectBasicProcessIdList)
|
||||
for process_id in process_ids:
|
||||
if process_id == process.pid:
|
||||
continue
|
||||
handle = None
|
||||
try:
|
||||
handle = win32api.OpenProcess(0x1000 | 0x0001, False, process_id)
|
||||
size = ctypes.c_ulong(32768)
|
||||
buffer = ctypes.create_unicode_buffer(size.value)
|
||||
if not query_name(int(handle), 0, buffer, ctypes.byref(size)):
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
executable = os.path.normcase(os.path.abspath(buffer.value))
|
||||
if executable in self.allowed and Path(executable).name.casefold() != 'viewdraw.exe':
|
||||
win32api.TerminateProcess(handle, 1)
|
||||
else:
|
||||
failures.append(f'preserved_non_worker pid={process_id}')
|
||||
except Exception as error:
|
||||
failures.append(f'child_cleanup pid={process_id} error={error}')
|
||||
finally:
|
||||
if handle is not None:
|
||||
handle.Close()
|
||||
except Exception as error:
|
||||
failures.append(f'job_cleanup error={error}')
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
return failures
|
||||
|
||||
def close(self) -> None:
|
||||
self.job.Close()
|
||||
|
||||
|
||||
def run_monitored_process(command: tuple[str, ...], idle_timeout: float) -> subprocess.CompletedProcess[str]:
|
||||
root = Path(command[3])
|
||||
job_id = command[-1]
|
||||
token = uuid4().hex
|
||||
ready = root / f'monitor-{token}.ready'
|
||||
stop = root / f'monitor-{token}.stop'
|
||||
progress_path = root / 'worker-progress.json'
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
watch = ProgressWatch(token, job_id, idle_timeout, time.monotonic())
|
||||
owned = _OwnedWorkers(token, {command[0], command[4]})
|
||||
process = None
|
||||
threads = []
|
||||
messages = queue.Queue(maxsize=1024)
|
||||
stop_readers = threading.Event()
|
||||
output = [bytearray(), bytearray()]
|
||||
|
||||
def read_stream(stream, channel):
|
||||
try:
|
||||
while not stop_readers.is_set():
|
||||
line = stream.readline(16384)
|
||||
if not line:
|
||||
break
|
||||
while not stop_readers.is_set():
|
||||
try:
|
||||
messages.put((channel, line), timeout=0.1)
|
||||
break
|
||||
except queue.Full:
|
||||
pass
|
||||
finally:
|
||||
stream.close()
|
||||
|
||||
def receive(channel, line):
|
||||
if channel == 0 and watch.accept(line, time.monotonic()):
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
elif len(output[channel]) < 1024 * 1024:
|
||||
output[channel].extend(line[:1024 * 1024 - len(output[channel])])
|
||||
|
||||
try:
|
||||
process = subprocess.Popen((*command, token), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
owned.assign(process)
|
||||
for channel, stream in enumerate((process.stdout, process.stderr)):
|
||||
thread = threading.Thread(target=read_stream, args=(stream, channel), daemon=True)
|
||||
thread.start()
|
||||
threads.append(thread)
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
_atomic_text(ready, token)
|
||||
while process.poll() is None:
|
||||
try:
|
||||
receive(*messages.get(timeout=min(0.1, idle_timeout / 10)))
|
||||
for pending in range(128):
|
||||
receive(*messages.get_nowait())
|
||||
except queue.Empty:
|
||||
pass
|
||||
if process.poll() is not None:
|
||||
break
|
||||
action = watch.action(time.monotonic())
|
||||
if action == 'request_stop':
|
||||
_atomic_text(stop, token)
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
elif action == 'unresponsive':
|
||||
raise subprocess.TimeoutExpired(command, idle_timeout * 2)
|
||||
drain_deadline = time.monotonic() + 5
|
||||
while (any(thread.is_alive() for thread in threads) or not messages.empty()) and time.monotonic() < drain_deadline:
|
||||
try:
|
||||
receive(*messages.get(timeout=0.05))
|
||||
except queue.Empty:
|
||||
pass
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
return subprocess.CompletedProcess(command, process.returncode, _decode(output[0]), _decode(output[1]))
|
||||
except Exception as error:
|
||||
if process is not None:
|
||||
failures = owned.stop_workers(process)
|
||||
process.wait(timeout=10)
|
||||
for thread in threads:
|
||||
thread.join(2)
|
||||
diagnostic = watch.snapshot() | {'monitor_error': str(error), 'worker_cleanup_notes': failures}
|
||||
try:
|
||||
_atomic_text(progress_path, json.dumps(diagnostic, ensure_ascii=False))
|
||||
except OSError:
|
||||
pass
|
||||
if isinstance(error, subprocess.TimeoutExpired):
|
||||
raise
|
||||
raise WorkerMonitorError(f'Worker monitoring failed after launch; execution requires reconciliation: {error}') from error
|
||||
raise
|
||||
finally:
|
||||
stop_readers.set()
|
||||
for thread in threads:
|
||||
thread.join(0.2)
|
||||
owned.close()
|
||||
@@ -0,0 +1,28 @@
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.part_replace.models import ComponentSnapshot, DesignSnapshot, PinSnapshot, UnitSnapshot
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def accept_minimal_project_placeholders(monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest) -> None:
|
||||
if request.node.path.name != "test_scanner.py":
|
||||
monkeypatch.setattr(
|
||||
"dx_productivity.trial_task_center.scanner._is_schematic_project",
|
||||
lambda _path: True,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def snapshot_factory():
|
||||
"""Return a fresh minimal snapshot factory for tests."""
|
||||
def make(project_id: str = "p1", part_number: str = "OLD-1") -> DesignSnapshot:
|
||||
pin = PinSnapshot("1", "A", Decimal("10.25"), Decimal("20"), "N$1")
|
||||
unit = UnitSnapshot(
|
||||
"u1", "/MAIN", "res.1", Decimal("0"), Decimal("0"),
|
||||
Decimal("0"), Decimal("0"), 0, False, (pin,),
|
||||
)
|
||||
component = ComponentSnapshot("/MAIN|R1", "R1", part_number, (unit,), ())
|
||||
return DesignSnapshot(2, project_id, "C:/P/a.prj", "abc", (component,))
|
||||
return make
|
||||
@@ -0,0 +1,206 @@
|
||||
{
|
||||
"format_version": 1,
|
||||
"dxdesigner": {
|
||||
"build": "7.9.5.1234",
|
||||
"version": "7.9.5"
|
||||
},
|
||||
"project": {
|
||||
"active_view": "Sheet1",
|
||||
"dirty": false,
|
||||
"identity": "probe-fixture"
|
||||
},
|
||||
"enumeration": {
|
||||
"available": true,
|
||||
"component_count": 1,
|
||||
"route": "Application.DesignComponents"
|
||||
},
|
||||
"components": [
|
||||
{
|
||||
"api_errors": [
|
||||
{
|
||||
"description": "fixture error",
|
||||
"number": 51001,
|
||||
"operation": "fixture.operation",
|
||||
"source": "fixture.source"
|
||||
}
|
||||
],
|
||||
"attributes": [
|
||||
{
|
||||
"name": "Vendor",
|
||||
"value": "Acme"
|
||||
}
|
||||
],
|
||||
"gates": [
|
||||
{
|
||||
"name": "A",
|
||||
"unit_number": 1
|
||||
}
|
||||
],
|
||||
"hierarchy": "/MAIN",
|
||||
"logical_identity": "/MAIN|U1",
|
||||
"mirror": false,
|
||||
"nets": [
|
||||
"N1"
|
||||
],
|
||||
"origin": {
|
||||
"x": 0.5,
|
||||
"y": 1
|
||||
},
|
||||
"part_number": "OLD-1",
|
||||
"pins": [
|
||||
{
|
||||
"name": "IN",
|
||||
"net_identity": "N1",
|
||||
"number": "1",
|
||||
"x": 0,
|
||||
"y": 1.5
|
||||
},
|
||||
{
|
||||
"name": "NC",
|
||||
"net_identity": null,
|
||||
"number": "2",
|
||||
"x": 2,
|
||||
"y": 3
|
||||
}
|
||||
],
|
||||
"position": {
|
||||
"x": 10,
|
||||
"y": 20
|
||||
},
|
||||
"refdes": "U1",
|
||||
"rotation": 90,
|
||||
"symbol_identity": "IC_A",
|
||||
"units": 1
|
||||
}
|
||||
],
|
||||
"interfaces": {
|
||||
"attributes": {"available": true},
|
||||
"gates": {"available": true},
|
||||
"hierarchy": {"available": true},
|
||||
"logical_identity": {"available": true},
|
||||
"mirror": {"available": true},
|
||||
"nets": {"available": true},
|
||||
"origin_x": {"available": true},
|
||||
"origin_y": {"available": true},
|
||||
"part_number": {"available": true},
|
||||
"pins": {"available": true},
|
||||
"position_x": {"available": true},
|
||||
"position_y": {"available": true},
|
||||
"refdes": {"available": true},
|
||||
"rotation": {"available": true},
|
||||
"symbol_identity": {"available": true},
|
||||
"units": {"available": true}
|
||||
},
|
||||
"production_replace_route": "native_replace_part",
|
||||
"routes": {
|
||||
"exact_set_selection": {
|
||||
"attempted": true,
|
||||
"available": true,
|
||||
"manual_fallback": "manual_exact_set_selection",
|
||||
"route": "ActiveView.SelectExactSet",
|
||||
"attempts": [{"attempted": true, "available": true, "error": null, "route": "ActiveView.SelectExactSet"}]
|
||||
},
|
||||
"native_replace_part": {
|
||||
"attempted": true,
|
||||
"available": true,
|
||||
"manual_fallback": "manual_native_replace_part",
|
||||
"route": "Application.OpenReplacePartDialog",
|
||||
"attempts": [{"attempted": true, "available": true, "error": null, "route": "Application.OpenReplacePartDialog"}]
|
||||
},
|
||||
"completion_observation": {
|
||||
"attempted": true,
|
||||
"available": true,
|
||||
"manual_fallback": "manual_completion_observation",
|
||||
"route": "Application.ReplacePartCompleted",
|
||||
"attempts": [{"attempted": true, "available": true, "error": null, "route": "Application.ReplacePartCompleted"}]
|
||||
},
|
||||
"undo": {
|
||||
"attempted": true,
|
||||
"available": true,
|
||||
"manual_fallback": "manual_undo",
|
||||
"route": "Application.Undo",
|
||||
"attempts": [{"attempted": true, "available": true, "error": null, "route": "Application.Undo"}]
|
||||
},
|
||||
"save": {
|
||||
"attempted": true,
|
||||
"available": true,
|
||||
"manual_fallback": "manual_save",
|
||||
"route": "Application.Save",
|
||||
"attempts": [{"attempted": true, "available": true, "error": null, "route": "Application.Save"}]
|
||||
},
|
||||
"open_project": {
|
||||
"attempted": true,
|
||||
"available": true,
|
||||
"manual_fallback": "manual_open_project",
|
||||
"route": "Application.OpenProject",
|
||||
"attempts": [{"attempted": true, "available": true, "error": null, "route": "Application.OpenProject"}]
|
||||
},
|
||||
"close_project": {
|
||||
"attempted": true,
|
||||
"available": true,
|
||||
"manual_fallback": "manual_close_project",
|
||||
"route": "Application.CloseProject",
|
||||
"attempts": [{"attempted": true, "available": true, "error": null, "route": "Application.CloseProject"}]
|
||||
},
|
||||
"packager": {
|
||||
"attempted": true,
|
||||
"available": true,
|
||||
"manual_fallback": "manual_packager",
|
||||
"route": "Application.RunPackager",
|
||||
"attempts": [{"attempted": true, "available": true, "error": null, "route": "Application.RunPackager"}]
|
||||
},
|
||||
"erc": {
|
||||
"attempted": true,
|
||||
"available": true,
|
||||
"manual_fallback": "manual_erc",
|
||||
"route": "Application.RunERC",
|
||||
"attempts": [{"attempted": true, "available": true, "error": null, "route": "Application.RunERC"}]
|
||||
},
|
||||
"netlist": {
|
||||
"attempted": true,
|
||||
"available": true,
|
||||
"manual_fallback": "manual_netlist",
|
||||
"route": "Application.RunNetlist",
|
||||
"attempts": [{"attempted": true, "available": true, "error": null, "route": "Application.RunNetlist"}]
|
||||
},
|
||||
"ccomp_research": {
|
||||
"attempted": true,
|
||||
"available": false,
|
||||
"manual_fallback": "manual_ccomp_research",
|
||||
"route": "Application.CComp",
|
||||
"attempts": [
|
||||
{
|
||||
"attempted": true,
|
||||
"available": false,
|
||||
"error": {
|
||||
"description": "fixture error",
|
||||
"number": 51001,
|
||||
"operation": "fixture.operation",
|
||||
"source": "fixture.source"
|
||||
},
|
||||
"route": "Application.CComp"
|
||||
}
|
||||
],
|
||||
"production_enabled": false
|
||||
}
|
||||
},
|
||||
"safety": {
|
||||
"disposable_project_marker": true,
|
||||
"mutating_probe_attempted": true,
|
||||
"mutating_probe_authorized": true,
|
||||
"operator_confirmation": true,
|
||||
"request_valid": true
|
||||
},
|
||||
"api_errors": [
|
||||
{
|
||||
"description": "fixture error",
|
||||
"number": 51001,
|
||||
"operation": "fixture.operation",
|
||||
"source": "fixture.source"
|
||||
}
|
||||
],
|
||||
"live_acceptance": {
|
||||
"checked": false,
|
||||
"reason": "live_795_host_not_exercised"
|
||||
}
|
||||
}
|
||||
Loaded 100 of 151 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user