Files
dxdesigner-part-replacement/docs/superpowers/plans/2026-09-01-dxdesigner-795-part-replacement-implementation.md
T

51 KiB

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

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

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
[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
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

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
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

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
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

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
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

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
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

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
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

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('<script src="https://x">'))
    text = output.read_text(encoding="utf-8")
    assert "&lt;script" in text
    assert "https://x" not in text
    assert "<script" not in text.casefold()


def test_partial_batch_never_renders_as_success(tmp_path: Path) -> None:
    output = tmp_path / "report.html"
    write_summary_html(output, report_with_states(ProjectState.VERIFIED_SAVED,
                                                   ProjectState.BLOCKED))
    assert "PARTIAL" in output.read_text(encoding="utf-8")


def test_ai_review_artifact_cannot_change_verified_state(tmp_path: Path) -> None:
    report = report_with_states(ProjectState.BLOCKED)
    (tmp_path / "ai-review.json").write_text(
        '{"recommendation":"approve"}', encoding="utf-8")
    output = tmp_path / "report.html"
    write_summary_html(output, report)
    assert "BLOCKED" in output.read_text(encoding="utf-8")
  • Step 2: Run report tests and verify failure

Run: py -3.12 -m pytest tests/part_replace/test_reports.py -v

Expected: collection fails because reports.py does not exist.

  • Step 3: Implement deterministic CSV/JSON/static HTML reports

Use csv.DictWriter, protocol canonical JSON, and html.escape. The HTML is a self-contained document using inline CSS only, no scripts, forms, external URLs, or active content. Show job ID, generated time, input hashes, project states, project-by-mapping counts, hard issues, nonblocking attribute differences, external-check status, certification identity, backup path, and resume action. AI review files are displayed only as separately labeled advisory attachments; report and controller state are rebuilt exclusively from the signed-off job inputs, bridge evidence, and append-only event log.

  • Step 4: Run report tests

Run: py -3.12 -m pytest tests/part_replace/test_reports.py -v

Expected: reports are stable, escaped, readable from local disk, and label partial/blocked jobs accurately.

  • Step 5: Commit reports
git add src/dx_productivity/part_replace/reports.py tests/part_replace/test_reports.py
git commit -m "feat: report replacement impact and verification"

Task 8: Batch Controller and Reproducible CLI

Files:

  • Create: src/dx_productivity/part_replace/controller.py
  • Create: src/dx_productivity/part_replace/cli.py
  • Create: src/dx_productivity/__main__.py
  • Create: tests/part_replace/test_controller.py
  • Create: tests/part_replace/test_cli.py
  • Modify: pyproject.toml

Interfaces:

  • Consumes: inputs, protocol, verification, certification, run store, and reports.

  • Produces: BatchController.create_job(...), ingest_inventory(project_id: str, snapshot_path: Path), prepare_apply(project_id: str, rule_index: int) -> BridgeCommand, verify_apply(project_id: str, rule_index: int, snapshot_path: Path) -> VerificationResult, confirm_saved(project_id: str, persisted_snapshot_path: Path), reconcile(project_id: str, snapshot_path: Path), and CLI subcommands discover, create, ingest, next, prepare, verify, confirm-saved, report, and status.

  • Step 1: Write failing stale-state, certification, and resume tests

def test_prepare_apply_blocks_stale_or_uncertified_pair(controller, inventory) -> None:
    controller.ingest_inventory("p1", inventory)
    with pytest.raises(ControllerError, match="uncertified_mapping"):
        controller.prepare_apply("p1", 0)
    controller.certify_for_test(0, inventory)
    controller.replace_current_fingerprint("p1", "stale")
    with pytest.raises(ControllerError, match="stale_project"):
        controller.prepare_apply("p1", 0)


def test_resume_skips_verified_saved_and_reconciles_uncertain(controller) -> None:
    controller.force_state("p1", ProjectState.VERIFIED_SAVED)
    controller.force_state("p2", ProjectState.APPLYING)
    assert controller.next_project().project_id == "p2"
    assert controller.action_for("p2") == "reconcile"
  • Step 2: Run controller tests and confirm failure

