51 KiB
DxDesigner 7.9.5 Automatic Reference Designator 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 polished automatic reference designator tool that is imported through the DxDesigner 7.9.5 startup-script mechanism, previews deterministic annotation changes in Python, and applies them through a validated VBS bridge with backup and rollback.
Architecture: DxDesigner 7.9.5 imports MenuAdd.vbs; an internal VBS bridge owns all application API access and exchanges a versioned UTF-8 request plus an ordered TSV apply schedule with a PySide6 application. Pure Python modules own identity grouping, ordering, numbering, validation, scheduling, backup metadata, and UI state so the core behavior is testable without a live DxDesigner installation.
Tech Stack: Python 3.12, PySide6 6.x, qtawesome 1.x, pytest 8.x, pytest-qt 4.x, VBScript/cscript, PowerShell 7 or Windows PowerShell 5.1, JSON, UTF-8 TSV, Git.
Spec: docs/superpowers/specs/2026-09-01-dxdesigner-795-refdes-design.md
Global Constraints
- DxDesigner/Expedition Enterprise 7.9.5 is the only schematic integration baseline for phase one.
- Installation must use
Settings -> Run at Startup -> Scriptswith one importedMenuAdd.vbs. - Do not require a newer Xpedition add-in framework, copied release DLLs, COM re-registration, or a project-format upgrade.
- All DxDesigner application access remains inside the internal VBS host; Python must not attach directly to
ViewDraw.Application. MenuAdd.vbsresolves paths through the user-levelDXTOOLS_HOMEenvironment variable and contains no fixed drive path.- Every
.vbssource file remains ASCII-only; Chinese captions and messages are assembled withChrWso the DxDesigner 7.9.5 script host never has to decode UTF-8 source text. - Python source must run under Python 3.12.
- The default behavior changes only blank or question-mark placeholder reference designators.
- Apply must be blocked on duplicate output, occupied output, missing prefix, stale snapshot, or invalid schedule.
- Every apply and restore operation creates a timestamped backup and verifies the complete result.
- Normal text contrast is at least 4.5:1; default content text is 13 pt; essential text is never below 10 pt.
- The UI must remain usable at 100%, 125%, and 150% Windows display scaling with no clipping or overlap.
- Live compatibility is not claimed until the read-only probe and acceptance checklist pass in DxDesigner 7.9.5.
Planned File Structure
pyproject.toml Python package, dependencies, entry points, pytest settings
src/dx_productivity/
__init__.py Package version
__main__.py `python -m dx_productivity` entry point
domain/
__init__.py Domain package boundary
models.py Immutable request, settings, plan, issue, and schedule types
identity.py Scope filtering, prefix resolution, logical-unit grouping
ordering.py Page/row/column coordinate ordering
numbering.py Continuous and page-based allocation
planner.py End-to-end plan construction
validation.py Source and proposed-plan validation
schedule.py Ordered direct, dependency, and cycle apply steps
bridge/
__init__.py Bridge package boundary
protocol.py Versioned JSON/TSV parsing and writing
run_store.py Run directories, atomic files, backups, history, restore inputs
ui/
__init__.py UI package boundary
app.py QApplication creation and command-line request loading
theme.py Light/dark/high-contrast tokens and icon helper
main_window.py Shared suite shell and navigation
refdes_page.py Approved automatic-reference-designator view
refdes_controller.py UI state to planner/result protocol orchestration
integration/dxdesigner795/
MenuAdd.vbs Startup-imported menu script
CompatibilityProbe.vbs Read-only in-host capability probe
ProbeAction.vbs Safe external-launch marker for route testing
BridgeCommon.vbs Pure escaping, parsing, schedule, and path helpers
RefDesBridge.vbs DxDesigner snapshot, launch, apply, verify, rollback
Install.ps1 User-level environment/config installer
Uninstall.ps1 User-level environment/config removal
tests/
conftest.py Shared factories, fixture paths, settings, and PowerShell fixture
fixtures/request-basic.json Representative 7.9.5 request
fixtures/request-multiunit.json Multi-unit and hierarchical request
domain/ Pure annotation tests
bridge/ JSON/TSV and run-store tests
ui/ pytest-qt tests
integration/ Static VBS, installer, and mocked workflow tests
vbs/test_bridge_common.vbs cscript assertions for pure VBS helpers
docs/user/refdes-tool.md Installation and operator guide
docs/testing/dxdesigner-795-live.md Target-version acceptance checklist
Task 1: Python Foundation and 7.9.5 Read-Only Compatibility Probe
Files:
- Create:
pyproject.toml - Create:
src/dx_productivity/__init__.py - Create:
src/dx_productivity/bridge/__init__.py - Create:
src/dx_productivity/bridge/probe_host.py - Create:
integration/dxdesigner795/CompatibilityProbe.vbs - Create:
integration/dxdesigner795/ProbeAction.vbs - Create:
tests/integration/test_compatibility_probe.py
Interfaces:
-
Consumes:
DXTOOLS_HOME, injected DxDesigner 7.9.5 globalsScripting,CommandBars,Application, andActiveView. -
Produces:
probe_host.write_probe_marker(output_path: Path, route: str, payload: dict[str, object]) -> None,probe_host.main(argv: Sequence[str] | None = None) -> int, and%LOCALAPPDATA%\DxProductivity\compatibility.jsonwithmenu_route, readable capabilities, yield method, and timestamp. -
Step 1: Write the failing foundation and probe tests
from pathlib import Path
from dx_productivity.bridge.probe_host import write_probe_marker
def test_probe_marker_is_versioned_json(tmp_path: Path) -> None:
output = tmp_path / "compatibility.json"
write_probe_marker(output, "named", {"selected_query": True})
assert output.read_text(encoding="utf-8") == (
'{"format_version":1,"route":"named","selected_query":true}\n'
)
def test_probe_cli_merges_capability_payload(tmp_path: Path) -> None:
output = tmp_path / "compatibility.json"
exit_code = main([
"--output", str(output), "--route", "named", "--payload-json",
'{"yield_method":"Scripting.DoEvents","retained_reference":true}',
])
assert exit_code == 0
assert json.loads(output.read_text(encoding="utf-8"))["yield_method"] == (
"Scripting.DoEvents"
)
def test_startup_probe_uses_only_795_menu_primitives() -> None:
text = Path("integration/dxdesigner795/CompatibilityProbe.vbs").read_text(
encoding="utf-8"
)
assert 'Scripting.GetEnvVariable("DXTOOLS_HOME")' in text
assert 'CommandBars("Sheet Menu Bar")' in text
assert text.isascii()
assert "D:\\NET_CHECK" not in text
- Step 2: Run the tests and verify the missing package failure
Run: py -3.12 -m pytest tests/integration/test_compatibility_probe.py -v
Expected: collection fails with ModuleNotFoundError: No module named 'dx_productivity'.
- Step 3: Create package metadata and the deterministic probe marker
[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 = ["PySide6>=6.7,<7", "qtawesome>=1.3,<2"]
[project.optional-dependencies]
dev = ["pytest>=8,<9", "pytest-qt>=4.4,<5", "coverage>=7,<8", "build>=1.2,<2"]
[project.scripts]
dx-productivity = "dx_productivity.ui.app:main"
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-ra"
def write_probe_marker(output_path: Path, route: str, payload: dict[str, object]) -> None:
data = {"format_version": 1, "route": route, **payload}
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(
json.dumps(data, ensure_ascii=False, separators=(",", ":")) + "\n",
encoding="utf-8",
)
def main(argv: Sequence[str] | None = None) -> int:
args = build_parser().parse_args(argv)
payload = json.loads(args.payload_json)
if not isinstance(payload, dict):
raise ValueError("probe payload must be a JSON object")
write_probe_marker(args.output, args.route, payload)
return 0
build_parser() requires --output, --route (named, run, or form), and --payload-json; the module ends with raise SystemExit(main()) so py -3.12 -m dx_productivity.bridge.probe_host is directly launchable from VBS.
- Step 4: Add the importable probe menu with two safe action routes
Dim DxToolsHome
DxToolsHome = Scripting.GetEnvVariable("DXTOOLS_HOME")
Set DxProbeMenu = CommandBars("Sheet Menu Bar").Controls.Add(cmdControlPopup)
DxProbeMenu.Caption = "Dx " & ChrW(&H517C) & ChrW(&H5BB9) & ChrW(&H6027) & _
ChrW(&H68C0) & ChrW(&H6D4B)
Set DxNamedButton = DxProbeMenu.Controls.Add
DxNamedButton.Caption = ChrW(&H68C0) & ChrW(&H6D4B) & ChrW(&H5185) & _
ChrW(&H90E8) & ChrW(&H56DE) & ChrW(&H8C03)
DxNamedButton.OnAction = "DxToolsProbeNamed"
Set DxRunButton = DxProbeMenu.Controls.Add
DxRunButton.Caption = ChrW(&H68C0) & ChrW(&H6D4B) & " Run " & _
ChrW(&H811A) & ChrW(&H672C)
DxRunButton.OnAction = "Run " & DxToolsHome & "\integration\dxdesigner795\ProbeAction.vbs"
Sub DxToolsProbeNamed()
Call DxToolsWriteProbe("named")
End Sub
DxToolsWriteProbe launches py -3.12 -m dx_productivity.bridge.probe_host through WScript.Shell and records only capability names, booleans, version strings, and the selected route. It must not serialize schematic content or change the active design. The probe also records the exact host method that can yield/pump messages while the Python process remains active. All VBS files are ASCII-only and assemble localized captions with ChrW.
- Step 5: Install the editable package and verify automated tests pass
Run: py -3.12 -m pip install -e ".[dev]"
Run: py -3.12 -m pytest tests/integration/test_compatibility_probe.py -v
Expected: both tests pass.
- Step 6: Run the probe through the documented 7.9.5 import path
Import integration/dxdesigner795/CompatibilityProbe.vbs through Settings -> Run at Startup -> Scripts, restart DxDesigner 7.9.5, and click the two probe actions in order. Record named when the first action writes compatibility.json; otherwise record run when the second action succeeds. If neither action succeeds, adapt a copy of the supplied 7.9.5 EFM in the 7.9.5 Form Editor to call ProbeAction.vbs, set the menu action to Form <launcher-path>, and record form.
Expected: exactly one route launches Python, the probe reports selected/full-design enumeration and readable component fields, retained component references remain valid, a working host yield/message-pump method is recorded, and the schematic remains unchanged. The live probe is incomplete until that yield method works while Python remains active.
- Step 7: Commit the foundation and probe
git add pyproject.toml src/dx_productivity integration/dxdesigner795 tests/integration/test_compatibility_probe.py
git commit -m "feat: add DxDesigner 7.9.5 compatibility probe"
Task 2: Immutable Domain Models and Versioned Bridge Protocol
Files:
- Create:
src/dx_productivity/domain/__init__.py - Create:
src/dx_productivity/domain/models.py - Create:
src/dx_productivity/bridge/protocol.py - Create:
tests/conftest.py - Create:
tests/fixtures/request-basic.json - Create:
tests/bridge/test_protocol.py
Interfaces:
-
Consumes: version-1
request.jsongenerated by VBS. -
Produces:
load_request(path: Path) -> DesignSnapshot,write_schedule(path: Path, schedule: tuple[ApplyStep, ...]) -> None, andload_apply_status(path: Path) -> ApplyStatus. -
Step 1: Write failing request and result protocol tests
def test_load_request_parses_decimal_coordinates(fixture_path: Path) -> None:
snapshot = load_request(fixture_path / "request-basic.json")
assert snapshot.format_version == 1
assert snapshot.components[0].bridge_id == "c0001"
assert snapshot.components[0].x == Decimal("125.400")
assert snapshot.components[0].selected is True
def test_write_schedule_is_contiguous_utf8_tsv(tmp_path: Path) -> None:
output = tmp_path / "result.tsv"
write_schedule(output, (ApplyStep(1, "c0001", "R?", "R1", "R1"),))
assert output.read_text(encoding="utf-8") == "1\tc0001\tR?\tR1\tR1\n"
- Step 2: Run the focused tests and confirm missing model failures
Run: py -3.12 -m pytest tests/bridge/test_protocol.py -v
Expected: fails because DesignSnapshot and ApplyStep are undefined.
- Step 3: Define exact immutable types and enums
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
from enum import Enum
from pathlib import Path
class Scope(str, Enum):
SELECTED = "selected"
CURRENT_SHEET = "current-sheet"
FULL_DESIGN = "full-design"
class ProcessingMode(str, Enum):
FILL_ONLY = "fill-only"
REANNOTATE = "reannotate"
class NumberingMode(str, Enum):
CONTINUOUS = "continuous"
PAGE = "page"
class SortOrder(str, Enum):
TOP_DOWN_LEFT_RIGHT = "top-down-left-right"
TOP_DOWN_RIGHT_LEFT = "top-down-right-left"
LEFT_RIGHT_TOP_DOWN = "left-right-top-down"
RIGHT_LEFT_TOP_DOWN = "right-left-top-down"
class Severity(str, Enum):
INFORMATIONAL = "informational"
WARNING = "warning"
BLOCKING = "blocking"
@dataclass(frozen=True, slots=True)
class ComponentRecord:
bridge_id: str
stable_uid: str | None
full_path: str
logical_group_key: str
sheet_name: str
sheet_number: int | None
x: Decimal
y: Decimal
y_axis_up: bool
refdes: str
symbol_refdes_default: str | None
selected: bool
current_sheet: bool
part_number: str
value: str
locked: bool
@dataclass(frozen=True, slots=True)
class ApplyStep:
sequence: int
bridge_id: str
expected_refdes: str
new_refdes: str
final_refdes: str
@dataclass(frozen=True, slots=True)
class PrefixResolution:
prefix: str | None
resolved: bool
issue_code: str | None
@dataclass(frozen=True, slots=True)
class LogicalComponent:
key: str
members: tuple[ComponentRecord, ...]
prefix: str | None
sheet_number: int | None
x: Decimal
normalized_y: Decimal
@dataclass(frozen=True, slots=True)
class Issue:
code: str
severity: Severity
message: str
bridge_ids: tuple[str, ...] = ()
@dataclass(frozen=True, slots=True)
class AnnotationSettings:
scope: Scope = Scope.SELECTED
processing_mode: ProcessingMode = ProcessingMode.FILL_ONLY
numbering_mode: NumberingMode = NumberingMode.CONTINUOUS
sort_order: SortOrder = SortOrder.TOP_DOWN_LEFT_RIGHT
start_number: int = 1
page_step: int = 100
page_start: int = 1
row_tolerance: Decimal = Decimal("5")
@dataclass(frozen=True, slots=True)
class PlanRow:
logical_key: str
bridge_ids: tuple[str, ...]
full_path: str
prefix: str | None
old_refdes: str
new_refdes: str | None
status: str
changed: bool
@dataclass(frozen=True, slots=True)
class AnnotationPlan:
snapshot_id: str
rows: tuple[PlanRow, ...]
issues: tuple[Issue, ...]
schedule: tuple[ApplyStep, ...]
@property
def can_apply(self) -> bool:
return bool(self.schedule) and not any(
issue.severity is Severity.BLOCKING for issue in self.issues
)
@dataclass(frozen=True, slots=True)
class DesignSnapshot:
format_version: int
run_id: str
snapshot_id: str
design_id: str
design_path: str
components: tuple[ComponentRecord, ...]
@dataclass(frozen=True, slots=True)
class ApplyStatus:
format_version: int
run_id: str
state: str
changed_count: int
backup_path: Path | None
failing_sequence: int | None = None
error: str | None = None
rollback_state: str | None = None
@dataclass(frozen=True, slots=True)
class RunPaths:
run_id: str
root: Path
request: Path
result: Path
locate: Path
apply_status: Path
@dataclass(frozen=True, slots=True)
class HistoryEntry:
timestamp: datetime
design_id: str
backup_path: Path
state: str
changed_count: int
@dataclass(frozen=True, slots=True)
class RestoreRequest:
design_id: str
source_backup: Path
expected: tuple[tuple[str, str, str], ...]
These types form the one canonical model source for all later tasks. tests/conftest.py defines the shared fixture_path, component_factory, group_factory, settings, snapshot_factory, plan_row_factory, and powershell fixtures used by later tasks.
- Step 4: Implement strict versioned parsing and atomic TSV writing
load_request rejects an unsupported format version, duplicate bridge IDs, invalid decimal strings, absent identity fields, and non-boolean state fields. write_schedule rejects tabs/newlines, noncontiguous sequence numbers, and more than two steps for one bridge ID before replacing the destination atomically.
- Step 5: Run protocol tests and the complete suite
Run: py -3.12 -m pytest tests/bridge/test_protocol.py -v
Run: py -3.12 -m pytest -q
Expected: all tests pass.
- Step 6: Commit the protocol contract
git add src/dx_productivity/domain src/dx_productivity/bridge/protocol.py tests/conftest.py tests/fixtures tests/bridge/test_protocol.py
git commit -m "feat: define refdes bridge protocol"
Task 3: Scope, Prefix Resolution, and Multi-Unit Identity Grouping
Files:
- Create:
src/dx_productivity/domain/identity.py - Create:
tests/fixtures/request-multiunit.json - Create:
tests/domain/test_identity.py
Interfaces:
-
Consumes:
tuple[ComponentRecord, ...],Scope, andProcessingMode. -
Produces:
select_scope(records, scope) -> tuple[ComponentRecord, ...],resolve_prefix(record) -> PrefixResolution, andgroup_logical_components(records) -> tuple[LogicalComponent, ...]. -
Step 1: Write failing placeholder, blank-prefix, scope, and multi-unit tests
@pytest.mark.parametrize(
("refdes", "symbol_default", "prefix", "resolved"),
[("R?", None, "R", True), ("tp??", None, "TP", True), ("", "C?", "C", True), ("", None, None, False)],
)
def test_resolve_prefix(refdes, symbol_default, prefix, resolved, component_factory):
result = resolve_prefix(component_factory(refdes=refdes, symbol_refdes_default=symbol_default))
assert (result.prefix, result.resolved) == (prefix, resolved)
def test_multiunit_symbols_form_one_logical_component(multiunit_records):
groups = group_logical_components(multiunit_records)
assert len(groups) == 1
assert {r.bridge_id for r in groups[0].members} == {"u1a", "u1b"}
- Step 2: Run tests and verify missing identity functions
Run: py -3.12 -m pytest tests/domain/test_identity.py -v
Expected: fails on imports from domain.identity.
- Step 3: Implement strict placeholder matching and scope selection
PLACEHOLDER_RE = re.compile(r"^([A-Za-z]+)\?+$")
def resolve_prefix(record: ComponentRecord) -> PrefixResolution:
for candidate in (record.refdes.strip(), (record.symbol_refdes_default or "").strip()):
match = PLACEHOLDER_RE.fullmatch(candidate)
if match:
return PrefixResolution(match.group(1).upper(), True, None)
return PrefixResolution(None, False, "missing-prefix")
select_scope returns selected records, current-sheet records, or all records without fallback. group_logical_components prefers stable_uid, then uses a nonempty logical_group_key; duplicate or empty fallback keys produce an ambiguous group issue rather than merging by reference designator.
- Step 4: Implement processing-mode eligibility
Fill-only eligibility accepts blank and placeholder values. Reannotation eligibility accepts unlocked logical components with a resolved prefix. Locked records remain in the plan as preserved rows and never enter the allocator.
- Step 5: Run identity tests and full suite
Run: py -3.12 -m pytest tests/domain/test_identity.py -v
Run: py -3.12 -m pytest -q
Expected: all tests pass.
- Step 6: Commit identity behavior
git add src/dx_productivity/domain/identity.py tests/domain/test_identity.py tests/fixtures/request-multiunit.json
git commit -m "feat: resolve refdes identity and prefixes"
Task 4: Coordinate Ordering and Number Allocation
Files:
- Create:
src/dx_productivity/domain/ordering.py - Create:
src/dx_productivity/domain/numbering.py - Create:
tests/domain/test_ordering.py - Create:
tests/domain/test_numbering.py
Interfaces:
-
Consumes:
tuple[LogicalComponent, ...],AnnotationSettings, and occupied formal reference designators. -
Produces:
order_components(components, settings) -> tuple[LogicalComponent, ...]andallocate_numbers(components, occupied, settings) -> dict[str, str]keyed by logical group key. -
Step 1: Write failing default Z-order tests
def test_default_order_is_sheet_top_to_bottom_then_left_to_right(group_factory):
groups = (
group_factory("b", sheet=1, x="30", y="100"),
group_factory("a", sheet=1, x="10", y="100"),
group_factory("c", sheet=1, x="5", y="80"),
group_factory("d", sheet=2, x="1", y="500"),
)
ordered = order_components(groups, settings(row_tolerance=Decimal("5")))
assert [g.key for g in ordered] == ["a", "b", "c", "d"]
- Step 2: Write failing continuous and page allocation tests
def test_continuous_allocation_skips_occupied(group_factory):
groups = (group_factory("a", prefix="R"), group_factory("b", prefix="R"))
result = allocate_numbers(groups, {"R1", "r3"}, settings(start_number=1))
assert result == {"a": "R2", "b": "R4"}
def test_page_mode_starts_sheet_three_at_301(group_factory):
groups = (group_factory("a", prefix="C", sheet=3),)
result = allocate_numbers(groups, set(), settings(numbering_mode=NumberingMode.PAGE))
assert result == {"a": "C301"}
- Step 3: Run focused tests and verify missing implementations
Run: py -3.12 -m pytest tests/domain/test_ordering.py tests/domain/test_numbering.py -v
Expected: fails on missing order_components and allocate_numbers.
- Step 4: Implement normalized row clustering and all four sort orders
Normalize API Y direction before sorting. Within each numeric sheet, create a new row when the distance from the current row anchor exceeds row_tolerance; sort each row by X. Use logical group key as the final tie-breaker. Reject page mode when any eligible component lacks a numeric sheet mapping.
- Step 5: Implement case-insensitive per-prefix allocators
Continuous mode starts at start_number for each prefix and advances until it finds a value absent from the uppercase occupied set. Page mode starts at sheet_number * page_step + page_start. Allocation order is the result from order_components and never depends on input collection order.
- Step 6: Run focused tests, randomized determinism test, and full suite
Run: py -3.12 -m pytest tests/domain/test_ordering.py tests/domain/test_numbering.py -v
Run: py -3.12 -m pytest -q
Expected: all tests pass, including a test that shuffles equal-coordinate input 50 times and receives identical output.
- Step 7: Commit ordering and allocation
git add src/dx_productivity/domain/ordering.py src/dx_productivity/domain/numbering.py tests/domain/test_ordering.py tests/domain/test_numbering.py
git commit -m "feat: add deterministic refdes allocation"
Task 5: Plan Validation and Ordered Apply Scheduling
Files:
- Create:
src/dx_productivity/domain/validation.py - Create:
src/dx_productivity/domain/schedule.py - Create:
src/dx_productivity/domain/planner.py - Create:
tests/domain/test_validation.py - Create:
tests/domain/test_schedule.py - Create:
tests/domain/test_planner.py
Interfaces:
-
Consumes:
DesignSnapshotandAnnotationSettings. -
Produces:
build_annotation_plan(snapshot, settings) -> AnnotationPlan,validate_plan(snapshot, rows) -> tuple[Issue, ...], andbuild_apply_schedule(rows) -> tuple[ApplyStep, ...]. -
Step 1: Write failing collision and missing-prefix plan tests
def test_plan_blocks_collision_with_component_outside_scope(snapshot_factory):
snapshot = snapshot_factory(target_ref="R?", outside_ref="R1")
plan = build_annotation_plan(snapshot, settings(start_number=1))
assert plan.rows[0].new_refdes == "R2"
assert not [issue for issue in plan.issues if issue.severity is Severity.BLOCKING]
def test_plan_blocks_unresolved_prefix(snapshot_factory):
plan = build_annotation_plan(snapshot_factory(target_ref=""), settings())
assert any(issue.code == "missing-prefix" for issue in plan.issues)
assert plan.can_apply is False
- Step 2: Write failing two-component cycle schedule test
def test_schedule_breaks_refdes_swap_with_prefix_placeholder(plan_row_factory):
rows = (
plan_row_factory("a", "R1", "R2"),
plan_row_factory("b", "R2", "R1"),
)
steps = build_apply_schedule(rows)
assert [(s.bridge_id, s.expected_refdes, s.new_refdes) for s in steps] == [
("a", "R1", "R?"),
("b", "R2", "R1"),
("a", "R?", "R2"),
]
assert [s.sequence for s in steps] == [1, 2, 3]
- Step 3: Run planner tests and confirm missing functions
Run: py -3.12 -m pytest tests/domain/test_validation.py tests/domain/test_schedule.py tests/domain/test_planner.py -v
Expected: fails on missing planner modules.
- Step 4: Implement source and proposed-plan validation
Validation emits stable issue codes for duplicate source formal reference designators, duplicate proposed output, occupied output, missing prefix, ambiguous logical identity, locked target, nonnumeric sheet in page mode, and multiple outputs for one logical component. AnnotationPlan.can_apply is false when any issue has Severity.BLOCKING.
- Step 5: Implement dependency scheduling with cycle breaking
Direct placeholder-to-formal changes are emitted first. For formal-to-formal changes, repeatedly emit rows whose target is not an unprocessed current value. When no row is available, choose the lexicographically smallest bridge ID, move it to <PREFIX>?, continue the now-acyclic chain, and finally move the temporary component to its final value. Emit final_refdes on every step and assert each bridge ID appears no more than twice.
- Step 6: Compose the end-to-end planner
build_annotation_plan selects scope, groups logical components, resolves prefixes, preserves locked/formal rows according to mode, orders eligible groups, computes the occupied set outside the target set, allocates new values, validates rows, and builds a schedule only when no blocking issue exists.
- Step 7: Run planner tests and complete suite
Run: py -3.12 -m pytest tests/domain -v
Run: py -3.12 -m pytest -q
Expected: all tests pass.
- Step 8: Commit the planner
git add src/dx_productivity/domain tests/domain
git commit -m "feat: validate and schedule refdes plans"
Task 6: Atomic Run Store, Backup History, and Restore Inputs
Files:
- Create:
src/dx_productivity/bridge/run_store.py - Create:
tests/bridge/test_run_store.py
Interfaces:
-
Consumes:
DesignSnapshot,AnnotationPlan,ApplyStatus, and%LOCALAPPDATA%. -
Produces:
RunStore.create_run() -> RunPaths,RunStore.write_backup(snapshot, plan) -> Path,RunStore.record_status(status) -> None,RunStore.list_history(design_id) -> tuple[HistoryEntry, ...], andRunStore.build_restore_settings(entry) -> RestoreRequest. -
Step 1: Write failing atomic-backup and history tests
def test_backup_contains_complete_old_and_new_mapping(tmp_path, snapshot, plan):
store = RunStore(tmp_path)
path = store.write_backup(snapshot, plan)
data = json.loads(path.read_text(encoding="utf-8"))
assert data["format_version"] == 1
assert data["design_id"] == snapshot.design_id
assert data["changes"][0] == {
"bridge_id": "c0001", "full_path": "ROOT\\R_A", "old_refdes": "R?", "new_refdes": "R1"
}
def test_history_ignores_incomplete_temporary_files(tmp_path):
store = RunStore(tmp_path)
(store.backup_root / "orphan.tmp").write_text("partial", encoding="utf-8")
assert store.list_history("design-a") == ()
- Step 2: Run tests and confirm missing run store
Run: py -3.12 -m pytest tests/bridge/test_run_store.py -v
Expected: fails on missing RunStore.
- Step 3: Implement run paths and atomic JSON replacement
Use tempfile.NamedTemporaryFile(delete=False, dir=destination.parent) followed by Path.replace so a crash cannot leave a valid-looking partial request, backup, status, or history file. Sanitize design IDs for filenames while retaining the original design ID inside JSON.
- Step 4: Implement history and restore preflight data
History entries include timestamp, design ID, source backup path, success/rollback state, and changed count. Restore uses stable UID/full path plus the currently expected new reference designator; it refuses to construct a result when identity or current value does not match the backup.
- Step 5: Run bridge tests and full suite
Run: py -3.12 -m pytest tests/bridge -v
Run: py -3.12 -m pytest -q
Expected: all tests pass.
- Step 6: Commit run persistence
git add src/dx_productivity/bridge/run_store.py tests/bridge/test_run_store.py
git commit -m "feat: add atomic refdes backup history"
Task 7: VBS Snapshot, Schedule Validation, Write-Back, and Rollback
Files:
- Create:
integration/dxdesigner795/BridgeCommon.vbs - Create:
integration/dxdesigner795/RefDesBridge.vbs - Create:
tests/vbs/test_bridge_common.vbs - Create:
tests/integration/test_vbs_bridge.py
Interfaces:
-
Consumes: injected 7.9.5 application objects,
DXTOOLS_HOME,compatibility.json, and version-1result.tsv. -
Produces: version-1
request.json,apply-status.json, a verified schematic mutation, and rollback on any failure. -
Step 1: Write failing cscript helper assertions
ExecuteGlobal CreateObject("Scripting.FileSystemObject").OpenTextFile( _
"integration\dxdesigner795\BridgeCommon.vbs", 1, False).ReadAll
Call AssertEqual("quote", DxJsonEscape("a" & Chr(34) & "b"), _
"a" & Chr(92) & Chr(34) & "b")
Call AssertEqual("newline", DxJsonEscape("a" & vbLf & "b"), "a\nb")
Call AssertEqual("valid schedule", DxValidateSchedule( _
"1" & vbTab & "c1" & vbTab & "R1" & vbTab & "R?" & vbTab & "R2" & vbCrLf & _
"2" & vbTab & "c2" & vbTab & "R2" & vbTab & "R1" & vbTab & "R1" & vbCrLf & _
"3" & vbTab & "c1" & vbTab & "R?" & vbTab & "R2" & vbTab & "R2"), True)
- Step 2: Run cscript and confirm missing helper failure
Run: cscript //nologo tests\vbs\test_bridge_common.vbs
Expected: fails because BridgeCommon.vbs does not exist.
- Step 3: Implement locale-safe UTF-8 and schedule helpers
BridgeCommon.vbs supplies DxJsonEscape, invariant coordinate formatting, ADODB.Stream UTF-8 read/write, TSV row parsing, contiguous sequence validation, allowed one/two-step bridge-ID validation, expected-current chaining, environment path resolution, and atomic replace through a same-directory temporary file.
- Step 4: Implement snapshot export with an in-memory object map
RefDesBridge.vbs obtains the top-level design through Application.GetProjectData, enumerates full-design components through the probe-confirmed API, assigns c000001 bridge IDs, retains component objects in a Scripting.Dictionary, marks selected and current-sheet membership, and writes only the fields defined by ComponentRecord.
When a probed property is unavailable, the compatibility adapter writes its specified fallback: empty stable UID, full path identity, empty symbol default, or false lock state. Missing both stable UID and unambiguous full path aborts export.
- Step 5: Implement nonblocking Python launch, mailbox processing, stale-state preflight, and ordered apply
Launch the configured Python executable with quoted arguments through WScript.Shell.Exec. Retain the bridge_id -> component object dictionary and run a throttled mailbox loop using the exact yield/message-pump method proven by the compatibility probe. While Python remains active, consume each atomically published locate.tsv and result.tsv exactly once: locate selects and zooms the mapped component; result triggers stale-state preflight and the ordered apply. Before each apply step, confirm the mapped object still exists and comp.Refdes equals expected_refdes, then assign new_refdes. Write apply-status.json before Python exits so the live UI can display the outcome. If Python exits without publishing a result, leave the design unchanged.
- Step 6: Implement verification and rollback
After the final step, verify every mapped component equals final_refdes, re-enumerate the full design, and check case-insensitive uniqueness of formal reference designators. On any error, restore the original in-memory mapping, verify restoration, and write apply-status.json with state, failing sequence, error number/description, rollback result, and backup path.
- Step 7: Run cscript and static bridge tests
Run: cscript //nologo tests\vbs\test_bridge_common.vbs
Run: py -3.12 -m pytest tests/integration/test_vbs_bridge.py -v
Expected: helper assertions pass; static tests confirm every VBS source is ASCII-only and RefDesBridge.vbs contains no direct Python COM attachment, fixed drive path, On Error Resume Next around the full operation, or writes before backup creation.
- Step 8: Commit the VBS bridge
git add integration/dxdesigner795/BridgeCommon.vbs integration/dxdesigner795/RefDesBridge.vbs tests/vbs tests/integration/test_vbs_bridge.py
git commit -m "feat: add safe DxDesigner 7.9.5 VBS bridge"
Task 8: Apple-Inspired PySide6 Shell and Design Tokens
Files:
- Create:
src/dx_productivity/ui/__init__.py - Create:
src/dx_productivity/__main__.py - Create:
src/dx_productivity/ui/theme.py - Create:
src/dx_productivity/ui/main_window.py - Create:
src/dx_productivity/ui/app.py - Create:
tests/ui/test_main_window.py
Interfaces:
- Consumes: command-line
--request <request.json>, system palette, andRunStore. - Produces:
create_application(argv) -> QApplication,MainWindow,apply_theme(app, Theme) -> None, and a navigation signal for module pages.
theme.py defines class Theme(str, Enum) with exact values LIGHT = "light", DARK = "dark", and HIGH_CONTRAST = "high-contrast"; all token maps are keyed by this enum.
- Step 1: Write failing shell layout and accessibility tests
def test_main_window_has_approved_minimum_and_navigation(qtbot):
window = MainWindow()
qtbot.addWidget(window)
assert window.minimumWidth() == 1100
assert window.minimumHeight() == 700
assert window.navigation.item_texts()[:3] == ["自动位号", "属性批改", "属性显示"]
def test_icon_buttons_have_accessible_names(qtbot):
window = MainWindow()
qtbot.addWidget(window)
for button in window.findChildren(QToolButton):
assert button.accessibleName()
assert button.toolTip()
- Step 2: Run UI tests in offscreen mode and confirm missing UI classes
Run: $env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest tests/ui/test_main_window.py -v
Expected: fails on missing MainWindow.
- Step 3: Implement centralized light, dark, and high-contrast tokens
Define semantic tokens for canvas, window, sidebar, surface, borders, primary/secondary text, accent, success, warning, danger, and focus. Use 13 pt default text, 10 pt minimum secondary text, 30 logical-pixel action buttons, 16 logical-pixel icons, 6-pixel control radii, and no decorative animation.
Use qtawesome icons with one consistent Font Awesome weight. Map familiar semantics such as refresh, preview, apply, search, filter, locate, history, settings, success, warning, and lock. Do not place visible text inside an icon-only tool button.
- Step 4: Implement the shared window shell
Build the 52-pixel title bar, 218-pixel navigation rail, resizable content area, project context, bridge state, theme toggle, refresh, preview, and Apply actions. Keep Apply at the top-right. The shell exposes page/action signals and does not import annotation algorithms.
- Step 5: Run keyboard focus and theme tests
Test Tab traversal, accessible names, light/dark token application, 1100x700 minimum layout, and absence of clipped child geometry at 100%, 125%, and 150% logical test scales.
Run: $env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest tests/ui/test_main_window.py -v
Expected: all tests pass.
- Step 6: Commit the UI shell
git add src/dx_productivity/__main__.py src/dx_productivity/ui tests/ui/test_main_window.py
git commit -m "feat: add polished productivity suite shell"
Task 9: Automatic Reference Designator Page and Controller
Files:
- Create:
src/dx_productivity/ui/refdes_page.py - Create:
src/dx_productivity/ui/refdes_controller.py - Create:
tests/ui/test_refdes_page.py - Create:
tests/ui/test_refdes_controller.py
Interfaces:
-
Consumes:
DesignSnapshot,AnnotationSettings,build_annotation_plan,RunStore, andwrite_schedule. -
Produces:
RefDesPage.settings_changed,RefDesPage.apply_requested,RefDesController.refresh_plan(),RefDesController.apply() -> Path, and preview selection/location signals. -
Step 1: Write failing default-control and Apply-state tests
def test_refdes_defaults_match_approved_design(qtbot):
page = RefDesPage()
qtbot.addWidget(page)
assert page.scope() is Scope.SELECTED
assert page.processing_mode() is ProcessingMode.FILL_ONLY
assert page.numbering_mode() is NumberingMode.CONTINUOUS
assert page.sort_order() is SortOrder.TOP_DOWN_LEFT_RIGHT
assert page.start_number() == 1
assert page.row_tolerance() == Decimal("5")
def test_blocking_issue_disables_apply(qtbot, controller, unresolved_snapshot):
controller.load_snapshot(unresolved_snapshot)
assert controller.page.apply_button.isEnabled() is False
assert controller.page.issue_text() == "1 个前缀待确认"
- Step 2: Run focused UI tests and confirm missing page/controller
Run: $env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest tests/ui/test_refdes_page.py tests/ui/test_refdes_controller.py -v
Expected: fails on missing RefDesPage and RefDesController.
- Step 3: Implement the approved rules panel and preview table
Use segmented controls for scope and processing mode, combo boxes for numbering and order, numeric controls for start/page step/page start/row tolerance, checkboxes for preservation rules, a prefix summary, search/filter toolbar, and a fixed-column preview model. Preview status always includes icon plus text: 待更新, 已保留, 需确认, or 阻断.
- Step 4: Implement controller-driven live recomputation
The controller converts widget state into immutable AnnotationSettings, calls build_annotation_plan, updates rows/issues/counts without mutating the snapshot, and enables Apply only when plan.can_apply and at least one changed row are true. Search filters the presentation model only and never changes the plan.
- Step 5: Implement preview, Apply, cancel, and locate signals
Preview runs automatically after a valid request loads and explicitly when Refresh/Generate Preview is clicked. Python remains open throughout the transaction. Apply first writes the backup and then atomically publishes the ordered result.tsv; a QTimer polls for the VBS-written apply-status.json, updates history exactly once, and displays success, verified rollback, or rollback failure without closing the window. Cancel before result creation exits without writing result.tsv and therefore cannot change the design.
Double-clicking a row atomically writes a locate.tsv request containing its bridge ID; the active VBS mailbox loop consumes it exactly once and selects/zooms the mapped component without applying annotation changes.
- Step 6: Run UI/controller tests and full suite
Run: $env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest tests/ui -v
Run: $env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest -q
Expected: all tests pass.
- Step 7: Commit the automatic-reference-designator UI
git add src/dx_productivity/ui/refdes_page.py src/dx_productivity/ui/refdes_controller.py tests/ui
git commit -m "feat: add automatic refdes preview workflow"
Task 10: Installer, Startup Menu, and Verified Route Adapter
Files:
- Create:
integration/dxdesigner795/MenuAdd.vbs - Create:
integration/dxdesigner795/Install.ps1 - Create:
integration/dxdesigner795/Uninstall.ps1 - Create:
tests/integration/test_installer.py - Create:
tests/integration/test_menu_script.py
Interfaces:
-
Consumes: probe-selected route, resolved Python 3.12 executable, project installation root, and user-level environment/config storage.
-
Produces:
DXTOOLS_HOME,%LOCALAPPDATA%\DxProductivity\settings.json, one importableMenuAdd.vbs, and a menu action that invokesRefDesBridge.vbsthrough the proven 7.9.5 route. -
Step 1: Write failing dry-run installer and menu tests
def test_installer_dry_run_handles_spaces_and_chinese(tmp_path, powershell):
install_root = tmp_path / "效率 工具"
result = powershell("integration/dxdesigner795/Install.ps1", "-InstallRoot", str(install_root), "-WhatIf")
assert result.returncode == 0
assert f'DXTOOLS_HOME={install_root.resolve()}' in result.stdout
def test_menu_script_uses_environment_and_795_sheet_bar():
text = Path("integration/dxdesigner795/MenuAdd.vbs").read_text(encoding="utf-8")
assert 'Scripting.GetEnvVariable("DXTOOLS_HOME")' in text
assert 'CommandBars("Sheet Menu Bar")' 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_installer.py tests/integration/test_menu_script.py -v
Expected: fails because installer and release menu files do not exist.
- Step 3: Implement nonadmin user-level installation
Install.ps1 validates Python is exactly major/minor 3.12, confirms the package imports, stores the resolved executable and probe-selected route in UTF-8 settings.json, and sets DXTOOLS_HOME with [Environment]::SetEnvironmentVariable(..., "User"). -WhatIf prints all intended values without changing the environment or filesystem outside a temporary test root.
Uninstall.ps1 removes only the user-level environment variable and user-local DxProductivity configuration after confirming their resolved paths belong to the configured install. It prints the exact DxDesigner Scripts-list entry the user must remove manually.
- Step 4: Implement idempotent menu registration
MenuAdd.vbs removes only an existing menu control with the exact suite tag/caption before adding one replacement. It reads the verified route from settings and generates one 自动位号 action. The source remains ASCII-only and constructs all Chinese captions/messages with ChrW. Missing home/config shows one concise message and does not add a broken action.
- Step 5: Test paths, idempotency, and route rendering
Run: py -3.12 -m pytest tests/integration/test_installer.py tests/integration/test_menu_script.py -v
Expected: tests pass for paths with spaces/Chinese characters and for named, run, and form route fixtures.
- Step 6: Repeat the live startup-import smoke test
Import only integration/dxdesigner795/MenuAdd.vbs through Settings -> Run at Startup -> Scripts, restart DxDesigner twice, and confirm exactly one suite menu appears each time. Invoke 自动位号 and confirm the Python UI receives a request without modifying the design before Apply.
- Step 7: Commit installation and menu integration
git add integration/dxdesigner795/MenuAdd.vbs integration/dxdesigner795/Install.ps1 integration/dxdesigner795/Uninstall.ps1 tests/integration/test_installer.py tests/integration/test_menu_script.py
git commit -m "feat: install through DxDesigner 7.9.5 startup scripts"
Task 11: Mocked End-to-End Workflow, Visual QA, and Operator Documentation
Files:
- Create:
tests/integration/mock_dxdesigner.py - Create:
tests/integration/test_end_to_end.py - Create:
docs/user/refdes-tool.md - Create:
docs/testing/dxdesigner-795-live.md - Modify:
src/dx_productivity/__main__.py
Interfaces:
-
Consumes: the complete version-1 bridge protocol and all phase-one modules.
-
Produces: a repeatable mock workflow, release verification commands, installation/operator guide, and live 7.9.5 acceptance record.
-
Step 1: Write the failing mocked end-to-end test
def test_fill_only_end_to_end_creates_verified_schedule(tmp_path, basic_request):
mock = MockDxDesigner(tmp_path, basic_request)
result = mock.run_app(
scope="selected",
mode="fill-only",
numbering="continuous",
auto_apply=True,
)
assert result.exit_code == 0
assert result.final_refdes == {"c0001": "R1", "c0002": "C1", "c0003": "U1"}
assert result.status.state == "applied"
assert result.backup.exists()
- Step 2: Run the end-to-end test and confirm missing mock harness
Run: $env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest tests/integration/test_end_to_end.py -v
Expected: fails because MockDxDesigner is undefined.
- Step 3: Implement the mock bridge process
The mock writes a real request.json, launches python -m dx_productivity --request <path> --test-auto-apply, validates result.tsv through the same constraints as VBS, applies every expected-current step to an in-memory component map, writes apply-status.json, and verifies final values. It supports injected stale-state and assignment-failure cases to exercise rollback UI.
- Step 4: Add operator and live-acceptance documentation
docs/user/refdes-tool.md documents Python installation, Install.ps1, the exact 7.9.5 startup-script import steps, restart requirement, scope/mode/order controls, preview statuses, Apply, backup location, Restore Last Annotation, diagnostics, and uninstall.
docs/testing/dxdesigner-795-live.md contains checkboxes for menu idempotency, selected/current/full scope, page and continuous numbering, top-down/left-right coordinate order, multi-unit components, collisions, Chinese/space paths, cancel, stale-state rejection, successful apply, injected failure rollback, restore, and full-design duplicate scan. It records DxDesigner build, Windows version, Python version, probe route, date, project fixture, and tester.
- Step 5: Run automated tests and coverage
Run: $env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest --cov=dx_productivity --cov-report=term-missing
Expected: all tests pass; domain and bridge Python modules have at least 90% line coverage; no uncovered branch remains in collision, cycle scheduling, stale-state, or rollback-plan tests.
- Step 6: Run visual acceptance at required window/scaling combinations
Capture and inspect light, dark, warning, blocking, empty-selection, and populated-preview states at 1100x700 and 1440x900 logical sizes under 100%, 125%, and 150% Windows scaling. Verify no clipped text, overlapping controls, truncated longest Chinese label, unstable table columns, missing icon, invisible focus, or color-only status.
- Step 7: Run the live 7.9.5 checklist and record evidence
Execute every item in docs/testing/dxdesigner-795-live.md on the target installation. A failed item remains a release blocker and records the observed API value/error plus the fixture used. Mark compatibility complete only when the checklist contains no unresolved failure.
- Step 8: Build and smoke-test the distributable Python 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-productivity --request tests\fixtures\request-basic.json --test-auto-apply
Expected: wheel builds, installs, opens the fixture, writes a valid schedule, and exits successfully.
- Step 9: Commit end-to-end verification and documentation
git add src/dx_productivity/__main__.py tests/integration docs/user docs/testing
git commit -m "test: verify automatic refdes workflow end to end"
Task 12: Final Regression and Release Review
Files:
- Modify only files required by failures discovered in this task.
Interfaces:
-
Consumes: all phase-one deliverables and the completed live acceptance record.
-
Produces: a clean working tree at a tested release commit.
-
Step 1: Run every automated verification command from a clean environment
py -3.12 -m pip install -e ".[dev]"
$env:QT_QPA_PLATFORM = "offscreen"
py -3.12 -m pytest --cov=dx_productivity --cov-report=term-missing
cscript //nologo tests\vbs\test_bridge_common.vbs
git diff --check
git status --short
Expected: tests and VBS assertions pass, git diff --check is empty, and status contains only deliberately untracked local acceptance artifacts covered by .gitignore.
- Step 2: Verify requirement-to-test traceability
Check every section of docs/superpowers/specs/2026-09-01-dxdesigner-795-refdes-design.md against a named automated test or a checked live-acceptance item. Add a concrete test when a requirement lacks evidence; do not close the phase with prose-only assurance.
- Step 3: Review the final diff for version leakage and unsafe operations
Run: rg -n "D:\\NET_CHECK|ViewDraw\.Application|GetActiveObject|newer|On Error Resume Next" src integration tests docs/user docs/testing
Expected: no fixed legacy path, direct Python COM attachment, newer-release dependency, or operation-wide error suppression. Any narrowly scoped On Error Resume Next has an immediate Err check and restoration of normal error handling.
- Step 4: Commit only regression fixes when needed
git add <files changed by a demonstrated regression fix>
git commit -m "fix: address automatic refdes release checks"
Skip this commit when Step 1 through Step 3 require no file changes.