feat: add complete yiyezhqiu productivity suite

This commit is contained in:
阿白叔 committed 2026-10-10 17:10:32 +08:00
commit e422ca8b2a
155 files changed
+18959

No files matched your search

@@ -0,0 +1,569 @@
# DxDesigner 7.9.5 Portable Offline Release 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 one portable Windows 11 x64 ZIP that runs the automatic-reference-designator tool offline without a system Python installation and integrates through a root-level `MenuAdd.vbs` imported by DxDesigner 7.9.5.
**Architecture:** DxDesigner owns all schematic API access through ASCII-only VBS. The bridge exports a versioned UTF-8 snapshot, starts a PyInstaller `onedir` executable beside the scripts, and applies only a validated result schedule after creating a backup. Python/PySide6 owns the UI, planning, validation, immutable result generation, and user-local history.
**Tech Stack:** Python 3.12, PySide6 Essentials 6.x, qtawesome 1.x, PyInstaller 6.x, VBScript, PowerShell 5.1+, pytest, pytest-qt
**Spec:** `docs/superpowers/specs/2026-09-01-dxdesigner-795-refdes-design.md`
## Global Constraints
- Supported schematic integration baseline: DxDesigner/Expedition Enterprise 7.9.5 only.
- Supported release operating system and architecture: Windows 11 x64.
- The target computer requires no Python installation and no network access.
- The release is one portable ZIP; it uses no installer, registry entry, environment variable, administrator privilege, newer Xpedition add-in framework, copied newer-release DLL, COM re-registration, or project-format upgrade.
- The user imports only the root `MenuAdd.vbs` through `Settings -> Run at Startup -> Scripts`.
- `MenuAdd.vbs` resolves bundled files from its own loaded location; there is no fixed drive path or `DXTOOLS_HOME` dependency.
- Every DxDesigner API call remains in VBS; Python never attaches to `ViewDraw.Application` or another DxDesigner COM server.
- Every VBS source is ASCII-only; Chinese captions and messages are assembled with `ChrW`.
- Run mailboxes, backups, history, logs, and preferences live under `%LOCALAPPDATA%\DxProductivity`.
- A live 7.9.5 acceptance failure blocks the 7.9.5 compatibility claim even when all mocked tests pass.
---
## File Structure
- `src/dx_productivity/bridge/protocol.py`: read/write the versioned snapshot, apply request, schedule, and apply status.
- `src/dx_productivity/bridge/launcher.py`: dispatch packaged probe and UI modes without relying on `py.exe`.
- `src/dx_productivity/ui/refdes_controller.py`: publish backup metadata before the schedule-ready signal.
- `integration/dxdesigner795/BridgeCommon.vbs`: focused ASCII-only UTF-8, JSON, TSV, and atomic-file helpers, packaged under `_runtime/vbs`.
- `integration/dxdesigner795/MenuAdd.vbs`: idempotent 7.9.5 menu registration and portable-root discovery.
- `integration/dxdesigner795/RefDesBridge.vbs`: snapshot export, mailbox loop, stale-state check, write-back, verification, and rollback.
- `integration/dxdesigner795/CompatibilityProbe.vbs`: read-only evidence for menu route, script-path source, API fields, and message-pump method.
- `packaging/DxDesignerTools.spec`: PyInstaller `onedir` definition with `_runtime` contents directory.
- `packaging/build_release.ps1`: reproducible x64 build, portable layout assembly, ZIP creation, and SHA-256 manifest.
- `tests/bridge/`, `tests/integration/`, `tests/vbs/`, `tests/packaging/`: contract, static-safety, mocked transaction, and built-artifact tests.
- `docs/user/DxDesigner_7.9.5_自动位号工具使用说明.docx`: offline user guide matching the portable workflow.
- `docs/testing/dxdesigner-795-live.md`: target-machine acceptance record.
---
### Task 1: Complete the Transaction Protocol and Packaged Launcher
**Files:**
- Create: `src/dx_productivity/bridge/launcher.py`
- Modify: `src/dx_productivity/bridge/protocol.py`
- Modify: `src/dx_productivity/domain/models.py`
- Modify: `src/dx_productivity/ui/refdes_controller.py`
- Modify: `src/dx_productivity/ui/app.py`
- Modify: `src/dx_productivity/__main__.py`
- Test: `tests/bridge/test_protocol.py`
- Test: `tests/bridge/test_launcher.py`
- Test: `tests/ui/test_refdes_controller.py`
**Interfaces:**
- Consumes: `DesignSnapshot`, `AnnotationPlan`, `RunPaths`, `probe_host.main`, and command-line arguments.
- Produces: `ApplyRequest`, `write_apply_request(path, request)`, `load_apply_request(path)`, `launcher.main(argv) -> int`, and `RunPaths.apply_request`.
- `ApplyRequest` fields are `format_version: int`, `run_id: str`, `snapshot_id: str`, `backup_path: Path`, and `schedule_sha256: str`.
- [ ] **Step 1: Write failing apply-request protocol tests**
```python
def test_apply_request_round_trip(tmp_path: Path) -> None:
request = ApplyRequest(1, "run-a", "snapshot-a", tmp_path / "备份.json", "a" * 64)
path = tmp_path / "apply-request.json"
write_apply_request(path, request)
assert load_apply_request(path) == request
def test_run_paths_exposes_apply_request(run_paths: RunPaths) -> None:
assert run_paths.apply_request == run_paths.root / "apply-request.json"
```
- [ ] **Step 2: Run the focused protocol tests and confirm failure**
Run: `py -3.12 -m pytest tests/bridge/test_protocol.py -v`
Expected: FAIL because `ApplyRequest`, its serializers, and `RunPaths.apply_request` do not exist.
- [ ] **Step 3: Implement immutable apply metadata and strict validation**
Add `ApplyRequest` to `models.py`. Add an `apply_request` property to `RunPaths` so existing positional construction remains compatible. In `protocol.py`, atomically write UTF-8 JSON with `ensure_ascii=False`, require `format_version == 1`, require matching nonempty run/snapshot IDs, require an absolute nonempty backup path, and require a lowercase 64-character hexadecimal SHA-256.
Add `schedule_sha256(schedule: tuple[ApplyStep, ...]) -> str` using the exact UTF-8 TSV bytes produced by `write_schedule`. One canonical `_schedule_text` helper must feed both hashing and file output.
- [ ] **Step 4: Write failing publication-order and launcher-dispatch tests**
```python
def test_apply_publishes_metadata_before_result(controller, monkeypatch):
calls = []
monkeypatch.setattr(protocol, "write_apply_request", lambda *args: calls.append("metadata"))
monkeypatch.setattr(protocol, "write_schedule", lambda *args: calls.append("result"))
controller.apply()
assert calls == ["metadata", "result"]
def test_launcher_dispatches_probe_without_starting_qt(monkeypatch, tmp_path):
called = []
monkeypatch.setattr(launcher, "probe_main", lambda argv: called.append(argv) or 0)
assert launcher.main(["probe", "--output", str(tmp_path / "probe.json")]) == 0
assert called[0][0:2] == ["--output", str(tmp_path / "probe.json")]
```
- [ ] **Step 5: Run the focused tests and confirm failure**
Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest tests/bridge/test_launcher.py tests/ui/test_refdes_controller.py -v`
Expected: FAIL because the packaged launcher and ordered apply metadata publication are absent.
- [ ] **Step 6: Implement launcher modes and publication order**
`launcher.main` accepts exactly two modes:
- `probe ...` delegates remaining arguments to `probe_host.main` without creating `QApplication`;
- `ui --request <absolute request.json>` delegates to `ui.app.main`.
No mode defaults to `ui` for direct user launches. The UI parser also accepts the packaging-only `--smoke-test-ms <positive integer>` option; after the window is shown it schedules `QApplication.quit` with `QTimer.singleShot`, while normal launches omit the option and remain interactive. Update `__main__.py` to call `launcher.main`. In `RefDesController.apply`, write the backup, compute the schedule digest, atomically publish `apply-request.json`, then publish `result.tsv` last as the bridge-ready signal.
- [ ] **Step 7: Run focused and full Python tests**
Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest tests/bridge tests/ui/test_refdes_controller.py -v`
Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest -q`
Expected: all tests pass.
- [ ] **Step 8: Commit the transaction protocol**
```powershell
git add src/dx_productivity/bridge src/dx_productivity/domain/models.py src/dx_productivity/ui/refdes_controller.py src/dx_productivity/ui/app.py src/dx_productivity/__main__.py tests/bridge tests/ui/test_refdes_controller.py
git commit -m "feat: complete packaged bridge transaction protocol"
```
### Task 2: Add Portable Script Discovery, Shared VBS Helpers, and Menu Registration
**Files:**
- Create: `integration/dxdesigner795/BridgeCommon.vbs`
- Create: `integration/dxdesigner795/MenuAdd.vbs`
- Create: `tests/vbs/test_bridge_common.vbs`
- Create: `tests/integration/test_menu_script.py`
- Modify: `integration/dxdesigner795/CompatibilityProbe.vbs`
- Modify: `tests/integration/test_compatibility_probe.py`
**Interfaces:**
- Consumes: the loaded startup-script path exposed by the DxDesigner 7.9.5 host and root siblings `RefDesBridge.vbs` and `DxDesignerTools.exe`.
- Produces: menu-local `DxToolsResolveRoot()`, shared `DxToolsQuote(value)`, `DxToolsJson(value)`, `DxToolsReadUtf8(path)`, `DxToolsWriteUtf8Atomic(path, text)`, and the named menu action `DxToolsRunRefDes`.
- [ ] **Step 1: Write failing static portable-root and menu tests**
```python
def test_menu_is_ascii_portable_and_uses_795_menu_bar():
text = Path("integration/dxdesigner795/MenuAdd.vbs").read_text("ascii")
assert 'CommandBars("Sheet Menu Bar")' in text
assert "DxToolsResolveRoot" in text
assert "DXTOOLS_HOME" not in text
assert "D:\\" not in text
assert "WScript.Shell" in text
assert text.isascii()
def test_probe_records_script_path_source():
text = Path("integration/dxdesigner795/CompatibilityProbe.vbs").read_text("ascii")
assert '"script_path_source"' in text
assert '"portable_root_valid"' in text
```
- [ ] **Step 2: Run the menu/probe tests and confirm failure**
Run: `py -3.12 -m pytest tests/integration/test_menu_script.py tests/integration/test_compatibility_probe.py -v`
Expected: FAIL because the release menu and self-location evidence are absent and the probe still depends on `DXTOOLS_HOME` and `py -3.12`.
- [ ] **Step 3: Write cscript tests for pure VBS helpers**
`tests/vbs/test_bridge_common.vbs` loads `BridgeCommon.vbs` and asserts JSON escaping for quote, slash, CR, LF, and tab; quoting of a path containing Chinese characters and spaces; UTF-8 round-trip; atomic replacement; and rejection of a malformed five-field schedule row.
Run: `cscript //nologo tests\vbs\test_bridge_common.vbs`
Expected: FAIL because `BridgeCommon.vbs` does not exist.
- [ ] **Step 4: Implement isolated ASCII-only helpers**
`BridgeCommon.vbs` keeps `On Error Resume Next` inside individual compatibility probes only and restores normal error handling immediately. UTF-8 functions use `ADODB.Stream`; atomic output writes a same-directory `.tmp` and then replaces the destination. All command arguments use one double-quote helper. It is loaded from `_runtime\vbs\BridgeCommon.vbs` by `MenuAdd.vbs` before either root bridge script is evaluated.
`DxToolsResolveRoot` tests these loaded-script full-name candidates in order, with each attempt wrapped in its own immediate `Err` check: `WScript.ScriptFullName`, `Scripting.CurrentScriptFullName`, and `Scripting.ScriptFullName`. The compatibility probe records the winning property name or an empty value. A candidate is accepted only when both sibling files exist:
```text
<root>\RefDesBridge.vbs
<root>\DxDesignerTools.exe
```
It does not accept the current working directory, recursively scan drives, or consult an environment variable. If no candidate validates, it returns an empty string and the menu displays a concise path error without adding a broken command.
- [ ] **Step 5: Implement idempotent menu registration**
`MenuAdd.vbs` contains the small self-location resolver because it must discover the root before shared helpers can be loaded. It removes only an existing top-level menu with the exact suite caption before adding one replacement to `CommandBars("Sheet Menu Bar")`; it does not depend on an unproven `Tag` property. It adds `自动位号`, `兼容性检测`, and `打开使用说明` entries. Captions and errors use `ChrW`; `OnAction` routes invoke named procedures defined in the imported script so the in-process DxDesigner objects remain available. The named procedures load `_runtime\vbs\BridgeCommon.vbs` and then the root bridge/probe source with `ExecuteGlobal`, and call their explicit entry procedure; they never run a second script host process.
- [ ] **Step 6: Make the compatibility probe launch the bundled executable**
Replace both `py -3.12 -m dx_productivity.bridge.probe_host` commands with the root sibling `DxDesignerTools.exe probe ...`. Refactor the probe so loading it defines `DxToolsRunCompatibilityProbe` without creating another menu. Add `script_path_source`, resolved absolute script path, `portable_root_valid`, executable existence, and VBS yield method to `compatibility.json`. The probe remains read-only.
- [ ] **Step 7: Run VBS, static, and Python tests**
Run: `cscript //nologo tests\vbs\test_bridge_common.vbs`
Run: `py -3.12 -m pytest tests/integration/test_menu_script.py tests/integration/test_compatibility_probe.py -v`
Expected: all tests pass; `rg -n "DXTOOLS_HOME|py -3.12|D:\\NET_CHECK" integration/dxdesigner795` returns no release-script match.
- [ ] **Step 8: Commit portable script discovery and menu registration**
```powershell
git add integration/dxdesigner795 tests/vbs tests/integration/test_menu_script.py tests/integration/test_compatibility_probe.py
git commit -m "feat: add self-locating DxDesigner 7.9.5 menu"
```
### Task 3: Implement DxDesigner Snapshot, Write-Back, Verification, and Rollback
**Files:**
- Create: `integration/dxdesigner795/RefDesBridge.vbs`
- Create: `tests/integration/test_vbs_bridge.py`
- Create: `tests/integration/mock_bridge.py`
- Create: `tests/integration/test_end_to_end.py`
- Modify: `integration/dxdesigner795/BridgeCommon.vbs`
**Interfaces:**
- Consumes: root `DxDesignerTools.exe`, `RunPaths` mailbox names, the probe-confirmed 7.9.5 component properties, `apply-request.json`, and `result.tsv`.
- Produces: a version-1 `request.json`, locate handling, ordered reference-designator writes, `apply-status.json`, full-design verification, and verified rollback.
- [ ] **Step 1: Write failing static bridge-safety tests**
```python
def test_bridge_has_required_transaction_stages():
text = Path("integration/dxdesigner795/RefDesBridge.vbs").read_text("ascii")
for name in (
"DxExportSnapshot", "DxLaunchUi", "DxPreflightApply",
"DxApplySchedule", "DxVerifyDesign", "DxRollback",
):
assert f"Sub {name}" in text or f"Function {name}" in text
assert "ViewDraw.Application" not in text
assert "GetActiveObject" not in text
assert "DXTOOLS_HOME" not in text
assert text.isascii()
```
- [ ] **Step 2: Run the static test and confirm failure**
Run: `py -3.12 -m pytest tests/integration/test_vbs_bridge.py -v`
Expected: FAIL because `RefDesBridge.vbs` does not exist.
- [ ] **Step 3: Implement snapshot export with an in-memory object map**
Create a unique `%LOCALAPPDATA%\DxProductivity\runs\<UTC timestamp>-<random token>` directory. Enumerate the full design through `Application.GetProjectData()` and `Application.DesignComponents`, assign contiguous IDs `c000001`, retain each component in a `Scripting.Dictionary`, and record selection/current-sheet membership without changing the design.
Write every field required by `ComponentRecord`. A missing UID uses full path; a missing symbol default becomes JSON `null`; an unavailable lock flag becomes `false`. Missing both UID and full path aborts before launching the UI. Coordinate values use locale-independent decimal points.
- [ ] **Step 4: Implement the packaged UI launch and mailbox loop**
Launch exactly:
```text
"<portable root>\DxDesignerTools.exe" ui --request "<run root>\request.json"
```
Use `WScript.Shell.Exec`, retain the object dictionary, and pump the first method proven by the compatibility probe. Consume atomically published `locate.tsv` once and select/zoom only the mapped component. Treat `result.tsv` as ready only when `apply-request.json` also exists. Closing the UI without a result leaves the design unchanged.
- [ ] **Step 5: Implement strict preflight and ordered write-back**
Before the first write, verify active design identity, snapshot ID, run ID, component count in scope, every `bridge_id`, every `expected_refdes`, the absolute backup file existence, and the SHA-256 of the exact result TSV bytes. Reject unknown IDs, noncontiguous sequences, more than two steps per ID, illegal control characters, and mismatched expected-current chains.
Apply rows in sequence. After each assignment, immediately read `comp.Refdes` and require a case-insensitive match. After all rows, re-enumerate the full design, verify each final value, and reject duplicate formal reference designators.
- [ ] **Step 6: Implement rollback and machine-readable status**
On any write or verification failure, restore every touched object to the original value stored in the snapshot, then re-read every restored value. Atomically write `apply-status.json` with state `applied`, `rolled-back`, or `rollback-failed`, including `run_id`, changed count, backup path, failing sequence, error text, and rollback state. Never suppress an assignment error or report success before full-design verification.
- [ ] **Step 7: Build a mocked bridge transaction harness**
`MockBridge` loads a real fixture snapshot, waits for a real controller result, validates the same sequence/current-value/digest invariants as VBS, applies to an in-memory map, and can inject a stale value or assignment failure. Tests assert successful fill-only apply, cycle schedules, cancel-without-result, stale-state rejection, verified rollback, and rollback failure status parsing.
- [ ] **Step 8: Run transaction and full regression tests**
Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest tests/integration/test_vbs_bridge.py tests/integration/test_end_to_end.py -v`
Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest -q`
Expected: all tests pass.
- [ ] **Step 9: Commit the safe write-back bridge**
```powershell
git add integration/dxdesigner795/BridgeCommon.vbs integration/dxdesigner795/RefDesBridge.vbs tests/integration
git commit -m "feat: add verified refdes write-back and rollback"
```
### Task 4: Add Operation History and Verified Restore
**Files:**
- Create: `src/dx_productivity/domain/restore.py`
- Create: `src/dx_productivity/ui/history_page.py`
- Create: `src/dx_productivity/ui/history_controller.py`
- Create: `tests/domain/test_restore.py`
- Create: `tests/ui/test_history_page.py`
- Create: `tests/ui/test_history_controller.py`
- Modify: `src/dx_productivity/ui/app.py`
- Modify: `src/dx_productivity/ui/main_window.py`
**Interfaces:**
- Consumes: current `DesignSnapshot`, `RunStore.list_history`, `RunStore.build_restore_settings`, `build_apply_schedule`, `write_apply_request`, and `write_schedule`.
- Produces: `build_restore_plan(snapshot, request) -> AnnotationPlan`, `HistoryPage`, and `HistoryController.restore_latest() -> Path`.
- [ ] **Step 1: Write failing restore-plan tests**
```python
def test_restore_plan_requires_current_values_to_match(snapshot, restore_request):
plan = build_restore_plan(snapshot, restore_request)
assert plan.can_apply
assert plan.rows[0].old_refdes == "R1"
assert plan.rows[0].new_refdes == "R?"
def test_restore_plan_blocks_stale_component(snapshot, restore_request):
stale = replace(snapshot, components=(replace(snapshot.components[0], refdes="R9"),))
plan = build_restore_plan(stale, restore_request)
assert not plan.can_apply
assert any(issue.code == "restore-stale" for issue in plan.issues)
```
- [ ] **Step 2: Run restore domain tests and confirm failure**
Run: `py -3.12 -m pytest tests/domain/test_restore.py -v`
Expected: FAIL because `build_restore_plan` does not exist.
- [ ] **Step 3: Implement identity-safe restore planning**
Match each restore item first by nonempty stable UID, then by exact hierarchical full path. Require one unambiguous component, require its current reference designator to equal `expected_refdes` case-insensitively, and reject collisions against every component outside the restore set. Convert validated items to `PlanRow` values and call `build_apply_schedule`, including placeholder cycle breaks. Return blocking issues `restore-missing`, `restore-ambiguous`, `restore-stale`, or `restore-collision` instead of guessing.
- [ ] **Step 4: Write failing history UI/controller tests**
```python
def test_history_page_shows_latest_entry_first(qtbot, entries):
page = HistoryPage()
qtbot.addWidget(page)
page.set_entries(entries)
assert page.row_run_id(0) == entries[0].run_id
assert page.restore_button.isEnabled()
def test_restore_creates_second_backup_before_result(controller, monkeypatch):
calls = []
monkeypatch.setattr(controller.run_store, "write_backup", lambda *args: calls.append("backup") or Path("backup.json"))
monkeypatch.setattr(protocol, "write_apply_request", lambda *args: calls.append("metadata"))
monkeypatch.setattr(protocol, "write_schedule", lambda *args: calls.append("result"))
controller.restore_latest()
assert calls == ["backup", "metadata", "result"]
```
- [ ] **Step 5: Run history UI tests and confirm failure**
Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest tests/ui/test_history_page.py tests/ui/test_history_controller.py -v`
Expected: FAIL because the history page and controller do not exist.
- [ ] **Step 6: Implement the history page and restore controller**
Replace navigation page index 6 with an unframed history table showing time, operation state, changed count, design, and backup path. Provide a `恢复上次位号` command with a confirmation dialog naming the affected count and backup timestamp. Disable it when no verified applicable entry exists.
`HistoryController` filters history by the active design, builds the restore plan against the current full snapshot, creates a fresh backup of the current values, writes apply metadata, and publishes `result.tsv` last. It polls the same `apply-status.json` contract as automatic annotation and refreshes history exactly once after success or verified rollback.
- [ ] **Step 7: Run focused and full UI regression tests**
Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest tests/domain/test_restore.py tests/ui/test_history_page.py tests/ui/test_history_controller.py -v`
Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest -q`
Expected: all tests pass.
- [ ] **Step 8: Commit operation history and restore**
```powershell
git add src/dx_productivity/domain/restore.py src/dx_productivity/ui/history_page.py src/dx_productivity/ui/history_controller.py src/dx_productivity/ui/app.py src/dx_productivity/ui/main_window.py tests/domain/test_restore.py tests/ui/test_history_page.py tests/ui/test_history_controller.py
git commit -m "feat: add verified annotation restore workflow"
```
### Task 5: Build the Portable PyInstaller Release and Offline ZIP
**Files:**
- Create: `packaging/DxDesignerTools.spec`
- Create: `packaging/build_release.ps1`
- Create: `tests/packaging/test_release_definition.py`
- Create: `tests/packaging/test_built_release.py`
- Modify: `pyproject.toml`
- Modify: `.gitignore`
**Interfaces:**
- Consumes: Python 3.12 x64, PyInstaller 6.x, application launcher, root VBS scripts, the DOCX guide, and application resources.
- Produces: `release/DxDesigner效率工具/`, `release/DxDesigner效率工具_Win11_x64.zip`, and `release/SHA256SUMS.txt`. The internal VBS helper is stored at `_runtime/vbs/BridgeCommon.vbs`; only the user-importable and directly dispatched scripts remain at the root.
- [ ] **Step 1: Write failing release-definition tests**
```python
def test_spec_is_onedir_with_runtime_subdirectory():
text = Path("packaging/DxDesignerTools.spec").read_text("utf-8")
assert "COLLECT(" in text
assert 'contents_directory="_runtime"' in text
assert "onefile" not in text.lower()
def test_build_script_copies_only_importable_root_scripts():
text = Path("packaging/build_release.ps1").read_text("utf-8")
assert "MenuAdd.vbs" in text
assert "RefDesBridge.vbs" in text
assert "CompatibilityProbe.vbs" in text
assert "BridgeCommon.vbs" in text
assert "_runtime\\vbs" in text
assert "Compress-Archive" in text
```
- [ ] **Step 2: Run release-definition tests and confirm failure**
Run: `py -3.12 -m pytest tests/packaging/test_release_definition.py -v`
Expected: FAIL because packaging files do not exist.
- [ ] **Step 3: Pin the build dependency and implement the spec**
Add `pyinstaller>=6.11,<7` to the `build` optional dependency group. `DxDesignerTools.spec` targets console-disabled Windows x64 `onedir`, uses `src/dx_productivity/bridge/launcher.py` as entry point, names the executable `DxDesignerTools.exe`, and sets `contents_directory="_runtime"`. Collect the PySide6 platform plug-in, image-format plug-ins, styles, and qtawesome font data explicitly.
- [ ] **Step 4: Implement a deterministic PowerShell release build**
`build_release.ps1` verifies 64-bit Python 3.12, removes only the repository-owned `build/pyinstaller`, `dist/DxDesignerTools`, and `release/DxDesigner效率工具` paths after resolving them under the worktree, runs PyInstaller, assembles the root VBS scripts and `docs` directory, checks every expected file, creates the ZIP, and writes SHA-256 hashes. It must not invoke pip, download a package, or modify the target computer.
- [ ] **Step 5: Install build dependencies on the build computer and build**
Run: `py -3.12 -m pip install -e ".[dev,build]"`
Run: `powershell -NoProfile -ExecutionPolicy Bypass -File packaging\build_release.ps1`
Expected: build succeeds and produces the directory, ZIP, and hash manifest.
- [ ] **Step 6: Test the built application without system Python on PATH**
Copy the release to a temporary path containing Chinese characters and spaces. Start the copied EXE with a sanitized `PATH` containing only Windows system directories:
```powershell
& "$releaseRoot\DxDesignerTools.exe" probe --output "$tempRoot\兼容性 结果.json" --route packaged --payload-json '{"portable":true}'
$env:QT_QPA_PLATFORM = "offscreen"
& "$releaseRoot\DxDesignerTools.exe" ui --request "$fixture" --smoke-test-ms 750
```
Expected: both processes exit `0`, the probe JSON is valid UTF-8, and the UI loads the request, icons, and Qt platform plug-in without consulting `py.exe`, `python.exe`, or the network.
- [ ] **Step 7: Run built-release structure and isolation tests**
Run: `py -3.12 -m pytest tests/packaging/test_built_release.py -v --release-root "release/DxDesigner效率工具"`
Expected: root scripts and EXE exist; `_runtime/python312.dll`, Qt plug-ins, and qtawesome fonts exist; no source `.py` is required at the portable root; no file contains `DXTOOLS_HOME`, `D:\NET_CHECK`, or a build-machine absolute path.
- [ ] **Step 8: Commit reproducible packaging definitions**
```powershell
git add packaging tests/packaging pyproject.toml .gitignore
git commit -m "build: add portable offline Windows release"
```
Do not commit `build/`, `dist/`, or generated `release/` binaries.
### Task 6: Update the DOCX Guide and Add Live 7.9.5 Acceptance Instructions
**Files:**
- Modify: `docs/user/DxDesigner_7.9.5_自动位号工具使用说明.docx`
- Create: `docs/testing/dxdesigner-795-live.md`
- Test: `tests/docs/test_user_guide.py`
**Interfaces:**
- Consumes: the final portable folder names, root scripts, menu captions, backup location, and compatibility limitations.
- Produces: a visually verified offline guide and a target-machine evidence checklist.
- [ ] **Step 1: Write failing document-content tests**
Extract DOCX paragraph/table text and assert it includes `解压整个目录`, `MenuAdd.vbs`, `无需安装 Python`, `%LOCALAPPDATA%\DxProductivity`, `兼容性检测`, `自动回滚`, and `重新导入`. Assert it does not instruct users to run an installer, install Python, set `DXTOOLS_HOME`, or use `D:\NET_CHECK`.
Run: `py -3.12 -m pytest tests/docs/test_user_guide.py -v`
Expected: FAIL because the current guide predates the portable offline workflow.
- [ ] **Step 2: Update the DOCX with the portable workflow**
Use the existing document theme and page structure. Replace installation sections with: extract the complete ZIP, keep the directory stable, import the root `MenuAdd.vbs`, restart DxDesigner, run `兼容性检测`, then use `自动位号`. Add upgrade-in-place, folder relocation/re-import, removal, missing-runtime recovery, backup location, rollback result meanings, and offline-use statements.
- [ ] **Step 3: Render and visually inspect every DOCX page**
Use the documents skill render workflow to generate page PNGs and a PDF. Inspect every page for missing Chinese glyphs, clipped tables, orphan headings, broken numbering, overlap, inconsistent margins, and stale installer/Python screenshots or text. Iterate until the rendered document is clean.
- [ ] **Step 4: Add the live 7.9.5 checklist**
The checklist records Windows build, DxDesigner build, extracted root, script-path source, menu route, yield method, probe JSON path, date, project fixture, and tester. It covers menu idempotency, Chinese/space path, selected/current/full scope, continuous/page numbering, four coordinate orders, multi-unit grouping, collision blocking, cancel, successful apply, stale-state rejection, injected-failure rollback, restore, and full-design duplicate verification.
- [ ] **Step 5: Run documentation tests**
Run: `py -3.12 -m pytest tests/docs/test_user_guide.py -v`
Expected: all tests pass and the visual inspection has no unresolved issue.
- [ ] **Step 6: Commit user and acceptance documentation**
```powershell
git add docs/user/DxDesigner_7.9.5_自动位号工具使用说明.docx docs/testing/dxdesigner-795-live.md tests/docs/test_user_guide.py
git commit -m "docs: document portable offline workflow"
```
### Task 7: Final Regression, Release Rebuild, and Handoff
**Files:**
- Modify only files required by demonstrated verification failures.
**Interfaces:**
- Consumes: all source, tests, VBS scripts, packaging definitions, documentation, and the target-machine checklist.
- Produces: a reproducible offline ZIP, checksum, automated verification record, and clearly separated pending live-7.9.5 evidence.
- [ ] **Step 1: Run the complete source verification suite**
```powershell
$env:QT_QPA_PLATFORM = "offscreen"
py -3.12 -m pytest -q
cscript //nologo tests\vbs\test_bridge_common.vbs
git diff --check
```
Expected: all tests and VBS assertions pass; `git diff --check` reports no error.
- [ ] **Step 2: Scan for forbidden dependencies and unsafe bridge patterns**
Run: `rg -n "DXTOOLS_HOME|D:\\NET_CHECK|ViewDraw\.Application|GetActiveObject|py -3\.12|python\.exe" integration packaging src docs/user docs/testing`
Expected: no release-time fixed path, system-Python command, direct Python COM attachment, or newer-release dependency. Any documentation mention of “no Python installation” is allowed.
- [ ] **Step 3: Rebuild from the committed packaging definition**
Run: `powershell -NoProfile -ExecutionPolicy Bypass -File packaging\build_release.ps1`
Run: `py -3.12 -m pytest tests/packaging/test_built_release.py -v --release-root "release/DxDesigner效率工具"`
Expected: rebuilt artifacts pass structure, packaged-probe, sanitized-PATH UI, Chinese-path, and checksum tests.
- [ ] **Step 4: Record current-machine limitations explicitly**
Confirm whether a live DxDesigner 7.9.5 installation is discoverable. If absent, leave `docs/testing/dxdesigner-795-live.md` unchecked and label the ZIP `offline build verified; live 7.9.5 acceptance pending`. Do not mark script self-location, real API property mapping, live write-back, or rollback as target-verified from mocked evidence.
- [ ] **Step 5: Review the complete diff and release contents**
Run: `git status --short`
Run: `Get-FileHash -Algorithm SHA256 "release\DxDesigner效率工具_Win11_x64.zip"`
Expected: only intentional source/document changes remain; the printed ZIP hash matches `release/SHA256SUMS.txt`; generated binaries remain ignored by git.
- [ ] **Step 6: Commit only fixes demonstrated by final verification**
When Step 1 through Step 5 exposes a failure, return to that owning task, add a focused regression test, implement the minimum correction, rerun the owning task and full suite, and use that task's explicit `git add` paths. Skip this step when final verification requires no correction.
- [ ] **Step 7: Hand off the offline archive and target checklist**
Provide the absolute ZIP path, SHA-256, uncompressed size, compressed size, root `MenuAdd.vbs` path after extraction, automated test count, and the exact unchecked live-acceptance items. The first target run starts with `兼容性检测`; its JSON evidence determines whether the named procedure and self-location candidates are genuinely supported by DxDesigner 7.9.5.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,344 @@
# 一叶知秋_重构版旧功能迁移实施计划
> **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:** 将原始“一叶知秋”中的旧 EFM/VBS 功能以可回滚、可验收的兼容模块接入当前自动位号工具宿主。
**Architecture:** 保留原始 EFM/VBS 的行为作为第一阶段兼容层,由当前启动资产生成器提供工具根目录和菜单动作;旧模块与 RefDes 使用独立资源、日志和状态边界。每个模块先达到兼容接入,再单独决定是否迁移到现代 Python/VBS 桥接。
**Tech Stack:** Python 3.12, PySide6, 7.9.5 内部 VBS, EFM, pytest, cscript, PyInstaller onedir。
**Spec:** `docs/superpowers/specs/2026-09-11-yiyezhqiu-migration-update-design.md`
## Global Constraints
- 用户可见产品名统一为“一叶知秋_重构版”,当前 Python 包名和内部协议标识暂不改名。
- 只支持 DxDesigner/Expedition Enterprise 7.9.5 的已验证接口,不引入新版 Xpedition API 或 DLL。
- 旧资源必须从工具自身目录解析,不使用 `D:\NET_CHECK`、持久化 `SKY_MT` 或其他固定安装路径。
- 旧 EFM/VBS 兼容接入不等同于现代化重构;未完成 7.9.5 副本工程验收的模块不得标记为 stable。
- 当前自动位号、预览、应用、历史和恢复行为保持不变。
- 任何旧模块失败都不得静默修改原理图,也不得修改 RefDes 运行目录中的快照、应用状态或历史记录。
- 所有新增 VBS 源文件保持 ASCII;中文菜单文本使用 `ChrW` 构造。
---
### Task 1: 固化旧资产清单与模块支持矩阵
**Files:**
- Create: `src/dx_productivity/legacy/__init__.py`
- Create: `src/dx_productivity/legacy/manifest.py`
- Create: `tests/legacy/test_manifest.py`
- Create: `integration/dxdesigner795/legacy/yiyezhqiu/` assets copied from `Z:\dxdesigner-795-refdes\MENTOR效率工具一叶知秋.zip`
- Modify: `packaging/DxDesignerTools.spec`
- Modify: `packaging/build_release.ps1`
- Modify: `tests/packaging/test_release_definition.py`
**Interfaces:**
- Produces `LegacyModule(module_id: str, display_name: str, host: str, action_kind: str, entrypoint: str, assets: tuple[str, ...], status: str)`.
- Produces `legacy_modules() -> tuple[LegacyModule, ...]` with IDs `bom`, `value`, `value1`, `part-number`, `property-visibility`, `network`, and `pcb-assembly-refdes`.
- Produces `validate_legacy_assets(root: Path) -> tuple[str, ...]`; it returns missing relative paths in deterministic order and never raises for an absent optional module.
- [ ] **Step 1: Write the failing test**
```python
def test_manifest_lists_only_original_yiyezhqiu_modules():
from dx_productivity.legacy.manifest import legacy_modules
modules = legacy_modules()
assert [item.module_id for item in modules] == [
"bom", "value", "value1", "part-number",
"property-visibility", "network", "pcb-assembly-refdes",
]
assert all(item.status == "compatibility" for item in modules)
```
- [ ] **Step 2: Run test to verify it fails**
Run: `pytest tests/legacy/test_manifest.py::test_manifest_lists_only_original_yiyezhqiu_modules -v`
Expected: FAIL with `ModuleNotFoundError: No module named 'dx_productivity.legacy'`.
- [ ] **Step 3: Write minimal implementation**
Define the frozen dataclass and return the seven entries. Use relative entrypoints such as `legacy/yiyezhqiu/NET_CHECK/PART_Ref_CHA.efm` and `legacy/yiyezhqiu/NET_CHECK/BOM_output/Bom.efm`; do not store an absolute path in the manifest.
Copy only the original functional assets required by the manifest. Keep the original documents outside the executable runtime unless a later user-guide task explicitly references them.
- [ ] **Step 4: Run test to verify it passes**
Run: `pytest tests/legacy/test_manifest.py -v`
Expected: PASS, including tests for deterministic ordering, missing asset reporting, and no absolute `D:\NET_CHECK` path.
- [ ] **Step 5: Add release assertions**
Extend `DxDesignerTools.spec` and `build_release.ps1` so the onedir release copies the legacy asset tree. Add a packaging test that requires the seven manifest entrypoints in the release directory and rejects any runtime path containing `D:\NET_CHECK`.
- [ ] **Step 6: Commit**
```bash
git add src/dx_productivity/legacy tests/legacy integration/dxdesigner795/legacy packaging/DxDesignerTools.spec packaging/build_release.ps1 tests/packaging/test_release_definition.py
git commit -m "feat: inventory legacy yiyezhqiu modules"
```
**Approval gate:** review the generated module matrix and confirm which of the seven modules may be marked `compatibility` for the first release.
### Task 2: Generate portable legacy menu actions
**Files:**
- Create: `src/dx_productivity/legacy/menu.py`
- Create: `tests/legacy/test_menu.py`
- Create: `integration/dxdesigner795/modules/legacy/LegacyMenu.vbs`
- Modify: `src/dx_productivity/bridge/startup_assets.py`
- Modify: `integration/dxdesigner795/MenuAdd.vbs`
- Modify: `tests/bridge/test_startup.py`
- Modify: `tests/integration/test_menu_script.py`
**Interfaces:**
- `render_legacy_menu(tool_root: Path, modules: tuple[LegacyModule, ...]) -> str` returns ASCII VBS that uses only `ChrW` for Chinese captions and builds each action from `tool_root`.
- `legacy_action_name(module_id: str) -> str` returns the string `DxLegacy_` plus the module ID with hyphens converted to underscores plus `.vbs`.
- `generate_startup_assets()` adds the legacy action scripts to `StartupAssets.action_scripts` without changing the four existing RefDes/compatibility/guide/diagnostic keys.
- [ ] **Step 1: Write the failing test**
```python
def test_render_legacy_menu_has_relative_runtime_actions(tmp_path):
from dx_productivity.legacy.manifest import legacy_modules
from dx_productivity.legacy.menu import render_legacy_menu
text = render_legacy_menu(tmp_path / "一叶知秋 重构版", legacy_modules())
assert text.isascii()
assert 'OnAction = "run DxLegacy_bom.vbs"' in text
assert 'OnAction = "run DxLegacy_network.vbs"' in text
assert "D:\\NET_CHECK" not in text
```
- [ ] **Step 2: Run test to verify it fails**
Run: `pytest tests/legacy/test_menu.py::test_render_legacy_menu_has_relative_runtime_actions -v`
Expected: FAIL because `dx_productivity.legacy.menu` does not exist.
- [ ] **Step 3: Write minimal implementation**
Render one top-level “一叶知秋_重构版” menu and a “旧版功能” submenu. Each generated action script receives `DxToolsHome` as an escaped ASCII/`ChrW` expression and calls a named legacy entry procedure. Do not place the resolved user path in the checked-in template.
- [ ] **Step 4: Run test to verify it passes**
Run: `pytest tests/legacy/test_menu.py tests/bridge/test_startup.py::test_generate_startup_assets_uses_vendor_run_actions_from_local_startup -v`
Expected: PASS; existing RefDes action names and menu routes remain unchanged.
- [ ] **Step 5: Add VBS contract assertions**
`LegacyMenu.vbs` must resolve the generated root, reject missing files with a message and diagnostic entry, and never write `SKY_MT`. Add `cscript //nologo tests/vbs/test_legacy_menu.vbs` covering duplicate top-level menu removal, all seven action captions, and missing-asset handling.
- [ ] **Step 6: Commit**
```bash
git add src/dx_productivity/legacy/menu.py tests/legacy/test_menu.py integration/dxdesigner795/modules/legacy/LegacyMenu.vbs src/dx_productivity/bridge/startup_assets.py integration/dxdesigner795/MenuAdd.vbs tests/bridge/test_startup.py tests/integration/test_menu_script.py tests/vbs/test_legacy_menu.vbs
git commit -m "feat: add portable legacy menu actions"
```
**Approval gate:** inspect the generated menu captions and approve the grouping before enabling any legacy action in the release package.
### Task 2A: Build the modern compatibility UI shell
**Files:**
- Create: `src/dx_productivity/ui/legacy_page.py`
- Create: `src/dx_productivity/ui/legacy_controller.py`
- Create: `tests/ui/test_legacy_page.py`
- Create: `tests/ui/test_legacy_controller.py`
- Modify: `src/dx_productivity/ui/app.py`
- Modify: `src/dx_productivity/ui/main_window.py`
- Modify: `src/dx_productivity/ui/theme.py`
**Interfaces:**
- `LegacyModulePage(module_ids: tuple[str, ...], title: str)` renders a consistent module-card grid with display name, host, compatibility status, resource status, and an action note.
- `LegacyController.modules() -> tuple[LegacyModule, ...]` returns the manifest entries and `resource_status(module_id: str, tool_root: Path) -> str` returns `ready`, `missing`, or `host-only`.
- `LegacyModulePage.launch_requested` emits the module ID; the initial compatibility action shows the DxDesigner menu route and never attempts to execute an EFM outside the 7.9.5 host.
- [ ] **Step 1: Write the failing Qt test**
```python
def test_legacy_page_groups_modules_and_shows_compatibility_state(qtbot):
from dx_productivity.ui.legacy_page import LegacyModulePage
page = LegacyModulePage(("value", "value1", "part-number"), "属性批改")
qtbot.addWidget(page)
assert page.card_titles() == ("Value 修改", "Value1 修改", "Part Number 修改")
assert page.status_for("value") == "兼容接入"
```
- [ ] **Step 2: Run test to verify it fails**
Run: `pytest tests/ui/test_legacy_page.py::test_legacy_page_groups_modules_and_shows_compatibility_state -v`
Expected: FAIL because the legacy UI page does not exist.
- [ ] **Step 3: Write minimal implementation**
Add a reusable page with fixed card geometry, clear host labels, an explicit compatibility badge, resource state, and a single “在 DxDesigner 中打开” action note. Wire navigation indices 1 through 5 to module groups while preserving the existing RefDes and history pages. Keep the old EFM form as the execution surface until a module has a modern adapter.
- [ ] **Step 4: Run tests to verify it passes**
Run: `pytest tests/ui/test_legacy_page.py tests/ui/test_legacy_controller.py tests/ui/test_main_window.py -v`
Expected: PASS for grouping, status text, missing resources, keyboard focus, light/dark themes, and navigation page titles.
- [ ] **Step 5: Commit**
```bash
git add src/dx_productivity/ui/legacy_page.py src/dx_productivity/ui/legacy_controller.py tests/ui/test_legacy_page.py tests/ui/test_legacy_controller.py src/dx_productivity/ui/app.py src/dx_productivity/ui/main_window.py src/dx_productivity/ui/theme.py
git commit -m "feat: add legacy compatibility UI shell"
```
**Approval gate:** review the five UI groups and confirm that legacy EFM execution remains explicitly host-only until modern adapters are validated.
### Task 3: Add the EFM/VBS compatibility dispatcher
**Files:**
- Create: `src/dx_productivity/legacy/dispatcher.py`
- Create: `tests/legacy/test_dispatcher.py`
- Create: `integration/dxdesigner795/modules/legacy/LegacyDispatch.vbs`
- Modify: `src/dx_productivity/bridge/startup_assets.py`
- Modify: `tests/integration/test_vbs_bridge.py`
**Interfaces:**
- `LegacyAction(module: LegacyModule, resolved_entrypoint: Path, available: bool, error: str | None)`.
- `resolve_legacy_action(tool_root: Path, module_id: str) -> LegacyAction` checks the manifest path and keeps the result inside `tool_root`.
- `render_legacy_action(module_id: str, tool_root: Path) -> str` returns an ASCII Run-action VBS wrapper.
- [ ] **Step 1: Write the failing test**
```python
def test_resolve_legacy_action_rejects_escape_and_missing_files(tmp_path):
from dx_productivity.legacy.dispatcher import resolve_legacy_action
missing = resolve_legacy_action(tmp_path, "bom")
assert missing.available is False
assert missing.error == "missing-entrypoint"
```
- [ ] **Step 2: Run test to verify it fails**
Run: `pytest tests/legacy/test_dispatcher.py::test_resolve_legacy_action_rejects_escape_and_missing_files -v`
Expected: FAIL because the dispatcher module and result type do not exist.
- [ ] **Step 3: Write minimal implementation**
Resolve the manifest entry with `Path.resolve()`, require `resolved.is_relative_to(tool_root.resolve())`, and return a structured unavailable result for missing or escaping entries. Generate wrappers that call `Form` with the resolved absolute entrypoint only after checking `FileSystemObject.FileExists`.
- [ ] **Step 4: Run test to verify it passes**
Run: `pytest tests/legacy/test_dispatcher.py -v`
Expected: PASS for valid paths, missing paths, path escapes, unsupported action kinds, and Chinese/space-containing tool roots.
- [ ] **Step 5: Add bridge isolation tests**
Assert that generated legacy actions do not import `RefDesApply.vbs`, do not write `apply-status.json`, and log `legacy.` plus the concrete module ID to the common diagnostics path. Add a VBS test that a missing EFM displays an error and exits before opening a form.
- [ ] **Step 6: Commit**
```bash
git add src/dx_productivity/legacy/dispatcher.py tests/legacy/test_dispatcher.py integration/dxdesigner795/modules/legacy/LegacyDispatch.vbs src/dx_productivity/bridge/startup_assets.py tests/integration/test_vbs_bridge.py
git commit -m "feat: isolate legacy form dispatch"
```
**Approval gate:** approve the compatibility-only behavior and confirm that legacy actions remain outside the RefDes apply/restore transaction.
### Task 4: Add module-specific compatibility checks and user support matrix
**Files:**
- Create: `tests/integration/test_legacy_modules.py`
- Create: `src/dx_productivity/legacy/acceptance.py`
- Create: `docs/testing/yiyezhqiu-legacy-acceptance.md`
- Create: `docs/user/一叶知秋_重构版_模块支持矩阵.md`
- Modify: `docs/user/DxDesigner_7.9.5_自动位号工具使用说明_v0.5.docx` through the existing document update script
- Modify: `tests/docs/test_user_guide.py`
**Interfaces:**
- `legacy_acceptance_cases() -> tuple[LegacyAcceptanceCase, ...]` returns one case per module with `module_id`, `host`, `expected_entrypoint`, `read_only`, and `requires_live_795`.
- The support matrix records `兼容接入`, `重构中`, or `已验证` and never infers live support from Python mocks.
- [ ] **Step 1: Write the failing test**
```python
def test_acceptance_matrix_has_one_case_per_manifest_module():
from dx_productivity.legacy.manifest import legacy_modules
from dx_productivity.legacy.acceptance import legacy_acceptance_cases
assert {case.module_id for case in legacy_acceptance_cases()} == {
item.module_id for item in legacy_modules()
}
assert all(case.requires_live_795 for case in legacy_acceptance_cases())
```
- [ ] **Step 2: Run test to verify it fails**
Run: `pytest tests/integration/test_legacy_modules.py::test_acceptance_matrix_has_one_case_per_manifest_module -v`
Expected: FAIL because the acceptance-case module does not exist.
- [ ] **Step 3: Write minimal implementation**
Add explicit acceptance cases. Mark BOM, Value, Value1, Part Number, property visibility, and network actions as DxDesigner host cases; mark PCB assembly reference movement as an Expedition PCB case. Keep all cases `兼容接入` until the live checklist is completed.
- [ ] **Step 4: Run test to verify it passes**
Run: `pytest tests/integration/test_legacy_modules.py tests/docs/test_user_guide.py -v`
Expected: PASS and the guide contains the product name, module matrix, backup warning, and “实机验收待完成” wording.
- [ ] **Step 5: Write the live acceptance checklist**
For each DxDesigner module record startup import, menu click, sample-project result, save behavior, error path, and repeat-start behavior. For PCB record the required host, menu section, active-document precondition, and no-DxDesigner fallback. Do not mark a case verified without a real 7.9.5 run.
- [ ] **Step 6: Commit**
```bash
git add src/dx_productivity/legacy/acceptance.py tests/integration/test_legacy_modules.py docs/testing/yiyezhqiu-legacy-acceptance.md docs/user/一叶知秋_重构版_模块支持矩阵.md docs/user/DxDesigner_7.9.5_自动位号工具使用说明_v0.5.docx tests/docs/test_user_guide.py
git commit -m "docs: add legacy module acceptance matrix"
```
**Approval gate:** approve each module's live acceptance result before its status changes from `兼容接入`.
### Task 5: Optional modernization of one validated module at a time
**Files:**
- Create per-module adapter under `src/dx_productivity/legacy/adapters/`
- Create per-module domain/UI tests under `tests/legacy/adapters/`
- Modify the corresponding VBS bridge and `src/dx_productivity/ui/main_window.py` only after the module compatibility case is accepted
**Interfaces:**
- Each adapter exposes `snapshot()`, `build_preview()`, `apply()`, and `rollback()` with module-specific dataclasses; it must not reuse RefDes-specific `AnnotationPlan` for non-RefDes data.
- A module is promoted to `重构中` only after a behavior comparison against its original EFM/VBS result on the same sample design.
- [ ] **Step 1: Write a behavior-capture test**
Capture one known input/output pair from the validated legacy module and assert the adapter produces the same visible result, including row counts and changed fields.
- [ ] **Step 2: Run the capture test before implementation**
Run the concrete adapter test for the selected module, for example `pytest tests/legacy/adapters/test_bom.py -v` when migrating BOM.
Expected: FAIL because the adapter has not been created.
- [ ] **Step 3: Implement the smallest adapter**
Reuse common diagnostics, path handling, and backup helpers. Keep the old EFM action available as a fallback until the adapter passes both automated and live acceptance.
- [ ] **Step 4: Run automated and live checks**
Run the module test, the complete existing test suite, and the matching section in `docs/testing/yiyezhqiu-legacy-acceptance.md`.
- [ ] **Step 5: Commit and request module approval**
```bash
git add src/dx_productivity/legacy/adapters tests/legacy/adapters src/dx_productivity/ui/main_window.py integration/dxdesigner795/modules
git commit -m "feat: modernize validated legacy module"
```
Do not start the next module until the current module is approved for `已验证` or explicitly returned to `兼容接入`.
@@ -0,0 +1,351 @@
# 一叶知秋_重构版在线更新实施计划
> **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:** 在便携式 Windows 发布包中加入可配置的版本检查、校验下载、旁路切换和失败回滚能力。
**Architecture:** 更新检查与主程序 UI 解耦,使用标准库 HTTP/文件读取和后台线程获取 manifest;更新器以当前同一个 EXE 的 `update` 子命令运行,等待主程序退出后在旁路目录完成替换。版本包永远先下载、校验和备份,再经过人工确认切换。
**Tech Stack:** Python 3.12, PySide6, `urllib.request`, `hashlib`, `json`, `tempfile`, `zipfile`, PyInstaller onedir, pytest, pytest-qt。
**Spec:** `docs/superpowers/specs/2026-09-11-yiyezhqiu-migration-update-design.md`
## Global Constraints
- 用户可见产品名为“一叶知秋_重构版”;Python 包名和现有 RefDes 协议标识保持不变。
- 版本比较使用 SemVer,不按文件名或文件修改时间判断新旧。
- 默认行为是自动检查、人工安装;不做静默安装和运行中覆盖自身 EXE。
- 下载包必须验证 SHA-256;生产 stable 清单必须验证 Ed25519 签名,签名失败不可绕过。
- 更新失败只能恢复版本目录,不修改 DxDesigner 原理图工程。
- 不保存账号密码、访问令牌或私有存储凭据。
- 兼容 HTTPS、`file://` 本地模拟源和 Windows 只读/共享目录;联网实测等待用户提供真实地址。
- 所有新增 UI、网络和更新操作必须有离线/失败状态和诊断日志。
---
### Task 1: 固化产品版本与 manifest 数据模型
**Files:**
- Create: `src/dx_productivity/update/__init__.py`
- Create: `src/dx_productivity/update/models.py`
- Create: `tests/update/test_models.py`
- Modify: `src/dx_productivity/__init__.py`
- Modify: `src/dx_productivity/ui/main_window.py`
**Interfaces:**
- `PRODUCT_ID = "yiyezhqiu-refactored"` and `DISPLAY_NAME = "一叶知秋_重构版"`.
- `SemVer.parse(value: str) -> SemVer` and `SemVer.is_newer_than(other: SemVer) -> bool`.
- `UpdateManifest.from_mapping(data: Mapping[str, object]) -> UpdateManifest` with fields `product`, `version`, `channel`, `min_supported_version`, `package_url`, `sha256`, `release_notes`, `published_at`, and optional `signature`.
- `UpdateManifest.is_compatible_with(current: SemVer) -> bool` rejects a current version below `min_supported_version` and mismatched `product`.
- [ ] **Step 1: Write the failing test**
```python
def test_manifest_parses_semver_and_rejects_wrong_product():
from dx_productivity.update.models import UpdateManifest
manifest = UpdateManifest.from_mapping({
"product": "yiyezhqiu-refactored",
"version": "1.1.0",
"channel": "stable",
"min_supported_version": "1.0.0",
"package_url": "file:///release.zip",
"sha256": "a" * 64,
"release_notes": "模块迁移",
"published_at": "2026-09-11",
})
assert manifest.version.is_newer_than(manifest.min_supported_version)
assert manifest.is_compatible_with("1.0.0")
```
- [ ] **Step 2: Run test to verify it fails**
Run: `pytest tests/update/test_models.py::test_manifest_parses_semver_and_rejects_wrong_product -v`
Expected: FAIL with `ModuleNotFoundError: No module named 'dx_productivity.update'`.
- [ ] **Step 3: Write minimal implementation**
Implement strict three-part SemVer parsing with optional prerelease identifiers, lowercase product/channel normalization, 64-hex SHA-256 validation, and explicit `ValueError` messages for missing or malformed fields. Keep `__version__` as the current package source of truth.
- [ ] **Step 4: Run test to verify it passes**
Run: `pytest tests/update/test_models.py -v`
Expected: PASS for stable/prerelease ordering, invalid versions, wrong product, invalid digest, and minimum-version rejection.
- [ ] **Step 5: Commit**
```bash
git add src/dx_productivity/update src/dx_productivity/__init__.py src/dx_productivity/ui/main_window.py tests/update/test_models.py
git commit -m "feat: add update manifest model"
```
**Approval gate:** approve the product ID and SemVer policy before any network code is added.
### Task 2: Implement manifest loading and update checks
**Files:**
- Create: `src/dx_productivity/update/service.py`
- Create: `tests/update/test_service.py`
- Modify: `src/dx_productivity/update/models.py`
**Interfaces:**
- `UpdateCheckResult(status: str, current: SemVer, manifest: UpdateManifest | None, message: str)`.
- `UpdateService.fetch_manifest(source: str, timeout: float = 10.0) -> UpdateManifest`.
- `UpdateService.check(source: str, current: SemVer, channel: str = "stable") -> UpdateCheckResult`.
- Test helper `write_manifest(path: Path, package_url: str, version: str = "1.1.0") -> None` writes a valid UTF-8 manifest fixture.
- [ ] **Step 1: Write the failing test**
```python
def test_check_returns_available_for_file_manifest(tmp_path):
manifest_path = tmp_path / "manifest.json"
write_manifest(manifest_path, "file:///release.zip")
from dx_productivity.update.service import UpdateService
result = UpdateService().check(manifest_path.as_uri(), "1.0.0")
assert result.status == "available"
assert result.manifest is not None
assert str(result.manifest.version) == "1.1.0"
```
- [ ] **Step 2: Run test to verify it fails**
Run: `pytest tests/update/test_service.py::test_check_returns_available_for_file_manifest -v`
Expected: FAIL because `UpdateService` is not defined.
- [ ] **Step 3: Write minimal implementation**
Use `urllib.request.urlopen` with a 10-second timeout for HTTPS and `Path.from_uri` handling for `file://` sources. Decode UTF-8 JSON, pass the mapping to `UpdateManifest.from_mapping`, filter by channel, and return `up-to-date`, `available`, `incompatible`, or `error` without raising network exceptions to the UI.
- [ ] **Step 4: Run test to verify it passes**
Run: `pytest tests/update/test_service.py -v`
Expected: PASS for offline errors, malformed JSON, wrong product, prerelease channel filtering, and equal/current versions.
- [ ] **Step 5: Commit**
```bash
git add src/dx_productivity/update/service.py src/dx_productivity/update/models.py tests/update/test_service.py
git commit -m "feat: check remote update manifests"
```
**Approval gate:** approve the manifest URL forms and error behavior before adding downloads.
### Task 3: Add package download, digest/signature verification, and staging
**Files:**
- Create: `src/dx_productivity/update/verification.py`
- Create: `src/dx_productivity/update/stager.py`
- Create: `tests/update/test_verification.py`
- Create: `tests/update/test_stager.py`
- Modify: `pyproject.toml` to add `cryptography>=42,<46`
- Modify: `packaging/DxDesignerTools.spec`
**Interfaces:**
- `sha256_file(path: Path) -> str`.
- `verify_ed25519(public_key: bytes, payload: bytes, signature: bytes) -> bool`.
- `UpdateStager.download_and_verify(manifest: UpdateManifest, destination: Path) -> Path` returns a verified ZIP path and raises `UpdateVerificationError` before any install action.
- Test helper `_make_manifest(package_url: str, sha256: str, signature: str | None = None) -> UpdateManifest` constructs a validated manifest for staging tests.
- [ ] **Step 1: Write the failing tests**
```python
def test_download_and_verify_rejects_digest_mismatch(tmp_path):
from dx_productivity.update.stager import UpdateStager, UpdateVerificationError
package_path = tmp_path / "release.zip"
package_path.write_bytes(b"PK\\x03\\x04test")
manifest = _make_manifest(package_path.as_uri(), "0" * 64)
with pytest.raises(UpdateVerificationError, match="sha256"):
UpdateStager().download_and_verify(manifest, tmp_path / "download")
```
- [ ] **Step 2: Run tests to verify they fail**
Run: `pytest tests/update/test_verification.py tests/update/test_stager.py -v`
Expected: FAIL because the verification and staging modules do not exist.
- [ ] **Step 3: Write minimal implementation**
Stream downloads to a `.part` file under the requested destination, compute SHA-256 while writing, atomically rename the verified ZIP, and reject non-ZIP content, path traversal entries, digest mismatch, invalid signatures, or destination paths outside `%LOCALAPPDATA%\\DxProductivity\\updates`.
Use `cryptography` Ed25519 verification when `manifest.signature` is present. Stable manifests without a valid signature are rejected; local development manifests may omit signatures only when the caller explicitly selects the `development` channel.
- [ ] **Step 4: Run tests to verify they pass**
Run: `pytest tests/update/test_verification.py tests/update/test_stager.py -v`
Expected: PASS for matching/mismatching digests, valid/invalid signatures, interrupted downloads, ZIP traversal, duplicate destination versions, and Chinese/space-containing paths.
- [ ] **Step 5: Commit**
```bash
git add src/dx_productivity/update/verification.py src/dx_productivity/update/stager.py tests/update/test_verification.py tests/update/test_stager.py pyproject.toml packaging/DxDesignerTools.spec
git commit -m "feat: verify and stage update packages"
```
**Approval gate:** inspect the signature/public-key handling and approve the stable-channel rejection rule.
### Task 4: Implement the post-exit updater and rollback transaction
**Files:**
- Create: `src/dx_productivity/update/installer.py`
- Create: `tests/update/test_installer.py`
- Modify: `src/dx_productivity/bridge/launcher.py`
- Modify: `tests/bridge/test_launcher.py`
- Modify: `packaging/build_release.ps1`
**Interfaces:**
- `InstallPlan(current_root: Path, staged_zip: Path, backup_root: Path, restart_command: tuple[str, ...])`.
- `UpdateInstaller.install(plan: InstallPlan) -> InstallResult` where `InstallResult.state` is `installed`, `rolled-back`, or `failed`.
- Launcher dispatches `DxDesignerTools.exe update --plan %LOCALAPPDATA%\\DxProductivity\\updates\\install-plan.json` without importing Qt.
- Test helper `make_plan(tmp_path: Path, restart_probe_exit_code: int) -> InstallPlan` creates old/new portable roots and a restart probe command that exits with the requested code.
- [ ] **Step 1: Write the failing test**
```python
def test_install_plan_restores_previous_root_when_restart_probe_fails(tmp_path):
from dx_productivity.update.installer import UpdateInstaller
plan = make_plan(tmp_path, restart_probe_exit_code=1)
result = UpdateInstaller().install(plan)
assert result.state == "rolled-back"
assert (plan.current_root / "DxDesignerTools.exe").read_bytes() == b"old"
```
- [ ] **Step 2: Run test to verify it fails**
Run: `pytest tests/update/test_installer.py::test_install_plan_restores_previous_root_when_restart_probe_fails -v`
Expected: FAIL because the installer transaction is not implemented.
- [ ] **Step 3: Write minimal implementation**
Write a JSON install plan, wait for the parent PID to exit, copy the current portable directory to a timestamped backup, extract the staged ZIP into a sibling directory, validate required files, atomically rename current to backup and staged to current, run a short `--smoke-test-ms 1000` restart probe, and restore backup on a nonzero exit or missing executable.
The updater must never delete the only known-good directory. Retain the most recent two backups and record every state transition under `%LOCALAPPDATA%\\DxProductivity\\updates\\install.log`.
- [ ] **Step 4: Run tests to verify they pass**
Run: `pytest tests/update/test_installer.py tests/bridge/test_launcher.py -v`
Expected: PASS for install, already-running parent, missing ZIP, failed smoke probe, rollback, repeated install, and UNC/Chinese paths.
- [ ] **Step 5: Commit**
```bash
git add src/dx_productivity/update/installer.py tests/update/test_installer.py src/dx_productivity/bridge/launcher.py tests/bridge/test_launcher.py packaging/build_release.ps1
git commit -m "feat: add rollbackable portable updater"
```
**Approval gate:** approve the backup retention count and smoke-probe rollback rule before wiring the UI.
### Task 5: Add Settings update UI and background coordination
**Files:**
- Create: `src/dx_productivity/ui/settings_page.py`
- Create: `src/dx_productivity/ui/settings_controller.py`
- Create: `tests/ui/test_settings_page.py`
- Create: `tests/ui/test_settings_controller.py`
- Modify: `src/dx_productivity/ui/app.py`
- Modify: `src/dx_productivity/ui/main_window.py`
- Modify: `src/dx_productivity/ui/theme.py`
**Interfaces:**
- `SettingsController.check_updates(source: str, channel: str) -> None` emits `check_started`, `check_finished(UpdateCheckResult)`, and `install_requested(UpdateManifest)`.
- `SettingsPage` exposes `source_input`, `channel_combo`, `auto_check_checkbox`, `check_button`, `install_button`, `version_label`, `status_label`, and `release_notes_view`.
- Settings persist only non-secret values under `%LOCALAPPDATA%\\DxProductivity\\settings.json`.
- Test helper `make_manifest(version: str) -> UpdateManifest` returns a stable-channel manifest with a valid digest and release notes.
- [ ] **Step 1: Write the failing Qt tests**
```python
def test_settings_page_requires_second_confirmation_before_install(qtbot):
from dx_productivity.ui.settings_page import SettingsPage
page = SettingsPage(current_version="1.0.0")
qtbot.addWidget(page)
page.show_update(make_manifest("1.1.0"))
assert page.install_button.isEnabled()
assert page.install_requested_emissions == 0
```
- [ ] **Step 2: Run tests to verify they fail**
Run: `pytest tests/ui/test_settings_page.py tests/ui/test_settings_controller.py -v`
Expected: FAIL because the settings page/controller do not exist.
- [ ] **Step 3: Write minimal implementation**
Add the Settings page at the existing navigation index 7. On check, show `检查中`, then `已是最新`, `发现新版本`, `离线`, or `检查失败`. On install, show release notes and a first confirmation; after download and verification require a second confirmation before launching the updater. Disable install on incompatible, unsigned stable, digest-failed, or missing-package results.
Use a worker `QThread` or `QRunnable` for network and staging work so the Qt event loop remains responsive. Auto-check once after the main window is shown only when the checkbox is enabled and the last check is older than 24 hours.
- [ ] **Step 4: Run tests to verify they pass**
Run: `pytest tests/ui/test_settings_page.py tests/ui/test_settings_controller.py tests/ui/test_main_window.py -v`
Expected: PASS for state transitions, double confirmation, disabled install, persistence, theme refresh, and no-network UI behavior.
- [ ] **Step 5: Commit**
```bash
git add src/dx_productivity/ui/settings_page.py src/dx_productivity/ui/settings_controller.py tests/ui/test_settings_page.py tests/ui/test_settings_controller.py src/dx_productivity/ui/app.py src/dx_productivity/ui/main_window.py src/dx_productivity/ui/theme.py
git commit -m "feat: add update controls to settings"
```
**Approval gate:** review the settings wording and confirm auto-check does not imply silent installation.
### Task 6: Package, document, and validate with a local update source
**Files:**
- Create: `tests/update/test_local_update_flow.py`
- Create: `docs/testing/yiyezhqiu-update-acceptance.md`
- Create: `docs/user/一叶知秋_重构版_更新说明.md`
- Modify: `packaging/DxDesignerTools.spec`
- Modify: `packaging/build_release.ps1`
- Modify: `tests/packaging/test_built_release.py`
- Modify: `tests/docs/test_user_guide.py`
**Interfaces:**
- `packaging/build_release.ps1` emits the current version, `SHA256SUMS.txt`, and a manifest template with `package_url` and `sha256` filled only when a release artifact exists.
- The acceptance document records local `file://` update success, digest failure, offline behavior, rollback, and stable signature rejection.
- Test helpers `make_local_release_pair(tmp_path: Path) -> tuple[Path, Path, Path]`, `run_update_check_and_install(root: Path, manifest: Path) -> InstallResult`, and `read_version(root: Path) -> str` create and exercise a complete local update fixture.
- [ ] **Step 1: Write the failing end-to-end test**
```python
def test_local_manifest_updates_older_portable_copy(tmp_path):
old_root, new_zip, manifest = make_local_release_pair(tmp_path)
result = run_update_check_and_install(old_root, manifest)
assert result.state == "installed"
assert read_version(old_root) == "1.1.0"
```
- [ ] **Step 2: Run test to verify it fails**
Run: `pytest tests/update/test_local_update_flow.py -v`
Expected: FAIL because the packaged updater and manifest generation are not wired together.
- [ ] **Step 3: Write minimal packaging and documentation implementation**
Add version metadata to the release root, generate the checksum file, document how to host the ZIP and manifest on HTTPS or a read-only share, and include explicit warnings that live DxDesigner 7.9.5 compatibility is independent from updater success.
- [ ] **Step 4: Run the full verification set**
Run: `pytest tests/update tests/bridge/test_launcher.py tests/packaging tests/docs/test_user_guide.py -v` and then `powershell -ExecutionPolicy Bypass -File packaging/build_release.ps1 -Clean`.
Expected: all tests PASS, the release ZIP contains updater code and manifest metadata, and a local file-source update installs then rolls back correctly.
- [ ] **Step 5: Commit and request release approval**
```bash
git add tests/update/test_local_update_flow.py docs/testing/yiyezhqiu-update-acceptance.md docs/user/一叶知秋_重构版_更新说明.md packaging/DxDesignerTools.spec packaging/build_release.ps1 tests/packaging/test_built_release.py tests/docs/test_user_guide.py
git commit -m "test: validate local portable update flow"
```
**Approval gate:** approve the local-source evidence before using the real storage address and publishing a stable manifest.