Run: py -3.12 -m pytest tests/part_replace/test_controller.py tests/part_replace/test_cli.py -v

Expected: collection fails because controller and CLI modules are missing.

  • Step 3: Implement use-case orchestration

create_job copies accepted inputs, records hashes, and initializes every project at inventory_pending. ingest_inventory validates project identity and advances to inventory_complete. Once all enabled projects are inventoried, the controller writes the impact matrix and moves nonblocking projects to apply_pending.

prepare_apply requires a verified backup, current snapshot fingerprint equal to inventory, and matching certification; it writes one atomic command containing the exact expected logical keys. verify_apply loads the post-dialog snapshot, runs hard verification, and either records success for that rule or blocks the project with undo_required. After the last rule it enters awaiting_save_confirmation. confirm_saved re-verifies the persisted snapshot before verified_saved or awaiting_external_checks.

The CLI returns 0 on completed commands, 2 on invalid user input, 3 on a blocking verification issue, and 4 when a live/manual action is required. It prints machine-readable JSON with --json and concise text otherwise. Add [project.scripts] with dx-part-replace = "dx_productivity.part_replace.cli:main", and make python -m dx_productivity call the same main() function.

  • Step 4: Run controller, CLI, and full Python tests

Run: py -3.12 -m pytest tests/part_replace -v

Expected: all pure Python tests pass without DxDesigner installed.

  • Step 5: Commit controller and CLI
git add pyproject.toml src/dx_productivity/part_replace/controller.py src/dx_productivity/part_replace/cli.py src/dx_productivity/__main__.py tests/part_replace/test_controller.py tests/part_replace/test_cli.py
git commit -m "feat: orchestrate multi-project replacement jobs"

Task 9: Mocked DxDesigner End-to-End Workflow

Files:

  • Create: tests/integration/mock_dxdesigner.py
  • Create: tests/integration/test_part_replace_end_to_end.py

Interfaces:

  • Consumes: real CLI, mailbox protocol, controller, fixtures, and run store.

  • Produces: MockDxDesigner.inventory(), consume_command(), replace(rule, fault=None), undo(), save(), and an end-to-end harness using real job files.

  • Step 1: Write failing successful, wrong-target, and crash-resume tests

def test_two_project_job_completes_with_one_group_apply_per_hit(tmp_path, job_inputs) -> None:
    harness = MockBatchHarness(tmp_path, job_inputs)
    result = harness.run_successfully()
    assert result.project_states == {"p1": "verified_saved", "p2": "verified_saved"}
    assert result.apply_groups == [("p1", "OLD-1", 3), ("p2", "OLD-1", 1)]
    assert result.backups_verified


def test_wrong_target_requires_verified_undo(tmp_path, job_inputs) -> None:
    harness = MockBatchHarness(tmp_path, job_inputs)
    result = harness.run_with_fault("p1", "wrong_target")
    assert result.project_states["p1"] == "blocked"
    assert result.undo_verified
    assert not result.saved_projects


def test_resume_reconciles_crash_during_apply(tmp_path, job_inputs) -> None:
    run_dir = MockBatchHarness(tmp_path, job_inputs).crash_during_apply("p2")
    resumed = MockBatchHarness.resume(run_dir)
    assert resumed.next_action == ("p2", "reconcile")
  • Step 2: Run the end-to-end test and verify missing harness

Run: py -3.12 -m pytest tests/integration/test_part_replace_end_to_end.py -v

Expected: collection fails because mock_dxdesigner.py does not exist.

  • Step 3: Implement the mock against real protocol files

Do not call controller internals to fake bridge behavior. The mock reads the published command, asserts the expected current fingerprint and selected keys, writes a real post-operation snapshot and bridge status, and invokes the same CLI subcommands an operator workflow uses. Faults mutate only one declared field so every verification branch has an isolated test.

  • Step 4: Run integration and full Python suites with coverage

