# DxDesigner 7.9.5 Multi-Project Part Replacement 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 resumable semi-automatic script that applies one old-Part-Number to new-Part-Number mapping set across multiple DxDesigner 7.9.5 projects through native Replace Part, with inventory, certification, backup, verification, and reports. **Architecture:** A pure Python 3.12 package owns immutable job inputs, snapshots, compatibility rules, the project state machine, backups, orchestration, and reports. ASCII-only VBScript runs inside DxDesigner 7.9.5 to enumerate and select live objects, invoke only probe-verified application routes, and exchange versioned UTF-8 files with Python; native Replace Part with Library Wins remains the production write path and has an explicit operator-menu fallback. **Tech Stack:** Python 3.12 standard library, pytest 8.x, coverage 7.x, VBScript/cscript, Windows PowerShell 5.1 or PowerShell 7, UTF-8 JSON/TSV, static HTML, Git. **Spec:** `docs/superpowers/specs/2026-09-01-dxdesigner-795-part-replacement-design.md` ## Global Constraints - DxDesigner/Expedition Enterprise 7.9.5 is the only supported schematic integration baseline. - All DxDesigner API access stays in the internal VBScript host; Python must not instantiate or attach to `ViewDraw.Application`. - Native Replace Part with Library Wins is the only version-1 production replacement path. - `ChangeComponentPreserveRefdes` and direct exported-design edits are prohibited production paths. - `ccomp` may be probed but must not be enabled for production Apply in version 1. - No UI-coordinate automation, `SendKeys`, blind timing delays, or automatic schematic rewiring. - Every `.vbs` source file is ASCII-only; localized messages use `ChrW` or are rendered by Python. - Python source runs on Python `>=3.12,<3.13` with no runtime package dependency. - Multi-project jobs use full-project scope; current-sheet and selected-component scopes are single-project only. - Mapping identity is case-insensitive after trimming, while reports preserve original spelling. - Duplicate, equal, chained, and cyclic mappings are rejected before inventory. - An uncertified old/new pair cannot enter production Apply and has no override. - Every project must be saved and closed before its complete project-tree backup. - Apply is blocked by stale state, ambiguous component identity, unverifiable protected state, or missing pin/network data. - Save is blocked until target, count, protected placement, pin geometry, connectivity, and unrelated-object invariants pass. - AI output is advisory only and cannot change verification or save state. - Compatibility is not claimed until the live 7.9.5 probe and acceptance checklist pass. --- ## Planned File Structure ```text pyproject.toml src/dx_productivity/ __init__.py __main__.py part_replace/ __init__.py models.py Immutable mappings, projects, snapshots, issues, states inputs.py Mapping/project parsing and candidate discovery protocol.py Versioned JSON/TSV and atomic file exchange verification.py Impact matrix and before/after invariant checks certification.py Trial certification fingerprints and invalidation run_store.py Durable event log, state projection, tree hashes, backups reports.py CSV, JSON, and static HTML report generation controller.py Inventory/apply/save/resume use-case orchestration cli.py Reproducible command-line interface integration/dxdesigner795/ BridgeCommon.vbs ASCII-only UTF-8, escaping, path, mailbox helpers PartReplaceProbe.vbs Read-mostly 7.9.5 capability and route probe PartReplaceBridge.vbs Inventory, selection, result export, undo/save adapter MenuAdd.vbs Idempotent startup-imported suite menu Start-PartReplacement.ps1 CLI launcher and optional standard path pickers Install.ps1 User-level DXTOOLS_HOME and settings installation tests/ conftest.py fixtures/ snapshot-before.json snapshot-after-compatible.json snapshot-after-pin-change.json part_replace/ test_models.py test_inputs.py test_protocol.py test_verification.py test_certification.py test_run_store.py test_reports.py test_controller.py test_cli.py integration/ mock_dxdesigner.py test_part_replace_end_to_end.py test_part_replace_probe.py test_part_replace_bridge.py test_part_replace_install.py vbs/ test_bridge_common.vbs docs/user/part-replacement.md docs/testing/dxdesigner-795-part-replacement-live.md ``` ## Spec Coverage | Spec sections | Implementation tasks | | --- | --- | | Purpose, compatibility, evidence, scope | Tasks 1, 8, 10, 11, 12 | | Mapping and project identity | Task 2 | | Architecture and file protocol | Tasks 3, 5, 7, 8, 10, 11 | | Inventory and impact matrix | Tasks 4, 8, 9, 11 | | Compatibility certification | Tasks 4, 6, 9, 13 | | Apply workflow and protected verification | Tasks 4, 5, 8, 9, 11 | | Failure handling, restore, and resume | Tasks 5, 8, 9, 11 | | Operator and AI-review boundaries | Tasks 3, 7, 8, 12, 13 | | Compatibility probe | Task 10 | | Automated/live testing and release criteria | Tasks 9, 10, 11, 12, 13, 14 | ### Task 1: Python Package and Immutable Domain Model **Files:** - Create: `pyproject.toml` - Create: `src/dx_productivity/__init__.py` - Create: `src/dx_productivity/part_replace/__init__.py` - Create: `src/dx_productivity/part_replace/models.py` - Create: `tests/conftest.py` - Create: `tests/part_replace/test_models.py` **Interfaces:** - Consumes: no earlier task. - Produces: `Scope`, `ProjectState`, `MappingRule`, `ProjectRef`, `PinSnapshot`, `UnitSnapshot`, `ComponentSnapshot`, `DesignSnapshot`, `Issue`, `VerificationResult`, `ImpactCell`, and `ExternalChecks` immutable dataclasses. - [ ] **Step 1: Write failing immutable-model tests** ```python from dataclasses import FrozenInstanceError from decimal import Decimal import pytest from dx_productivity.part_replace.models import ( ComponentSnapshot, DesignSnapshot, MappingRule, PinSnapshot, ProjectState, Scope, UnitSnapshot, ) def test_snapshot_model_is_immutable_and_decimal_exact() -> None: pin = PinSnapshot(number="1", name="A", x=Decimal("10.25"), y=Decimal("20"), net="N$1") unit = UnitSnapshot(unit_id="u1", sheet="/MAIN", symbol="res.1", x=Decimal("0"), y=Decimal("0"), rotation=0, mirrored=False, pins=(pin,)) component = ComponentSnapshot(logical_key="/MAIN|R1", refdes="R1", part_number="OLD-1", units=(unit,), attributes=()) snapshot = DesignSnapshot(format_version=1, project_id="p1", project_path="C:/P/a.prj", fingerprint="abc", components=(component,)) with pytest.raises(FrozenInstanceError): snapshot.project_id = "p2" # type: ignore[misc] assert snapshot.components[0].units[0].pins[0].x == Decimal("10.25") def test_state_and_scope_values_are_protocol_stable() -> None: assert Scope.FULL_PROJECT.value == "full_project" assert ProjectState.AWAITING_SAVE_CONFIRMATION.value == "awaiting_save_confirmation" assert MappingRule("OLD", "NEW").old_part_number == "OLD" ``` - [ ] **Step 2: Run the test and confirm the missing-package failure** Run: `py -3.12 -m pytest tests/part_replace/test_models.py -v` Expected: collection fails with `ModuleNotFoundError: No module named 'dx_productivity'`. - [ ] **Step 3: Add package metadata and the focused model types** ```toml [build-system] requires = ["setuptools>=75"] build-backend = "setuptools.build_meta" [project] name = "dx-productivity" version = "0.1.0" requires-python = ">=3.12,<3.13" dependencies = [] [project.optional-dependencies] dev = ["pytest>=8,<9", "pytest-cov>=5,<7", "coverage>=7,<8", "build>=1.2,<2"] [tool.setuptools.packages.find] where = ["src"] [tool.pytest.ini_options] testpaths = ["tests"] addopts = "-ra" ``` Implement every record with `@dataclass(frozen=True, slots=True)`. Store attributes as sorted `tuple[tuple[str, str], ...]`, pins and units as tuples, coordinates as `Decimal`, rotation as integer degrees, and issue details as immutable tuples. `ExternalChecks` has `packager`, `erc`, and `netlist` fields of type `bool | None`. Define the exact state values from Section 11.1 of the spec. Put shared immutable snapshot factories in `tests/conftest.py`; they must return new values per test and must not read or write the live filesystem outside `tmp_path`. - [ ] **Step 4: Install editable development dependencies and run the focused test** Run: `py -3.12 -m pip install -e ".[dev]"` Run: `py -3.12 -m pytest tests/part_replace/test_models.py -v` Expected: all model tests pass. - [ ] **Step 5: Commit the package foundation** ```powershell git add pyproject.toml src/dx_productivity tests/part_replace/test_models.py git commit -m "feat: add part replacement domain model" ``` ### Task 2: Strict Mapping and Project Inputs **Files:** - Create: `src/dx_productivity/part_replace/inputs.py` - Create: `tests/part_replace/test_inputs.py` **Interfaces:** - Consumes: `MappingRule`, `ProjectRef`, and `Scope` from `models.py`. - Produces: `InputError(code: str, message: str)`, `load_mapping(path: Path) -> tuple[MappingRule, ...]`, `load_projects(path: Path, allowed_suffixes: tuple[str, ...]) -> tuple[ProjectRef, ...]`, and `discover_projects(root: Path, allowed_suffixes: tuple[str, ...]) -> tuple[Path, ...]`. - [ ] **Step 1: Write failing mapping validation tests** ```python def test_load_mapping_rejects_case_duplicate_chain_and_cycle(tmp_path: Path) -> None: duplicate = write(tmp_path / "duplicate.csv", "old_part_number,new_part_number\nA,B\na,C\n") with pytest.raises(InputError, match="duplicate_source"): load_mapping(duplicate) chain = write(tmp_path / "chain.csv", "old_part_number,new_part_number\nA,B\nB,C\n") with pytest.raises(InputError, match="mapping_chain"): load_mapping(chain) cycle = write(tmp_path / "cycle.csv", "old_part_number,new_part_number\nA,B\nB,A\n") with pytest.raises(InputError, match="mapping_cycle"): load_mapping(cycle) def test_load_mapping_accepts_utf8_bom_and_preserves_spelling(tmp_path: Path) -> None: path = tmp_path / "替换.csv" path.write_text("old_part_number,new_part_number\n old-01 , New-01 \n", encoding="utf-8-sig") assert load_mapping(path) == (MappingRule("old-01", "New-01"),) ``` - [ ] **Step 2: Run the focused test and confirm the missing-module failure** Run: `py -3.12 -m pytest tests/part_replace/test_inputs.py -v` Expected: collection fails because `inputs.py` does not exist. - [ ] **Step 3: Implement strict CSV and project-list parsing** Use `csv.DictReader`, require the header set to equal `{"old_part_number", "new_part_number"}`, normalize identity with `value.strip().casefold()`, reject equal rules before graph checks, detect chains when any normalized target is also a normalized source, and report a cycle-specific code when the directed graph closes. Preserve input order. For projects, ignore blank lines and `#` comments, require absolute existing files with an allowlisted case-insensitive suffix, resolve each path, reject duplicates case-insensitively on Windows, and derive `project_id` as the first 16 hex characters of SHA-256 over the normalized canonical path. Discovery recursively finds only allowlisted project-definition files, sorts by casefolded canonical path, and returns candidates without writing or accepting them. - [ ] **Step 4: Run all input tests** Run: `py -3.12 -m pytest tests/part_replace/test_inputs.py -v` Expected: tests pass for invalid graphs, exact headers, Unicode paths, duplicate projects, missing projects, deterministic discovery, and explicit review output. - [ ] **Step 5: Commit input validation** ```powershell git add src/dx_productivity/part_replace/inputs.py tests/part_replace/test_inputs.py git commit -m "feat: validate replacement job inputs" ``` ### Task 3: Versioned Snapshot and Mailbox Protocol **Files:** - Create: `src/dx_productivity/part_replace/protocol.py` - Create: `tests/part_replace/test_protocol.py` - Create: `tests/fixtures/snapshot-before.json` - Create: `tests/fixtures/snapshot-after-compatible.json` - Create: `tests/fixtures/snapshot-after-pin-change.json` **Interfaces:** - Consumes: snapshot and mapping models. - Produces: immutable `BridgeCommand` and `BridgeStatus` records; `load_snapshot(path: Path) -> DesignSnapshot`, `write_snapshot(path: Path, snapshot: DesignSnapshot) -> None`, `write_command(path: Path, command: BridgeCommand) -> None`, `load_status(path: Path) -> BridgeStatus`, `atomic_write_text(path: Path, text: str) -> None`, and `snapshot_fingerprint(snapshot: DesignSnapshot) -> str`. - [ ] **Step 1: Write failing round-trip, schema, Decimal, and atomicity tests** ```python def test_snapshot_round_trip_is_canonical(tmp_path: Path, before_snapshot: DesignSnapshot) -> None: output = tmp_path / "snapshot.json" write_snapshot(output, before_snapshot) loaded = load_snapshot(output) assert loaded == before_snapshot assert json.loads(output.read_text(encoding="utf-8"))["format_version"] == 1 assert snapshot_fingerprint(loaded) == snapshot_fingerprint(before_snapshot) assert not list(tmp_path.glob("*.tmp")) def test_unknown_schema_is_rejected(tmp_path: Path) -> None: path = tmp_path / "future.json" path.write_text('{"format_version":2}', encoding="utf-8") with pytest.raises(ProtocolError, match="unsupported_format_version"): load_snapshot(path) ``` - [ ] **Step 2: Run the protocol tests and verify missing symbols** Run: `py -3.12 -m pytest tests/part_replace/test_protocol.py -v` Expected: collection fails because `protocol.py` is missing. - [ ] **Step 3: Implement canonical protocol conversion** Serialize Decimal values as strings, booleans as JSON booleans, tuples as JSON arrays, attributes as sorted `{"name": ..., "value": ...}` objects, and object keys in deterministic order. Reject unknown format versions, missing required fields, duplicate logical keys, duplicate unit IDs within a component, and duplicate pin numbers within a unit. `BridgeCommand` has exact fields `format_version`, `command_id`, `action`, `job_id`, `project_id`, `scope`, `old_part_number`, `new_part_number`, `expected_logical_keys`, `expected_count`, and `expected_fingerprint`. Atomic publication writes UTF-8 with `\n` newlines to a same-directory unique temporary file, flushes and `os.fsync()`s it, then calls `os.replace()`. - [ ] **Step 4: Run the protocol and fixture tests** Run: `py -3.12 -m pytest tests/part_replace/test_protocol.py -v` Expected: all canonicalization, validation, and atomicity tests pass. - [ ] **Step 5: Commit the protocol** ```powershell git add src/dx_productivity/part_replace/protocol.py tests/part_replace/test_protocol.py tests/fixtures git commit -m "feat: add versioned part replacement protocol" ``` ### Task 4: Impact Matrix and Hard Verification Engine **Files:** - Create: `src/dx_productivity/part_replace/verification.py` - Create: `tests/part_replace/test_verification.py` **Interfaces:** - Consumes: `DesignSnapshot`, `MappingRule`, `ImpactCell`, and `VerificationResult`. - Produces: `build_impact_matrix(snapshots: Iterable[DesignSnapshot], rules: Sequence[MappingRule]) -> tuple[ImpactCell, ...]`, `eligible_logical_keys(snapshot: DesignSnapshot, rule: MappingRule) -> tuple[str, ...]`, and `verify_replacement(before: DesignSnapshot, after: DesignSnapshot, rule: MappingRule, expected_logical_keys: Sequence[str], coordinate_tolerance: Decimal = Decimal("0.000001")) -> VerificationResult`. - [ ] **Step 1: Write failing compatible and blocking-difference tests** ```python def test_compatible_replacement_preserves_every_hard_invariant(fixtures) -> None: result = verify_replacement(fixtures.before, fixtures.compatible, MappingRule("OLD-1", "NEW-1"), ("/MAIN|R1",)) assert result.passed assert result.issues == () @pytest.mark.parametrize("mutator,code", [ (change_refdes, "refdes_changed"), (move_origin, "placement_changed"), (remove_pin, "pin_set_changed"), (move_pin, "pin_position_changed"), (change_net, "connectivity_changed"), (change_unrelated_part, "unrelated_component_changed"), (select_wrong_target, "wrong_target_part_number"), ]) def test_verification_blocks_unsafe_change(fixtures, mutator, code) -> None: result = verify_replacement(fixtures.before, mutator(fixtures.compatible), MappingRule("OLD-1", "NEW-1"), ("/MAIN|R1",)) assert not result.passed assert code in {issue.code for issue in result.issues} ``` - [ ] **Step 2: Run the focused tests and confirm failure** Run: `py -3.12 -m pytest tests/part_replace/test_verification.py -v` Expected: collection fails because `verification.py` does not exist. - [ ] **Step 3: Implement deterministic matching and comparisons** Index components by `logical_key`. Compare the complete before/after component key set, then treat expected keys and unrelated keys separately. For expected keys require exact target Part Number after trim/casefold, exact RefDes, hierarchy, unit set, symbol placement, integer rotation, mirror state, gate/slot, pin-number set, and net identity. Compare coordinates with absolute Decimal difference no larger than the supplied serialization tolerance. Library-controlled symbol and non-protected attribute changes are returned as nonblocking differences. Any expected object missing, extra object added, duplicate identity, count mismatch, protected-field change, pin change, network change, or unrelated component change is blocking. - [ ] **Step 4: Run verification tests including multi-unit fixtures** Run: `py -3.12 -m pytest tests/part_replace/test_verification.py -v` Expected: all hard-invariant and impact-matrix tests pass. - [ ] **Step 5: Commit verification logic** ```powershell git add src/dx_productivity/part_replace/verification.py tests/part_replace/test_verification.py git commit -m "feat: verify part replacements without rewiring" ``` ### Task 5: Durable Run Store, Project States, and Full Backup **Files:** - Create: `src/dx_productivity/part_replace/run_store.py` - Create: `tests/part_replace/test_run_store.py` **Interfaces:** - Consumes: protocol atomic writes, `ProjectRef`, `ProjectState`, and snapshot fingerprints. - Produces: immutable `TreeManifest`; `RunStore.create(root: Path, rules: Sequence[MappingRule], projects: Sequence[ProjectRef]) -> RunStore`, `RunStore.append_event(project_id: str, event: str, payload: Mapping[str, object]) -> None`, `RunStore.transition(project_id: str, target: ProjectState) -> None`, `RunStore.project_state(project_id: str) -> ProjectState`, `fingerprint_tree(root: Path) -> TreeManifest`, `backup_project(project_root: Path, backup_root: Path) -> TreeManifest`, `verify_tree(root: Path, manifest: TreeManifest) -> bool`, and `restore_project(project_root: Path, backup_root: Path, recovery_root: Path, manifest: TreeManifest, closed_confirmed: bool) -> TreeManifest`. - [ ] **Step 1: Write failing transition and backup tests** ```python def test_invalid_state_transition_is_rejected(run_store: RunStore) -> None: with pytest.raises(StateError, match="invalid_transition"): run_store.transition("p1", ProjectState.VERIFIED_SAVED) def test_backup_is_complete_and_manifest_detects_change(tmp_path: Path) -> None: project = tmp_path / "工程" (project / "design").mkdir(parents=True) (project / "design" / "main.sch").write_bytes(b"schematic") backup = tmp_path / "backup" manifest = backup_project(project, backup) assert verify_tree(backup, manifest) (backup / "design" / "main.sch").write_bytes(b"changed") assert not verify_tree(backup, manifest) def test_restore_requires_closed_project_and_preserves_failed_tree(tmp_path: Path) -> None: project, backup, manifest = make_changed_project_and_backup(tmp_path) with pytest.raises(BackupError, match="project_must_be_closed"): restore_project(project, backup, tmp_path / "recovery", manifest, closed_confirmed=False) failed_manifest = restore_project(project, backup, tmp_path / "recovery", manifest, closed_confirmed=True) assert verify_tree(project, manifest) assert verify_tree(tmp_path / "recovery", failed_manifest) ``` - [ ] **Step 2: Run focused tests and verify failure** Run: `py -3.12 -m pytest tests/part_replace/test_run_store.py -v` Expected: collection fails because `run_store.py` is missing. - [ ] **Step 3: Implement append-only state and safe tree copying** Allow only the transitions defined by the spec, plus `blocked` from every non-final state and re-entry from `blocked` to `inventory_pending` after an explicit reconcile event. Write each event as one canonical JSON line containing monotonic sequence, UTC timestamp, project ID, prior state, target state, event, and payload. Rebuild state from the log on open and reject a malformed or noncontiguous sequence. Tree manifests contain normalized relative paths, byte sizes, and SHA-256 hashes for every regular file. Reject symlinks/reparse points and any relative path that escapes the project root. Require the backup destination not to exist and not to be inside the source tree. Copy to a sibling staging directory, verify it, then rename it to the final backup path. Restore requires `closed_confirmed=True`, a canonical target equal to the job record, and a verified backup. Copy the current failed tree into a new recovery directory and verify that manifest before replacing project contents from the backup. Verify the restored tree before reporting success; retain both backup and recovery trees. - [ ] **Step 4: Run state, corruption, path-safety, and backup tests** Run: `py -3.12 -m pytest tests/part_replace/test_run_store.py -v` Expected: all tests pass, including interruption replay and Unicode paths. - [ ] **Step 5: Commit durable run storage** ```powershell git add src/dx_productivity/part_replace/run_store.py tests/part_replace/test_run_store.py git commit -m "feat: persist replacement jobs and verified backups" ``` ### Task 6: Trial Compatibility Certification **Files:** - Create: `src/dx_productivity/part_replace/certification.py` - Create: `tests/part_replace/test_certification.py` **Interfaces:** - Consumes: before/after snapshots, `MappingRule`, `VerificationResult`, external-check results, and atomic JSON writes. - Produces: `interface_fingerprint(snapshot: DesignSnapshot, logical_keys: Sequence[str]) -> str`, `CertificationStore.record(rule: MappingRule, target_fingerprint: str, library_identity: str | None, checks: ExternalChecks) -> Certification`, and `CertificationStore.require(rule: MappingRule, target_fingerprint: str, library_identity: str | None) -> Certification`. - [ ] **Step 1: Write failing certification and invalidation tests** ```python def test_certification_requires_hard_checks_and_external_checks(store, fixtures) -> None: with pytest.raises(CertificationError, match="external_checks_incomplete"): store.record(MappingRule("OLD-1", "NEW-1"), fixtures.target_fingerprint, "lib-r42", ExternalChecks(packager=True, erc=None, netlist=True)) def test_changed_library_or_target_fingerprint_invalidates(store, certification) -> None: with pytest.raises(CertificationError, match="certification_mismatch"): store.require(certification.rule, "different-fingerprint", "lib-r42") with pytest.raises(CertificationError, match="certification_mismatch"): store.require(certification.rule, certification.target_fingerprint, "lib-r43") ``` - [ ] **Step 2: Run tests and confirm the missing-module failure** Run: `py -3.12 -m pytest tests/part_replace/test_certification.py -v` Expected: collection fails because `certification.py` does not exist. - [ ] **Step 3: Implement immutable certification records** Fingerprint only the observed interface: normalized unit/gate identities, symbol origin, pin number/name/coordinate tuples, and logical unit count. Require successful hard verification and explicit `True` for Packager, ERC, and netlist. Store created UTC time, 7.9.5 build, old/new values, target fingerprint, optional library identity, representative project fingerprint, and evidence paths. When library identity is absent, exact target fingerprint is mandatory on every production Apply. Never expose a force or ignore flag. - [ ] **Step 4: Run certification tests** Run: `py -3.12 -m pytest tests/part_replace/test_certification.py -v` Expected: valid records round-trip and all mismatches fail closed. - [ ] **Step 5: Commit certification support** ```powershell git add src/dx_productivity/part_replace/certification.py tests/part_replace/test_certification.py git commit -m "feat: certify safe part replacement pairs" ``` ### Task 7: Reports and Operator-Facing Difference Output **Files:** - Create: `src/dx_productivity/part_replace/reports.py` - Create: `tests/part_replace/test_reports.py` **Interfaces:** - Consumes: run-store events, impact cells, verification results, certifications, and project states. - Produces: immutable `BatchReport`; `write_impact_csv(path: Path, cells: Sequence[ImpactCell]) -> None`, `write_differences_json(path: Path, results: Sequence[VerificationResult]) -> None`, and `write_summary_html(path: Path, report: BatchReport) -> None`. - [ ] **Step 1: Write failing escaping and partial-batch tests** ```python def test_html_report_escapes_part_numbers_and_has_no_remote_content(tmp_path: Path) -> None: output = tmp_path / "report.html" write_summary_html(output, report_with_part_number('