Run: py -3.12 -m pytest tests/part_replace tests/integration/test_part_replace_end_to_end.py --cov=dx_productivity.part_replace --cov-report=term-missing

Expected: all tests pass; inputs.py, protocol.py, verification.py, certification.py, run_store.py, and controller.py each have at least 90% line coverage, with no uncovered failure branch in mapping graphs, hard verification, state transitions, certification invalidation, or resume.

  • Step 5: Commit mocked end-to-end verification
git add tests/integration/mock_dxdesigner.py tests/integration/test_part_replace_end_to_end.py
git commit -m "test: exercise replacement jobs end to end"

Task 10: ASCII-Only VBS Helpers and 7.9.5 Compatibility Probe

Files:

  • Create: integration/dxdesigner795/BridgeCommon.vbs
  • Create: integration/dxdesigner795/PartReplaceProbe.vbs
  • Create: tests/vbs/test_bridge_common.vbs
  • Create: tests/integration/test_part_replace_probe.py

Interfaces:

  • Consumes: DXTOOLS_HOME, injected Scripting, Application, ActiveView, and a disposable 7.9.5 project.

  • Produces: DxReadUtf8, DxWriteUtf8Atomic, DxJsonEscape, DxInvariantNumber, DxResolveRunPath, and a versioned compatibility profile recording exact build, capability booleans, route names, errors, and manual fallbacks.

  • Step 1: Write failing cscript and static-source tests

def test_probe_source_is_ascii_and_does_not_enable_unsafe_replace() -> None:
    text = Path("integration/dxdesigner795/PartReplaceProbe.vbs").read_text(encoding="ascii")
    assert "ChangeComponentPreserveRefdes" not in text
    assert "SendKeys" not in text
    assert "GetObject" not in text
    assert 'Scripting.GetEnvVariable("DXTOOLS_HOME")' in text
    assert '"production_replace_route":"native_replace_part"' in text


def test_bridge_common_has_narrow_error_scopes() -> None:
    text = Path("integration/dxdesigner795/BridgeCommon.vbs").read_text(encoding="ascii")
    assert "ADODB.Stream" in text
    assert "On Error Resume Next" not in text or "Err.Number" in text
  • Step 2: Run tests and confirm missing files

Run: cscript //nologo tests\vbs\test_bridge_common.vbs

Run: py -3.12 -m pytest tests/integration/test_part_replace_probe.py -v

Expected: both commands fail because the helper and probe files do not exist.

  • Step 3: Implement pure helpers and a read-mostly route probe

The probe must never replace a component in the production design. It records version/build, active project identity, dirty state, full component enumeration, Part Number, RefDes, hierarchy, units, symbol identity, origin/position/rotation/ mirror, attributes, pins, nets, exact-set selection, native dialog command availability, completion observation, Undo/save/open/close route availability, Packager/ERC/netlist route availability, and every API error number/description.

Probing a route that would mutate design state requires a disposable-project marker in the request and an explicit operator confirmation. The generated profile always fixes production_replace_route to native_replace_part; a successful ccomp experiment is recorded only as research evidence and never as an enabled Apply route.

  • Step 4: Run cscript and static probe tests

Run: cscript //nologo tests\vbs\test_bridge_common.vbs

Run: py -3.12 -m pytest tests/integration/test_part_replace_probe.py -v

Expected: helpers pass under Windows Script Host and probe source passes all safety assertions. Live-only checks remain unchecked in the acceptance record.

  • Step 5: Commit helpers and probe
git add integration/dxdesigner795/BridgeCommon.vbs integration/dxdesigner795/PartReplaceProbe.vbs tests/vbs/test_bridge_common.vbs tests/integration/test_part_replace_probe.py
git commit -m "feat: probe DxDesigner 7.9.5 replacement routes"

Task 11: Live Part Replacement Bridge

Files:

  • Create: integration/dxdesigner795/PartReplaceBridge.vbs
  • Create: tests/integration/test_part_replace_bridge.py

Interfaces:

  • Consumes: verified compatibility profile, bridge command, active project, and BridgeCommon.vbs helpers.

  • Produces: versioned inventory/post-operation snapshots, exact object selection, native Replace Part launch or manual-menu prompt, verified Undo/save calls, and bridge status JSON.

  • Step 1: Write failing bridge contract and safety tests

def test_bridge_requires_expected_current_state_before_selection() -> None:
    text = bridge_text()
    assert text.index("DxVerifyProjectIdentity") < text.index("DxSelectLogicalKeys")
    assert text.index("DxVerifySnapshotFingerprint") < text.index("DxSelectLogicalKeys")


def test_bridge_has_no_prohibited_write_route() -> None:
    text = bridge_text()
    assert "ChangeComponentPreserveRefdes" not in text
    assert ".ChangeComponent " not in text
    assert "SendKeys" not in text
    assert "ViewDraw.Application" not in text


def test_bridge_falls_back_to_operator_native_menu() -> None:
    text = bridge_text()
    assert "native_replace_part" in text
    assert "manual_native_dialog" in text
    assert "continue_after_manual_dialog" in text
    assert "expected_count" in text
    assert "new_part_number" in text
  • Step 2: Run bridge tests and confirm missing file

Run: py -3.12 -m pytest tests/integration/test_part_replace_bridge.py -v

Expected: tests fail because PartReplaceBridge.vbs does not exist.

  • Step 3: Implement inventory, exact selection, dialog handoff, and status

Inventory enumerates logical components through the probe-selected adapter, groups every placed unit, and fails closed if identity or a protected field is missing. For Apply, retain an in-memory dictionary from logical_key to live objects, re-read Part Number and RefDes for every expected key, reject any extra selected object, and select exactly the expected group.

Display old/new Part Numbers and expected count. Use the probe-verified native dialog command only when its profile flag and exact route name match; otherwise publish manual_action_required, preserve the selection, and instruct the operator to open the native menu. The fallback script then exits. After the operator closes Replace Part, the Continue part replacement menu action sends continue_after_manual_dialog; the bridge verifies project/command identity and exports the fresh complete snapshot. If the verified native route opens a modal dialog and returns only when it closes, the bridge exports immediately on return. Neither route polls window captions or waits for a fixed duration.

For project navigation, use a probe-verified open/close route only when enabled by the compatibility profile. Otherwise publish manual_project_open_required with the canonical next path and exit. The next menu invocation must verify that the active project identity matches before inventory or Apply.

Undo and save commands require an explicit Python command whose project ID, expected fingerprint, and prior bridge status match. After save, export another snapshot. Every narrow On Error Resume Next block immediately captures Err.Number and Err.Description, restores normal handling, and publishes a blocking status.

  • Step 4: Run bridge static tests and mocked protocol regression

Run: py -3.12 -m pytest tests/integration/test_part_replace_bridge.py tests/integration/test_part_replace_end_to_end.py -v

Expected: all contract tests pass and the Python mock still consumes the same protocol.

  • Step 5: Commit the live bridge
git add integration/dxdesigner795/PartReplaceBridge.vbs tests/integration/test_part_replace_bridge.py
git commit -m "feat: bridge native DxDesigner part replacement"

Task 12: Launcher, Startup Menu, and User-Level Installation

Files:

  • Create: integration/dxdesigner795/MenuAdd.vbs
  • Create: integration/dxdesigner795/Start-PartReplacement.ps1
  • Create: integration/dxdesigner795/Install.ps1
  • Create: tests/integration/test_part_replace_install.py

Interfaces:

  • Consumes: installation root, Python 3.12 executable, compatibility profile, mapping path, project-list path, and optional discovery root.

  • Produces: user-level DXTOOLS_HOME, %LOCALAPPDATA%\DxProductivity\settings.json, one idempotent Dx Productivity menu with probe/inventory/apply actions, and a reproducible dx-part-replace launch command.

  • Step 1: Write failing dry-run, ASCII, and idempotency tests

def test_launcher_dry_run_quotes_unicode_paths(tmp_path, powershell) -> None:
    mapping = tmp_path / "规则 文件.csv"
    projects = tmp_path / "工程列表.txt"
    result = powershell("integration/dxdesigner795/Start-PartReplacement.ps1",
                        "-Mapping", mapping, "-Projects", projects, "-WhatIf")
    assert result.returncode == 0
    assert str(mapping.resolve()) in result.stdout
    assert str(projects.resolve()) in result.stdout


def test_menu_is_ascii_idempotent_and_uses_environment() -> None:
    text = Path("integration/dxdesigner795/MenuAdd.vbs").read_text(encoding="ascii")
    assert 'Scripting.GetEnvVariable("DXTOOLS_HOME")' in text
    assert 'CommandBars("Sheet Menu Bar")' in text
    assert "DX_PRODUCTIVITY_PART_REPLACE" in text
    assert "D:\\" not in text
  • Step 2: Run installer tests and confirm missing files

Run: py -3.12 -m pytest tests/integration/test_part_replace_install.py -v

Expected: tests fail because launcher, installer, and menu files are missing.

  • Step 3: Implement nonadmin installation and reproducible launch

Install.ps1 validates Python is exactly major/minor 3.12, validates the package import, stores the resolved executable and user-local run root in UTF-8 settings.json, and sets DXTOOLS_HOME at user scope. -WhatIf prints every resolved value and makes no user-level environment or configuration change.

Start-PartReplacement.ps1 accepts explicit paths for reproducibility. When a path is omitted in an interactive console, it may use standard Windows file or folder pickers; cancellation exits without creating a job. It invokes the installed console entry point with an argument array, not a shell-built command string.

MenuAdd.vbs removes only an existing control with the exact suite tag before adding one replacement. It exposes Part replacement probe, Inventory current project, and Continue part replacement; captions assembled with ChrW may be localized without changing ASCII source encoding.

  • Step 4: Run installer and menu tests

Run: py -3.12 -m pytest tests/integration/test_part_replace_install.py -v

Expected: tests pass for spaces, Chinese paths, dry-run safety, missing settings, and repeated startup import.

  • Step 5: Commit launcher and installation
git add integration/dxdesigner795/MenuAdd.vbs integration/dxdesigner795/Start-PartReplacement.ps1 integration/dxdesigner795/Install.ps1 tests/integration/test_part_replace_install.py
git commit -m "feat: install DxDesigner part replacement scripts"

Task 13: Operator Documentation and Live 7.9.5 Acceptance

Files:

  • Create: docs/user/part-replacement.md
  • Create: docs/testing/dxdesigner-795-part-replacement-live.md
  • Create: tests/integration/test_part_replace_docs.py
  • Modify: docs/superpowers/specs/2026-09-01-dxdesigner-795-part-replacement-design.md only if live evidence disproves a documented route assumption.

Interfaces:

  • Consumes: completed CLI, scripts, compatibility profile schema, test fixtures, and research sources cited by the spec.

  • Produces: exact installation/job/recovery instructions and an evidence-bearing target-version acceptance record.

  • Step 1: Write the documentation contract test

def test_operator_docs_cover_every_irreversible_boundary() -> None:
    guide = Path("docs/user/part-replacement.md").read_text(encoding="utf-8")
    for phrase in ["replacement.csv", "projects.txt", "Library Wins",
                   "Save and continue", "close without saving", "backup",
                   "verified_saved", "manual_native_dialog"]:
        assert phrase in guide


def test_live_checklist_has_no_implicit_passes() -> None:
    checklist = Path("docs/testing/dxdesigner-795-part-replacement-live.md").read_text(encoding="utf-8")
    assert "- [ ]" in checklist
    assert "DxDesigner build:" in checklist
    assert "Central library identity or fingerprint:" in checklist
  • Step 2: Run the documentation test and confirm missing files

Run: py -3.12 -m pytest tests/integration/test_part_replace_docs.py -v

Expected: tests fail because the guide and checklist do not exist. Add tests/integration/test_part_replace_docs.py with the two contract tests above.

  • Step 3: Write exact operator and recovery instructions

Document mapping/project formats, discovery review, inventory pass, impact matrix, disposable certification, backup prerequisites, the automatic and manual native-dialog routes, exact Library Wins selection, target/count display, verification issues, Undo, close-without-save, project save gate, external checks, resume, report interpretation, restore prerequisites, and uninstall.

Clearly label the scripts evaluation-only until the live checklist passes.

  • Step 4: Create and execute the live acceptance checklist

The checklist contains separate unchecked items for exact 7.9.5 build, active project identity, dirty-state rejection, full inventory, exact group selection, native dialog route or manual fallback, correct and wrong target, compatible single-unit replacement, compatible multi-unit replacement when site-relevant, origin mismatch, pin mismatch, changed net, unrelated-object protection, stale inventory, backup/restore, Undo, close without save, persisted-save verification, multi-project resume, Packager, ERC, and netlist comparison.

For every item record fixture, mapping, observed API route/value/error, evidence path, tester, and date. Do not check an item based on automated/mock results.

  • Step 5: Run the documentation and complete automated regression suites

Run: py -3.12 -m pytest -q

Run: cscript //nologo tests\vbs\test_bridge_common.vbs

Run: git diff --check

Expected: automated tests and VBS helpers pass with no whitespace errors. The live checklist remains visibly incomplete until run on the user's installation.

  • Step 6: Commit documentation and acceptance artifacts
git add docs/user/part-replacement.md docs/testing/dxdesigner-795-part-replacement-live.md tests/integration/test_part_replace_docs.py
git commit -m "docs: add part replacement operation and acceptance guide"

Task 14: Final Regression, Package Build, and Release Classification

Files:

  • No planned source modification. A demonstrated failure returns execution to the owning task, where its test and implementation are corrected and committed before Task 14 restarts.

Interfaces:

  • Consumes: all version-1 implementation, automated evidence, and live acceptance record.

  • Produces: an installable Python package, verified script bundle, and explicit evaluation or production-accepted release classification.

  • Step 1: Run all automated verification from a clean Python process

py -3.12 -m pip install -e ".[dev]"
py -3.12 -m pytest --cov=dx_productivity.part_replace --cov-report=term-missing
cscript //nologo tests\vbs\test_bridge_common.vbs
git diff --check

Expected: all tests pass; safety-critical pure Python modules meet the Task 9 coverage floor; VBS helper assertions pass; diff check is empty.

  • Step 2: Scan for prohibited routes and fixed paths

Run: rg -n "ViewDraw\.Application|GetObject|ChangeComponentPreserveRefdes|\.ChangeComponent |SendKeys|D:\\\\|On Error Resume Next" src integration -g "*.py" -g "*.vbs" -g "*.ps1"

Expected: no Python COM attachment, direct production component-change method, keyboard automation, or fixed legacy drive path. Any narrow VBS error suppression has an immediate error capture and is explicitly accepted by its static test.

  • Step 3: Build and smoke-test the package

Run: py -3.12 -m build

Run: py -3.12 -m pip install --force-reinstall dist\dx_productivity-0.1.0-py3-none-any.whl

Run: dx-part-replace --help

Expected: wheel builds and installs, the CLI lists every approved subcommand, and importing the package does not require DxDesigner or third-party runtime libraries.

  • Step 4: Classify the release from evidence

If any required live checklist item is unchecked, write release-status.json with {"classification":"evaluation","reason":"live_795_acceptance_incomplete"}. Only when every live item has checked evidence may it contain {"classification":"production-accepted"}. Add the status file to the run artifact directory, not the source tree.

  • Step 5: Confirm no uncommitted implementation remains

Run: git status --short

Expected: no uncommitted source, test, integration-script, or operator-document file. Evaluation run artifacts stay outside the source tree and do not appear.