from __future__ import annotations import hashlib import json import os from pathlib import Path import re import subprocess from typing import Any import pytest from dx_productivity.part_replace.protocol import ( load_snapshot, load_status, snapshot_fingerprint, ) ROOT = Path(__file__).resolve().parents[2] COMMON = ROOT / "integration" / "dxdesigner795" / "BridgeCommon.vbs" BRIDGE = ROOT / "integration" / "dxdesigner795" / "PartReplaceBridge.vbs" _INTERFACES = ( "attributes", "gates", "hierarchy", "logical_identity", "mirror", "nets", "origin_x", "origin_y", "part_number", "pins", "position_x", "position_y", "refdes", "rotation", "symbol_identity", "units", ) _ROUTES = { "exact_set_selection": "ActiveView.SelectExactSet", "native_replace_part": "Application.OpenReplacePartDialog", "completion_observation": "Application.ReplacePartCompleted", "undo": "Application.Undo", "save": "Application.Save", "open_project": "Application.OpenProject", "close_project": "Application.CloseProject", "packager": "Application.RunPackager", "erc": "Application.RunERC", "netlist": "Application.RunNetlist", "ccomp_research": "Application.CComp", } def _vbs_string(value: str) -> str: return '"' + value.replace('"', '""') + '"' def _project_id(path: Path) -> str: identity = os.path.normcase(str(path.resolve(strict=False))) return hashlib.sha256(identity.encode("utf-8")).hexdigest()[:16] def _route_record(name: str, route: str, *, available: bool = True) -> dict[str, Any]: error = None if not available: error = { "description": "fixture route unavailable", "number": 51001, "operation": f"route.{name}.{route}", "source": "fixture.route", } record = { "attempted": True, "available": available, "manual_fallback": f"manual_{name}", "route": route, "attempts": [ { "attempted": True, "available": available, "error": error, "route": route, } ], } if name == "ccomp_research": record["production_enabled"] = False return record def _profile(*, live_checked: bool = True) -> dict[str, Any]: return { "format_version": 1, "dxdesigner": {"build": "7.9.5.1234", "version": "7.9.5"}, "project": {"active_view": "Sheet1", "dirty": False, "identity": "probe-fixture"}, "enumeration": { "available": True, "component_count": 3, "route": "Application.DesignComponents", }, "components": [], "interfaces": {name: {"available": True} for name in _INTERFACES}, "production_replace_route": "native_replace_part", "routes": {name: _route_record(name, route) for name, route in _ROUTES.items()}, "safety": { "disposable_project_marker": True, "mutating_probe_attempted": True, "mutating_probe_authorized": True, "operator_confirmation": True, "request_valid": True, }, "api_errors": [], "live_acceptance": { "checked": live_checked, **( { "evidence_sha256": "a" * 64, "reason": "live_795_acceptance_completed", } if live_checked else {"reason": "live_795_host_not_exercised"} ), }, } def _profile_component() -> dict[str, Any]: return { "api_errors": [], "attributes": [{"name": "Vendor", "value": "Acme"}], "gates": [{"name": "A", "unit_number": 1}], "hierarchy": "/MAIN", "logical_identity": "/MAIN|U1", "mirror": False, "nets": ["N1"], "origin": {"x": 0, "y": 0}, "part_number": "OLD-1", "pins": [{"name": "IN", "net_identity": "N1", "number": "1", "x": 0, "y": 0}], "position": {"x": 0, "y": 0}, "refdes": "U1", "rotation": 0, "symbol_identity": "IC_A", "units": 1, } def _command(project_path: Path, action: str = "inventory") -> dict[str, Any]: return { "action": action, "command_id": "command-1", "expected_count": 0, "expected_fingerprint": "", "expected_logical_keys": [], "format_version": 1, "job_id": "job-1", "new_part_number": "", "old_part_number": "", "project_id": _project_id(project_path), "scope": "full_project", } def _write_json(path: Path, value: object) -> None: path.write_text( json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n", encoding="utf-8", newline="", ) def _wrapper_source(root: Path, project_path: Path) -> str: return fr'''Option Explicit Dim RouteCalls Dim FailureOperation Dim SelectionMode Dim DialogPartNumber Dim CaptureModalStatus Dim ModalStatusText Dim CollectionAccessCount Sub FailIfRequested(ByVal Operation, ByVal Number, ByVal Source, ByVal Description) If FailureOperation = Operation Then Err.Raise Number, Source, Description End Sub Class FakeScripting Public Function GetEnvVariable(ByVal Name) If Name = "DXTOOLS_HOME" Then GetEnvVariable = {_vbs_string(str(root))} Else GetEnvVariable = "" End If End Function End Class Class FakeAttribute Public Name Public Value End Class Class FakeGate Public Name Public UnitNumber End Class Class FakePin Public Number Public Name Public X Public Y Public NetIdentity End Class Class FakeComponent Public ObjectId Public LogicalIdentity Public PartNumber Public RefDes Public Hierarchy Public Units Public Gates Public SymbolName Public OriginX Public OriginY Public X Public Y Public Rotation Public Mirrored Public Attributes Public Pins Public Nets End Class Function NewAttribute(ByVal Name, ByVal Value) Dim Result Set Result = New FakeAttribute Result.Name = Name Result.Value = Value Set NewAttribute = Result End Function Function NewGate(ByVal Name, ByVal Number) Dim Result Set Result = New FakeGate Result.Name = Name Result.UnitNumber = Number Set NewGate = Result End Function Function NewPin(ByVal Number, ByVal Name, ByVal X, ByVal Y, ByVal NetIdentity) Dim Result Set Result = New FakePin Result.Number = Number Result.Name = Name Result.X = X Result.Y = Y Result.NetIdentity = NetIdentity Set NewPin = Result End Function Function NewComponent(ByVal ObjectId, ByVal LogicalIdentity, ByVal PartNumber, _ ByVal RefDes, ByVal UnitId, ByVal UnitNumber, ByVal SymbolName, _ ByVal X, ByVal Y, ByVal Rotation, ByVal Mirrored, ByRef Pins, ByRef Nets) Dim Result Dim Gates(0) Dim Attributes(0) Set Result = New FakeComponent Result.ObjectId = ObjectId Result.LogicalIdentity = LogicalIdentity Result.PartNumber = PartNumber Result.RefDes = RefDes Result.Hierarchy = "/MAIN" Result.Units = 1 Set Gates(0) = NewGate(UnitId, UnitNumber) Result.Gates = Gates Result.SymbolName = SymbolName Result.OriginX = X - 0.5 Result.OriginY = Y - 0.5 Result.X = X Result.Y = Y Result.Rotation = Rotation Result.Mirrored = Mirrored Set Attributes(0) = NewAttribute("Vendor", "Acme") Result.Attributes = Attributes Result.Pins = Pins Result.Nets = Nets Set NewComponent = Result End Function Class FakeApplication Public ProjectPath Public Modified Public ComponentItems Private VersionValue Private BuildValue Private Sub Class_Initialize() VersionValue = "7.9.5" BuildValue = "7.9.5.1234" ProjectPath = {_vbs_string(str(project_path))} Modified = False End Sub Public Property Get Version FailIfRequested "Application.Version", 53008, _ "FakeApplication.Version", "version unavailable" Version = VersionValue End Property Public Property Get Build FailIfRequested "Application.Build", 53009, _ "FakeApplication.Build", "build unavailable" Build = BuildValue End Property Public Property Get DesignComponents If FailureOperation = "Application.DesignComponentsChanging" Then CollectionAccessCount = CollectionAccessCount + 1 If CollectionAccessCount = 1 Then Err.Raise 54001, "FakeApplication.DesignComponents.first", _ "first collection access failed" Else Err.Raise 54002, "FakeApplication.DesignComponents.second", _ "second collection access failed" End If End If FailIfRequested "Application.DesignComponents", 53001, _ "FakeApplication.DesignComponents", "enumeration unavailable" DesignComponents = ComponentItems End Property Public Function OpenReplacePartDialog Dim Item RouteCalls = RouteCalls & "native_replace_part|" FailIfRequested "Application.OpenReplacePartDialog", 53003, _ "FakeApplication.OpenReplacePartDialog", "dialog unavailable" If CaptureModalStatus Then ModalStatusText = DxReadUtf8({_vbs_string(str(root / "run" / "status.json"))}) End If For Each Item In ActiveView.SelectedObjects Item.PartNumber = DialogPartNumber Next Modified = True OpenReplacePartDialog = True End Function Public Property Get ReplacePartCompleted RouteCalls = RouteCalls & "completion_observation|" FailIfRequested "Application.ReplacePartCompleted", 53010, _ "FakeApplication.ReplacePartCompleted", "completion unavailable" ReplacePartCompleted = True End Property Public Function Undo Dim Item RouteCalls = RouteCalls & "undo|" FailIfRequested "Application.Undo", 53004, _ "FakeApplication.Undo", "undo unavailable" For Each Item In ComponentItems If Item.LogicalIdentity = "/MAIN|U1" Then Item.PartNumber = "OLD-1" Next Undo = True End Function Public Function Save RouteCalls = RouteCalls & "save|" FailIfRequested "Application.Save", 53005, _ "FakeApplication.Save", "save unavailable" Modified = False Save = True End Function Public Function OpenProject(ByVal Path) RouteCalls = RouteCalls & "open_project:" & CStr(Path) & "|" FailIfRequested "Application.OpenProject", 53006, _ "FakeApplication.OpenProject", "open unavailable" ProjectPath = CStr(Path) OpenProject = True End Function Public Function CloseProject RouteCalls = RouteCalls & "close_project|" FailIfRequested "Application.CloseProject", 53007, _ "FakeApplication.CloseProject", "close unavailable" If FailureOperation <> "Application.CloseProjectLeavesOpen" Then ProjectPath = "" End If CloseProject = True End Function Public Function RunPackager RouteCalls = RouteCalls & "packager|" FailIfRequested "Application.RunPackager", 53011, _ "FakeApplication.RunPackager", "Packager unavailable" If FailureOperation = "Application.RunPackagerFailed" Then RunPackager = False Else RunPackager = True End If End Function Public Function RunERC Dim Items RouteCalls = RouteCalls & "erc|" FailIfRequested "Application.RunERC", 53012, _ "FakeApplication.RunERC", "ERC unavailable" If FailureOperation = "Application.RunERCChangesDesign" Then Items = ComponentItems Items(1).PartNumber = "CHANGED-BY-ERC" Items(2).PartNumber = "CHANGED-BY-ERC" End If If FailureOperation = "Application.RunERCFailed" Then RunERC = False Else RunERC = True End If End Function Public Function RunNetlist RouteCalls = RouteCalls & "netlist|" FailIfRequested "Application.RunNetlist", 53013, _ "FakeApplication.RunNetlist", "netlist unavailable" If FailureOperation = "Application.RunNetlistFailed" Then RunNetlist = False Else RunNetlist = True End If End Function End Class Class FakeActiveView Public Name Private CurrentSelection Private Sub Class_Initialize() Name = "Sheet1" CurrentSelection = Array() End Sub Public Function SelectExactSet(ByRef Items) Dim Count Dim Expanded RouteCalls = RouteCalls & "exact_set_selection|" FailIfRequested "ActiveView.SelectExactSet", 53002, _ "FakeActiveView.SelectExactSet", "selection unavailable" If SelectionMode = "append_extra" Then Count = UBound(Items) - LBound(Items) + 1 ReDim Expanded(Count) Dim Index For Index = 0 To Count - 1 Set Expanded(Index) = Items(Index) Next Set Expanded(Count) = Application.ComponentItems(0) CurrentSelection = Expanded ElseIf SelectionMode = "scalar_selected" Then Count = UBound(Items) - LBound(Items) + 1 ReDim Expanded(Count - 1) Set Expanded(0) = Items(0) Expanded(1) = "not-a-selected-object" CurrentSelection = Expanded Else CurrentSelection = Items End If SelectExactSet = True End Function Public Sub SetManualSelection(ByRef Items) CurrentSelection = Items End Sub Public Property Get SelectedObjects SelectedObjects = CurrentSelection End Property End Class Sub InitializeManualSelection(ByRef View, ByRef Target, ByVal Mode) Dim Components Dim ManualItems Components = Target.ComponentItems Select Case CStr(Mode) Case "manual_exact" ReDim ManualItems(1) Set ManualItems(0) = Components(1) Set ManualItems(1) = Components(2) View.SetManualSelection ManualItems Case "manual_extra" ReDim ManualItems(2) Set ManualItems(0) = Components(1) Set ManualItems(1) = Components(2) Set ManualItems(2) = Components(0) View.SetManualSelection ManualItems Case "manual_duplicate" ReDim ManualItems(1) Set ManualItems(0) = Components(1) Set ManualItems(1) = Components(1) View.SetManualSelection ManualItems End Select End Sub Sub InitializeComponents(ByRef Target) Dim Components(2) Dim PinsR(0) Dim NetsR(0) Dim PinsA(1) Dim NetsA(1) Dim PinsB(0) Dim NetsB(0) Set PinsR(0) = NewPin("1", "R", 10, 20, "KEEP") NetsR(0) = "KEEP" Set Components(0) = NewComponent("R1-A", "/MAIN|R1", "KEEP-1", _ "R1", "A", 1, "RES", 10, 20, 0, False, PinsR, NetsR) Set PinsA(0) = NewPin("1", "IN", 101, 200, "N1") Set PinsA(1) = NewPin("2", "OUT", 99, 200, "N2") NetsA(0) = "N1" NetsA(1) = "N2" Set Components(1) = NewComponent("U1-A", "/MAIN|U1", InitialPartNumber, _ "U1", "A", 1, "IC_A", 100, 200, 90, False, PinsA, NetsA) Set PinsB(0) = NewPin("3", "IO", 111, 210, "N3") NetsB(0) = "N3" Set Components(2) = NewComponent("U1-B", "/MAIN|U1", InitialPartNumber, _ "U1", "B", 2, "IC_B", 110, 210, 0, True, PinsB, NetsB) Target.ComponentItems = Components End Sub Sub ApplyDataMode(ByRef Target, ByVal Mode) Dim Items Dim FirstTarget Dim SecondTarget Dim Gates Dim Pins Dim Attributes Dim Nets Dim BadValue Items = Target.ComponentItems Set FirstTarget = Items(1) Set SecondTarget = Items(2) Select Case CStr(Mode) Case "missing_identity" FirstTarget.LogicalIdentity = "" Case "duplicate_unit" Gates = SecondTarget.Gates Gates(0).Name = "A" Case "ambiguous_refdes" SecondTarget.RefDes = "U2" Case "missing_pins" SecondTarget.Pins = Array() Case "missing_net" SecondTarget.Nets = Array() Case "unconnected_pin" Pins = SecondTarget.Pins Pins(0).NetIdentity = Null SecondTarget.Nets = Array() Case "duplicate_pin" Pins = FirstTarget.Pins Pins(1).Number = "1" Case "non_object_component" Items(1) = "not-a-component" Target.ComponentItems = Items Case "non_object_attribute" Attributes = FirstTarget.Attributes Attributes(0) = "not-an-attribute" FirstTarget.Attributes = Attributes Case "non_object_gate" Gates = FirstTarget.Gates Gates(0) = "not-a-gate" FirstTarget.Gates = Gates Case "non_object_pin" Pins = FirstTarget.Pins Pins(0) = "not-a-pin" FirstTarget.Pins = Pins Case "object_gate_name" Gates = FirstTarget.Gates Set BadValue = CreateObject("Scripting.Dictionary") Set Gates(0).Name = BadValue Case "object_net" Nets = FirstTarget.Nets Set BadValue = CreateObject("Scripting.Dictionary") Set Nets(0) = BadValue FirstTarget.Nets = Nets Case "object_pin_net" Pins = FirstTarget.Pins Set BadValue = CreateObject("Scripting.Dictionary") Set Pins(0).NetIdentity = BadValue Case "object_project_path" Set BadValue = CreateObject("Scripting.Dictionary") Set Target.ProjectPath = BadValue Case "object_modified" Set BadValue = CreateObject("Scripting.Dictionary") Set Target.Modified = BadValue Case "multiple_object_coordinates" Set BadValue = CreateObject("Scripting.Dictionary") Set FirstTarget.OriginX = BadValue Set FirstTarget.OriginY = BadValue Case "multiple_object_pin_fields" Pins = FirstTarget.Pins Set BadValue = CreateObject("Scripting.Dictionary") Set Pins(0).Number = BadValue Set Pins(0).Name = BadValue End Select End Sub Function SelectedCsv() Dim Item Dim Result Result = "" For Each Item In ActiveView.SelectedObjects If Len(Result) > 0 Then Result = Result & "," If IsObject(Item) Then Result = Result & Item.ObjectId Else Result = Result & "" End If Next SelectedCsv = Result End Function Dim Fso Dim CommonSource Dim BridgeSource Dim Scripting Dim Application Dim ActiveView Dim InitialPartNumber Set Fso = CreateObject("Scripting.FileSystemObject") CommonSource = Fso.OpenTextFile({_vbs_string(str(COMMON))}, 1, False, 0).ReadAll ExecuteGlobal CommonSource BridgeSource = Fso.OpenTextFile({_vbs_string(str(BRIDGE))}, 1, False, 0).ReadAll ExecuteGlobal BridgeSource Set Scripting = New FakeScripting Set Application = New FakeApplication Set ActiveView = New FakeActiveView InitialPartNumber = WScript.Arguments(5) InitializeComponents Application Application.Modified = CBool(WScript.Arguments(6)) ApplyDataMode Application, WScript.Arguments(7) If CBool(WScript.Arguments(9)) Then Application.ProjectPath = "" RouteCalls = "" FailureOperation = WScript.Arguments(2) SelectionMode = WScript.Arguments(3) DialogPartNumber = WScript.Arguments(4) CaptureModalStatus = CBool(WScript.Arguments(8)) ModalStatusText = "" CollectionAccessCount = 0 InitializeManualSelection ActiveView, Application, SelectionMode DxRunPartReplaceBridge WScript.Arguments(0), "run\profile.json", _ "run\command.json", "run\status.json", "run\snapshot.json", _ WScript.Arguments(1) Dim CallsFile Set CallsFile = Fso.CreateTextFile(Fso.BuildPath({_vbs_string(str(root / 'run'))}, _ "route_calls.txt"), True, False) CallsFile.Write RouteCalls CallsFile.Close Dim SelectionFile Set SelectionFile = Fso.CreateTextFile(Fso.BuildPath({_vbs_string(str(root / 'run'))}, _ "selection.txt"), True, False) SelectionFile.Write SelectedCsv() SelectionFile.Close Dim ModalStatusFile Set ModalStatusFile = Fso.CreateTextFile(Fso.BuildPath({_vbs_string(str(root / 'run'))}, _ "modal_status.json"), True, False) ModalStatusFile.Write ModalStatusText ModalStatusFile.Close ''' def _run_bridge( tmp_path: Path, *, action: str, profile: dict[str, Any] | None = None, command: dict[str, Any] | None = None, project_path_argument: str = "", failure_operation: str = "", selection_mode: str = "exact", dialog_part_number: str = "NEW-1", initial_part_number: str = "OLD-1", initial_modified: bool = False, data_mode: str = "complete", capture_modal_status: bool = False, start_closed: bool = False, reuse: bool = False, ) -> tuple[Path, subprocess.CompletedProcess[str]]: project_path = tmp_path / "fixture" / "design.prj" project_path.parent.mkdir(exist_ok=reuse) project_path.write_text("fake project\n", encoding="ascii") run_dir = tmp_path / "run" run_dir.mkdir(exist_ok=reuse) if profile is not None or not (run_dir / "profile.json").exists(): _write_json(run_dir / "profile.json", profile or _profile()) if command is not None or not (run_dir / "command.json").exists(): _write_json(run_dir / "command.json", command or _command(project_path, action)) wrapper = tmp_path / "run_bridge.vbs" wrapper.write_text(_wrapper_source(tmp_path, project_path), encoding="ascii") completed = subprocess.run( [ "cscript", "//nologo", str(wrapper), action, project_path_argument, failure_operation, selection_mode, dialog_part_number, initial_part_number, str(initial_modified), data_mode, str(capture_modal_status), str(start_closed), ], cwd=ROOT, check=False, capture_output=True, text=True, encoding="utf-8", errors="replace", env={**os.environ, "PYTHONPATH": str(ROOT / "src")}, ) return run_dir, completed def _assert_cscript_ok(completed: subprocess.CompletedProcess[str]) -> None: output = completed.stdout + completed.stderr assert completed.returncode == 0, output assert "Microsoft VBScript" not in output, output def _snapshot_data(project_path: Path, part_number: str = "OLD-1") -> dict[str, Any]: return { "components": [ { "attributes": [{"name": "Vendor", "value": "Acme"}], "logical_key": "/MAIN|R1", "part_number": "KEEP-1", "refdes": "R1", "units": [ { "mirrored": False, "origin_x": "9.5", "origin_y": "19.5", "pins": [{"name": "R", "net": "KEEP", "number": "1", "x": "10", "y": "20"}], "rotation": 0, "sheet": "/MAIN", "symbol": "RES", "unit_id": "A", "x": "10", "y": "20", } ], }, { "attributes": [{"name": "Vendor", "value": "Acme"}], "logical_key": "/MAIN|U1", "part_number": part_number, "refdes": "U1", "units": [ { "mirrored": False, "origin_x": "99.5", "origin_y": "199.5", "pins": [ {"name": "IN", "net": "N1", "number": "1", "x": "101", "y": "200"}, {"name": "OUT", "net": "N2", "number": "2", "x": "99", "y": "200"}, ], "rotation": 90, "sheet": "/MAIN", "symbol": "IC_A", "unit_id": "A", "x": "100", "y": "200", }, { "mirrored": True, "origin_x": "109.5", "origin_y": "209.5", "pins": [{"name": "IO", "net": "N3", "number": "3", "x": "111", "y": "210"}], "rotation": 0, "sheet": "/MAIN", "symbol": "IC_B", "unit_id": "B", "x": "110", "y": "210", }, ], }, ], "format_version": 2, "project_id": _project_id(project_path), "project_path": str(project_path.resolve(strict=False)), } def _fingerprint(data: dict[str, Any]) -> str: canonical = json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(",", ":")) return hashlib.sha256(canonical.encode("utf-8")).hexdigest() def _replace_command(project_path: Path) -> dict[str, Any]: command = _command(project_path, "replace_part") command.update( { "expected_count": 1, "expected_fingerprint": _fingerprint(_snapshot_data(project_path)), "expected_logical_keys": ["/MAIN|U1"], "new_part_number": "NEW-1", "old_part_number": "OLD-1", } ) return command def _snapshot_command( project_path: Path, action: str, *, part_number: str = "OLD-1", ) -> dict[str, Any]: command = _command(project_path, action) command["expected_fingerprint"] = _fingerprint( _snapshot_data(project_path, part_number) ) return command def test_inventory_exports_complete_multi_unit_protocol_snapshot(tmp_path: Path) -> None: # Catches inventory dropping units, protected values, unrelated components, or fingerprint evidence. run_dir, completed = _run_bridge(tmp_path, action="inventory") _assert_cscript_ok(completed) snapshot = load_snapshot(run_dir / "snapshot.json") assert (run_dir / "snapshot.json").read_bytes().startswith(b"{") assert (run_dir / "snapshot.json").read_bytes().endswith(b"\n") assert snapshot.project_id == _project_id(tmp_path / "fixture" / "design.prj") assert Path(snapshot.project_path) == tmp_path / "fixture" / "design.prj" assert snapshot.fingerprint == snapshot_fingerprint(snapshot) assert [(component.logical_key, component.refdes, component.part_number) for component in snapshot.components] == [ ("/MAIN|R1", "R1", "KEEP-1"), ("/MAIN|U1", "U1", "OLD-1"), ] target = snapshot.components[1] assert target.attributes == (("Vendor", "Acme"),) assert [ (str(unit.origin_x), str(unit.origin_y), str(unit.x), str(unit.y)) for unit in target.units ] == [ ("99.5", "199.5", "100", "200"), ("109.5", "209.5", "110", "210"), ] assert [(unit.unit_id, unit.sheet, unit.symbol, str(unit.x), str(unit.y), unit.rotation, unit.mirrored) for unit in target.units] == [ ("A", "/MAIN", "IC_A", "100", "200", 90, False), ("B", "/MAIN", "IC_B", "110", "210", 0, True), ] assert [(pin.number, pin.name, str(pin.x), str(pin.y), pin.net) for pin in target.units[0].pins] == [ ("1", "IN", "101", "200", "N1"), ("2", "OUT", "99", "200", "N2"), ] status = load_status(run_dir / "status.json") assert status.state == "inventory_exported" assert status.snapshot_path == str((run_dir / "snapshot.json").resolve()) assert status.details == (("action", "inventory"), ("expected_count", "0"), ("job_id", "job-1")) assert (run_dir / "status.json").read_bytes().startswith(b"{") assert (run_dir / "status.json").read_bytes().endswith(b"\n") assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" @pytest.mark.parametrize( ("data_mode", "expected_code"), ( ("missing_identity", "missing_protected_field"), ("duplicate_unit", "duplicate_unit_identity"), ("ambiguous_refdes", "ambiguous_logical_identity"), ("missing_pins", "missing_pin_data"), ("missing_net", "missing_net_data"), ("duplicate_pin", "duplicate_pin_number"), ), ) def test_inventory_fails_closed_on_ambiguous_or_incomplete_live_evidence( tmp_path: Path, data_mode: str, expected_code: str, ) -> None: # Catches incomplete identity, unit, pin, or net data entering a versioned snapshot. run_dir, completed = _run_bridge( tmp_path, action="inventory", data_mode=data_mode, ) _assert_cscript_ok(completed) assert not (run_dir / "snapshot.json").exists() status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ("blocked", expected_code) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" def test_inventory_serializes_an_unconnected_pin_as_protocol_null(tmp_path: Path) -> None: # Catches VBScript coercing or rejecting the protocol's supported null net identity. run_dir, completed = _run_bridge( tmp_path, action="inventory", data_mode="unconnected_pin", ) _assert_cscript_ok(completed) snapshot = load_snapshot(run_dir / "snapshot.json") target = next( component for component in snapshot.components if component.logical_key == "/MAIN|U1" ) unit_b = next(unit for unit in target.units if unit.unit_id == "B") assert unit_b.pins[0].net is None assert load_status(run_dir / "status.json").state == "inventory_exported" @pytest.mark.parametrize( "malformed_key", ({"logical": "object"}, None, 7, ["nested"]), ) def test_command_rejects_malformed_expected_keys_without_vbscript_error( tmp_path: Path, malformed_key: Any, ) -> None: # Catches expected-key validation coercing an object/null/number before checking its type. project_path = tmp_path / "fixture" / "design.prj" command = _replace_command(project_path) command["expected_logical_keys"] = [malformed_key] run_dir, completed = _run_bridge(tmp_path, action="replace_part", command=command) _assert_cscript_ok(completed) status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ("blocked", "invalid_command") assert dict(status.details)["operation"] == "command.expected_logical_keys" @pytest.mark.parametrize( "field_name", ("action", "command_id", "expected_count", "job_id", "project_id"), ) def test_malformed_command_status_fields_publish_loadable_blocking_status( tmp_path: Path, field_name: str, ) -> None: # Catches command-validation failure publication coercing an untrusted JSON object. project_path = tmp_path / "fixture" / "design.prj" command = _command(project_path) command[field_name] = {"malformed": "object"} run_dir, completed = _run_bridge( tmp_path, action="inventory", command=command, ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ("blocked", "invalid_command") assert isinstance(status.command_id, str) assert isinstance(status.project_id, str) @pytest.mark.parametrize( ("data_mode", "expected_operation"), ( ("non_object_component", "Application.DesignComponents"), ("non_object_attribute", "component.Attributes"), ("non_object_gate", "component.Gates"), ("non_object_pin", "component.Pins"), ("object_gate_name", "component.Gates.Name"), ("object_net", "component.Nets"), ("object_pin_net", "component.Pins.NetIdentity"), ), ) def test_inventory_blocks_malformed_live_values_without_vbscript_error( tmp_path: Path, data_mode: str, expected_operation: str, ) -> None: # Catches live collection items or gate/net values reaching Set/CStr before type validation. run_dir, completed = _run_bridge( tmp_path, action="inventory", data_mode=data_mode, ) _assert_cscript_ok(completed) status = load_status(run_dir / "status.json") assert status.state == "blocked" assert status.error_code == "missing_protected_field" assert dict(status.details)["operation"] == expected_operation @pytest.mark.parametrize( ("data_mode", "expected_operation"), ( ("multiple_object_coordinates", "component.OriginX"), ("multiple_object_pin_fields", "component.Pins.Number"), ), ) def test_inventory_preserves_first_malformed_field_evidence( tmp_path: Path, data_mode: str, expected_operation: str, ) -> None: # Catches eager VBScript Or evaluation replacing the first malformed-field failure. run_dir, completed = _run_bridge( tmp_path, action="inventory", data_mode=data_mode, ) _assert_cscript_ok(completed) status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ( "blocked", "missing_protected_field", ) assert dict(status.details)["operation"] == expected_operation def test_inventory_rejects_object_project_path_before_string_conversion(tmp_path: Path) -> None: # Catches an object-valued live project identity reaching Trim/CStr. run_dir, completed = _run_bridge( tmp_path, action="inventory", data_mode="object_project_path", ) _assert_cscript_ok(completed) status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ( "blocked", "missing_protected_field", ) assert dict(status.details)["operation"] == "Application.ProjectPath" def test_navigation_rejects_object_project_path_before_string_conversion( tmp_path: Path, ) -> None: # Catches a malformed active-project identity reaching path comparison or conversion. next_path = tmp_path / "next" / "next.prj" next_path.parent.mkdir() next_path.write_text("next fake project\n", encoding="ascii") command = _snapshot_command(next_path, "open_project") run_dir, completed = _run_bridge( tmp_path, action="open_project", command=command, project_path_argument=str(next_path), data_mode="object_project_path", ) _assert_cscript_ok(completed) status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ( "blocked", "missing_protected_field", ) assert dict(status.details)["operation"] == "Application.ProjectPath.before_open" def test_automatic_selection_rejects_non_object_selected_value(tmp_path: Path) -> None: # Catches a scalar selected-object entry reaching Set after the route returns. project_path = tmp_path / "fixture" / "design.prj" run_dir, completed = _run_bridge( tmp_path, action="replace_part", command=_replace_command(project_path), selection_mode="scalar_selected", ) _assert_cscript_ok(completed) status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ( "blocked", "missing_protected_field", ) assert dict(status.details)["operation"] == "ActiveView.SelectedObjects" def test_apply_rejects_stale_snapshot_before_selection(tmp_path: Path) -> None: # Catches any selection or dialog side effect occurring before the complete current fingerprint matches. project_path = tmp_path / "fixture" / "design.prj" command = _replace_command(project_path) command["expected_fingerprint"] = "0" * 64 run_dir, completed = _run_bridge(tmp_path, action="replace_part", command=command) _assert_cscript_ok(completed) status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ("blocked", "stale_snapshot") assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" assert (run_dir / "selection.txt").read_text(encoding="ascii") == "" def test_apply_rejects_wrong_active_project_before_selection(tmp_path: Path) -> None: # Catches a valid snapshot command being applied to a different active project. project_path = tmp_path / "fixture" / "design.prj" command = _replace_command(project_path) command["project_id"] = "wrong-project" run_dir, completed = _run_bridge(tmp_path, action="replace_part", command=command) _assert_cscript_ok(completed) status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ( "blocked", "project_identity_mismatch", ) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" assert (run_dir / "selection.txt").read_text(encoding="ascii") == "" def test_apply_selects_every_unit_once_then_publishes_manual_native_fallback( tmp_path: Path, ) -> None: # Catches per-unit dialogs, unrelated selection, or an unavailable native route being called anyway. project_path = tmp_path / "fixture" / "design.prj" profile = _profile() profile["routes"]["native_replace_part"] = _route_record( "native_replace_part", _ROUTES["native_replace_part"], available=False ) run_dir, completed = _run_bridge( tmp_path, action="replace_part", profile=profile, command=_replace_command(project_path), ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "exact_set_selection|" assert (run_dir / "selection.txt").read_text(encoding="ascii") == "U1-A,U1-B" status = load_status(run_dir / "status.json") assert status.state == "manual_action_required" assert status.error_code is None details = dict(status.details) assert details["manual_route"] == "manual_native_dialog" assert details["old_part_number"] == "OLD-1" assert details["new_part_number"] == "NEW-1" assert details["expected_count"] == "1" def test_apply_rejects_extra_object_returned_by_exact_selection_route(tmp_path: Path) -> None: # Catches a route claiming exact selection while retaining an unrelated live object. project_path = tmp_path / "fixture" / "design.prj" run_dir, completed = _run_bridge( tmp_path, action="replace_part", command=_replace_command(project_path), selection_mode="append_extra", ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "exact_set_selection|" assert (run_dir / "selection.txt").read_text(encoding="ascii") == "U1-A,U1-B,R1-A" status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ("blocked", "selection_mismatch") def test_apply_uses_verified_modal_native_route_and_exports_after_return(tmp_path: Path) -> None: # Catches post-operation export occurring before the verified modal call returns. project_path = tmp_path / "fixture" / "design.prj" run_dir, completed = _run_bridge( tmp_path, action="replace_part", command=_replace_command(project_path), ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == ( "exact_set_selection|native_replace_part|completion_observation|" ) assert (run_dir / "selection.txt").read_text(encoding="ascii") == "U1-A,U1-B" snapshot = load_snapshot(run_dir / "snapshot.json") assert snapshot.components[1].part_number == "NEW-1" assert snapshot.fingerprint == snapshot_fingerprint(snapshot) status = load_status(run_dir / "status.json") assert status.state == "applied" assert status.snapshot_path == str((run_dir / "snapshot.json").resolve()) def test_automatic_modal_requires_completion_observation_before_snapshot( tmp_path: Path, ) -> None: # Catches snapshot export immediately after the dialog route without completion evidence. project_path = tmp_path / "fixture" / "design.prj" run_dir, completed = _run_bridge( tmp_path, action="replace_part", command=_replace_command(project_path), failure_operation="Application.ReplacePartCompleted", ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == ( "exact_set_selection|native_replace_part|completion_observation|" ) assert not (run_dir / "snapshot.json").exists() status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ("blocked", "api_error") def test_automatic_modal_publishes_correlated_operator_status_before_call( tmp_path: Path, ) -> None: # Catches a modal mutation starting before durable old/new/count/Library Wins evidence exists. project_path = tmp_path / "fixture" / "design.prj" run_dir, completed = _run_bridge( tmp_path, action="replace_part", command=_replace_command(project_path), capture_modal_status=True, ) _assert_cscript_ok(completed) during_modal = load_status(run_dir / "modal_status.json") assert during_modal.state == "native_dialog_opening" assert during_modal.command_id == "command-1" assert during_modal.project_id == _project_id(project_path) assert dict(during_modal.details) == { "action": "replace_part", "expected_count": "1", "instruction": "Confirm the displayed target and choose Library Wins", "job_id": "job-1", "library_choice": "Library Wins", "new_part_number": "NEW-1", "old_part_number": "OLD-1", } assert load_status(run_dir / "status.json").state == "applied" def test_apply_rejects_a_noncanonical_selection_route_name(tmp_path: Path) -> None: # Catches a similarly named route being accepted as valid profile evidence. project_path = tmp_path / "fixture" / "design.prj" profile = _profile() profile["routes"]["exact_set_selection"]["route"] = "ActiveView.SelectAlmostExact" run_dir, completed = _run_bridge( tmp_path, action="replace_part", profile=profile, command=_replace_command(project_path), ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" assert (run_dir / "selection.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ( "blocked", "compatibility_profile_invalid", ) assert dict(status.details)["operation"] == ( "profile.routes.exact_set_selection.route" ) def test_unverified_profile_falls_back_to_manual_selection_without_automatic_routes( tmp_path: Path, ) -> None: # Catches unchecked live evidence either blocking the manual path or authorizing automatic routes. project_path = tmp_path / "fixture" / "design.prj" run_dir, completed = _run_bridge( tmp_path, action="replace_part", profile=_profile(live_checked=False), command=_replace_command(project_path), ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" assert (run_dir / "selection.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert status.state == "manual_action_required" assert status.error_code is None assert dict(status.details)["manual_route"] == "manual_exact_selection" def test_unverified_profile_falls_back_to_manual_project_navigation(tmp_path: Path) -> None: # Catches unchecked route evidence authorizing automatic project open or blocking its fallback. next_path = tmp_path / "next" / "next.prj" next_path.parent.mkdir() next_path.write_text("next fake project\n", encoding="ascii") command = _snapshot_command(next_path, "open_project") run_dir, completed = _run_bridge( tmp_path, action="open_project", profile=_profile(live_checked=False), command=command, project_path_argument=str(next_path), start_closed=True, ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert status.state == "manual_project_open_required" assert status.error_code is None assert dict(status.details)["canonical_next_path"] == str(next_path.resolve()) def test_profile_schema_is_fully_validated_before_application_access(tmp_path: Path) -> None: # Catches a malformed late route record being hidden by an earlier live Application access. profile = _profile() profile["routes"]["save"]["attempts"][0]["error"] = [] run_dir, completed = _run_bridge( tmp_path, action="inventory", profile=profile, failure_operation="Application.Version", ) _assert_cscript_ok(completed) status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ( "blocked", "compatibility_profile_invalid", ) assert dict(status.details)["operation"] == "profile.routes.save.attempts[0].error" def test_nested_profile_net_type_is_validated_before_assignment(tmp_path: Path) -> None: # Catches an object-valued probe pin net escaping through Variant assignment before live access. profile = _profile() component = _profile_component() component["pins"][0]["net_identity"] = {"not": "a net"} profile["components"] = [component] run_dir, completed = _run_bridge( tmp_path, action="inventory", profile=profile, failure_operation="Application.Version", ) _assert_cscript_ok(completed) status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ( "blocked", "compatibility_profile_invalid", ) assert dict(status.details)["operation"] == "profile.components[0].pins[0].net_identity" @pytest.mark.parametrize( ("field_path", "malformed_value"), ( (("format_version",), {}), (("live_acceptance",), True), (("live_acceptance", "checked"), {}), (("live_acceptance", "reason"), {}), (("dxdesigner",), []), (("dxdesigner", "version"), {}), (("project",), []), (("project", "dirty"), {}), (("enumeration",), []), (("enumeration", "available"), {}), (("enumeration", "route"), {}), (("enumeration", "component_count"), 1.5), (("components",), [True]), (("interfaces",), []), (("interfaces", "pins"), True), (("interfaces", "pins", "available"), {}), (("routes",), []), (("safety",), []), (("safety", "request_valid"), {}), (("api_errors",), [True]), (("production_replace_route",), {}), ), ) def test_malformed_profile_types_publish_blocked_status_without_live_access( tmp_path: Path, field_path: tuple[str, ...], malformed_value: Any, ) -> None: # Catches malformed nested JSON escaping profile validation as a VBScript runtime error. profile = _profile() container = profile for field_name in field_path[:-1]: container = container[field_name] container[field_path[-1]] = malformed_value run_dir, completed = _run_bridge( tmp_path, action="inventory", profile=profile, failure_operation="Application.Version", ) _assert_cscript_ok(completed) assert not (run_dir / "snapshot.json").exists() assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" assert (run_dir / "selection.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ( "blocked", "compatibility_profile_invalid", ) @pytest.mark.parametrize( ("field_path", "malformed_value"), ( (("routes", "exact_set_selection"), True), (("routes", "exact_set_selection"), []), (("routes", "exact_set_selection", "route"), {}), (("routes", "exact_set_selection", "attempts"), [True]), (("routes", "exact_set_selection", "attempts", 0, "route"), {}), ), ) def test_malformed_route_evidence_is_blocked_without_live_access( tmp_path: Path, field_path: tuple[str | int, ...], malformed_value: Any, ) -> None: # Catches malformed route evidence reaching live access or being presented as a usable fallback. project_path = tmp_path / "fixture" / "design.prj" profile = _profile() container = profile for field_name in field_path[:-1]: container = container[field_name] container[field_path[-1]] = malformed_value run_dir, completed = _run_bridge( tmp_path, action="replace_part", profile=profile, command=_replace_command(project_path), failure_operation="Application.Version", ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" assert (run_dir / "selection.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ( "blocked", "compatibility_profile_invalid", ) def _start_manual_dialog_handoff(tmp_path: Path) -> tuple[Path, dict[str, Any]]: project_path = tmp_path / "fixture" / "design.prj" profile = _profile() profile["routes"]["native_replace_part"] = _route_record( "native_replace_part", _ROUTES["native_replace_part"], available=False ) command = _replace_command(project_path) run_dir, completed = _run_bridge( tmp_path, action="replace_part", profile=profile, command=command, ) _assert_cscript_ok(completed) assert load_status(run_dir / "status.json").state == "manual_action_required" return run_dir, command def _start_manual_selection_handoff( tmp_path: Path, *, live_checked: bool = True, native_available: bool = False, ) -> tuple[Path, dict[str, Any], dict[str, Any]]: project_path = tmp_path / "fixture" / "design.prj" profile = _profile(live_checked=live_checked) profile["routes"]["exact_set_selection"] = _route_record( "exact_set_selection", _ROUTES["exact_set_selection"], available=False ) profile["routes"]["native_replace_part"] = _route_record( "native_replace_part", _ROUTES["native_replace_part"], available=native_available ) command = _replace_command(project_path) run_dir, completed = _run_bridge( tmp_path, action="replace_part", profile=profile, command=command, ) _assert_cscript_ok(completed) status = load_status(run_dir / "status.json") assert status.state == "manual_action_required" assert dict(status.details)["manual_route"] == "manual_exact_selection" return run_dir, command, profile def test_continue_after_manual_selection_verifies_exact_selection_then_hands_off_dialog( tmp_path: Path, ) -> None: # Catches a manual selection being trusted without read-only exact-set verification. run_dir, command, _ = _start_manual_selection_handoff(tmp_path) _, completed = _run_bridge( tmp_path, action="continue_after_manual_selection", command=command, selection_mode="manual_exact", reuse=True, ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" assert (run_dir / "selection.txt").read_text(encoding="ascii") == "U1-A,U1-B" status = load_status(run_dir / "status.json") assert status.state == "manual_action_required" details = dict(status.details) assert details["manual_route"] == "manual_native_dialog" assert details["old_part_number"] == "OLD-1" assert details["new_part_number"] == "NEW-1" def test_continue_after_manual_selection_rejects_extra_selected_object(tmp_path: Path) -> None: # Catches a manual selection containing an unrelated object reaching the native dialog path. run_dir, command, _ = _start_manual_selection_handoff(tmp_path) _, completed = _run_bridge( tmp_path, action="continue_after_manual_selection", command=command, selection_mode="manual_extra", reuse=True, ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ("blocked", "selection_mismatch") def test_continue_after_manual_selection_rejects_uncorrelated_prior_status( tmp_path: Path, ) -> None: # Catches a selection continuation from another command or job being accepted. run_dir, command, _ = _start_manual_selection_handoff(tmp_path) prior = json.loads((run_dir / "status.json").read_text(encoding="utf-8")) prior["command_id"] = "stale-command" _write_json(run_dir / "status.json", prior) _, completed = _run_bridge( tmp_path, action="continue_after_manual_selection", command=command, selection_mode="manual_exact", reuse=True, ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ( "blocked", "manual_continuation_mismatch", ) def test_continue_after_manual_selection_never_uses_unchecked_automatic_dialog( tmp_path: Path, ) -> None: # Catches probe-only route evidence authorizing a modal call after manual selection. run_dir, command, _ = _start_manual_selection_handoff( tmp_path, live_checked=False, native_available=True, ) _, completed = _run_bridge( tmp_path, action="continue_after_manual_selection", command=command, selection_mode="manual_exact", reuse=True, ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert status.state == "manual_action_required" assert dict(status.details)["manual_route"] == "manual_native_dialog" def test_continue_after_manual_selection_uses_live_accepted_automatic_dialog( tmp_path: Path, ) -> None: # Catches a verified native dialog route being ignored after exact manual selection. run_dir, command, _ = _start_manual_selection_handoff( tmp_path, native_available=True, ) _, completed = _run_bridge( tmp_path, action="continue_after_manual_selection", command=command, selection_mode="manual_exact", reuse=True, ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == ( "native_replace_part|completion_observation|" ) snapshot = load_snapshot(run_dir / "snapshot.json") assert snapshot.components[1].part_number == "NEW-1" assert load_status(run_dir / "status.json").state == "applied" def test_manual_selection_and_dialog_continuations_remain_separate(tmp_path: Path) -> None: # Catches selection continuation incorrectly treating an unopened manual dialog as completed Apply. run_dir, command, _ = _start_manual_selection_handoff(tmp_path) _, selected = _run_bridge( tmp_path, action="continue_after_manual_selection", command=command, selection_mode="manual_exact", reuse=True, ) _assert_cscript_ok(selected) assert load_status(run_dir / "status.json").state == "manual_action_required" _, completed = _run_bridge( tmp_path, action="continue_after_manual_dialog", command=command, initial_part_number="NEW-1", initial_modified=True, reuse=True, ) _assert_cscript_ok(completed) snapshot = load_snapshot(run_dir / "snapshot.json") assert snapshot.components[1].part_number == "NEW-1" assert load_status(run_dir / "status.json").state == "applied" def test_unverified_profile_allows_correlated_manual_dialog_continuation( tmp_path: Path, ) -> None: # Catches the unchecked live gate blocking a correlated read-only post-dialog export. run_dir, command, _ = _start_manual_selection_handoff( tmp_path, live_checked=False, ) _, selected = _run_bridge( tmp_path, action="continue_after_manual_selection", command=command, selection_mode="manual_exact", reuse=True, ) _assert_cscript_ok(selected) assert dict(load_status(run_dir / "status.json").details)["manual_route"] == ( "manual_native_dialog" ) _, completed = _run_bridge( tmp_path, action="continue_after_manual_dialog", command=command, initial_part_number="NEW-1", initial_modified=True, reuse=True, ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" snapshot = load_snapshot(run_dir / "snapshot.json") assert snapshot.components[1].part_number == "NEW-1" assert load_status(run_dir / "status.json").state == "applied" def test_continue_after_manual_dialog_correlates_then_exports_fresh_snapshot( tmp_path: Path, ) -> None: # Catches continuation trusting menu timing instead of the durable correlated handoff. run_dir, command = _start_manual_dialog_handoff(tmp_path) _, completed = _run_bridge( tmp_path, action="continue_after_manual_dialog", command=command, initial_part_number="NEW-1", initial_modified=True, reuse=True, ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" snapshot = load_snapshot(run_dir / "snapshot.json") assert snapshot.components[1].part_number == "NEW-1" assert snapshot.fingerprint == snapshot_fingerprint(snapshot) status = load_status(run_dir / "status.json") assert status.state == "applied" assert status.details == ( ("action", "replace_part"), ("expected_count", "1"), ("job_id", "job-1"), ) def _corrupt_prior_status(path: Path, corruption: str) -> None: data = json.loads(path.read_text(encoding="utf-8")) if corruption == "command": data["command_id"] = "stale-command" elif corruption == "project": data["project_id"] = "wrong-project" elif corruption == "state": data["state"] = "applying" else: details = dict(data["details"]) details["job_id" if corruption == "job" else "action"] = "wrong" data["details"] = [[name, details[name]] for name in ("action", "expected_count", "job_id")] _write_json(path, data) @pytest.mark.parametrize("corruption", ("command", "project", "job", "action", "state")) def test_continue_after_manual_dialog_rejects_uncorrelated_prior_status( tmp_path: Path, corruption: str, ) -> None: # Catches stale or cross-job manual continuation authorizing a snapshot as completed Apply evidence. run_dir, command = _start_manual_dialog_handoff(tmp_path) _corrupt_prior_status(run_dir / "status.json", corruption) _, completed = _run_bridge( tmp_path, action="continue_after_manual_dialog", command=command, initial_part_number="NEW-1", initial_modified=True, reuse=True, ) _assert_cscript_ok(completed) assert not (run_dir / "snapshot.json").exists() assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ( "blocked", "manual_continuation_mismatch", ) @pytest.mark.parametrize("malformed_version", (1.0, {"version": 1})) def test_manual_continuation_rejects_non_integer_status_version_without_vbscript_error( tmp_path: Path, malformed_version: Any, ) -> None: # Catches status validation accepting a numeric double or coercing an object through CLng. run_dir, command = _start_manual_dialog_handoff(tmp_path) prior = json.loads((run_dir / "status.json").read_text(encoding="utf-8")) prior["format_version"] = malformed_version _write_json(run_dir / "status.json", prior) _, completed = _run_bridge( tmp_path, action="continue_after_manual_dialog", command=command, initial_part_number="NEW-1", initial_modified=True, reuse=True, ) _assert_cscript_ok(completed) status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ( "blocked", "manual_continuation_mismatch", ) def _start_applied_operation(tmp_path: Path) -> tuple[Path, dict[str, Any], str]: project_path = tmp_path / "fixture" / "design.prj" command = _replace_command(project_path) run_dir, completed = _run_bridge( tmp_path, action="replace_part", command=command, ) _assert_cscript_ok(completed) snapshot = load_snapshot(run_dir / "snapshot.json") assert load_status(run_dir / "status.json").state == "applied" return run_dir, command, snapshot.fingerprint def _control_command( replace_command: dict[str, Any], action: str, expected_fingerprint: str, ) -> dict[str, Any]: command = dict(replace_command) command["action"] = action command["expected_fingerprint"] = expected_fingerprint return command @pytest.mark.parametrize( ("action", "state", "part_number", "route_call"), ( ("undo", "undo_verified", "OLD-1", "undo|"), ("save", "saved", "NEW-1", "save|"), ), ) def test_undo_and_save_require_correlated_explicit_commands_and_export( tmp_path: Path, action: str, state: str, part_number: str, route_call: str, ) -> None: # Catches direct menu mutation without a fresh expected fingerprint and applied-status correlation. run_dir, replace_command, current_fingerprint = _start_applied_operation(tmp_path) command = _control_command(replace_command, action, current_fingerprint) _, completed = _run_bridge( tmp_path, action=action, command=command, initial_part_number="NEW-1", initial_modified=True, reuse=True, ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == route_call snapshot = load_snapshot(run_dir / "snapshot.json") assert snapshot.components[1].part_number == part_number assert snapshot.fingerprint == snapshot_fingerprint(snapshot) status = load_status(run_dir / "status.json") assert status.state == state assert dict(status.details)["action"] == "replace_part" @pytest.mark.parametrize("action", ("undo", "save")) def test_undo_and_save_reject_stale_current_fingerprint_before_route( tmp_path: Path, action: str, ) -> None: # Catches Undo or Save running against live state other than Python's explicitly expected state. run_dir, replace_command, _ = _start_applied_operation(tmp_path) command = _control_command(replace_command, action, "0" * 64) _, completed = _run_bridge( tmp_path, action=action, command=command, initial_part_number="NEW-1", initial_modified=True, reuse=True, ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ("blocked", "stale_snapshot") @pytest.mark.parametrize("action", ("undo", "save")) def test_undo_and_save_reject_wrong_prior_bridge_status( tmp_path: Path, action: str, ) -> None: # Catches a same-project command being replayed after the correlated applied status was lost. run_dir, replace_command, current_fingerprint = _start_applied_operation(tmp_path) prior = json.loads((run_dir / "status.json").read_text(encoding="utf-8")) prior["state"] = "manual_action_required" _write_json(run_dir / "status.json", prior) command = _control_command(replace_command, action, current_fingerprint) _, completed = _run_bridge( tmp_path, action=action, command=command, initial_part_number="NEW-1", initial_modified=True, reuse=True, ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ( "blocked", "manual_continuation_mismatch", ) def test_control_rejects_non_integer_prior_status_version(tmp_path: Path) -> None: # Catches a floating-point status protocol version authorizing Undo. run_dir, replace_command, current_fingerprint = _start_applied_operation(tmp_path) prior = json.loads((run_dir / "status.json").read_text(encoding="utf-8")) prior["format_version"] = 1.0 _write_json(run_dir / "status.json", prior) command = _control_command(replace_command, "undo", current_fingerprint) _, completed = _run_bridge( tmp_path, action="undo", command=command, initial_part_number="NEW-1", initial_modified=True, reuse=True, ) _assert_cscript_ok(completed) status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ( "blocked", "control_status_mismatch", ) @pytest.mark.parametrize( "malformed_snapshot_path", (None, 7, {"path": "snapshot.json"}), ) def test_control_rejects_malformed_applied_snapshot_path_before_route( tmp_path: Path, malformed_snapshot_path: Any, ) -> None: # Catches a structurally invalid prior applied status authorizing native Undo. run_dir, replace_command, current_fingerprint = _start_applied_operation(tmp_path) prior = json.loads((run_dir / "status.json").read_text(encoding="utf-8")) prior["snapshot_path"] = malformed_snapshot_path _write_json(run_dir / "status.json", prior) command = _control_command(replace_command, "undo", current_fingerprint) _, completed = _run_bridge( tmp_path, action="undo", command=command, initial_part_number="NEW-1", initial_modified=True, reuse=True, ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ( "blocked", "control_status_mismatch", ) @pytest.mark.parametrize( ("action", "manual_route"), (("undo", "manual_native_undo"), ("save", "manual_native_save")), ) def test_undo_and_save_use_manual_status_when_exact_route_is_unverified( tmp_path: Path, action: str, manual_route: str, ) -> None: # Catches an unavailable profile flag being ignored for a mutating route. run_dir, replace_command, current_fingerprint = _start_applied_operation(tmp_path) profile = _profile() profile["routes"][action] = _route_record(action, _ROUTES[action], available=False) command = _control_command(replace_command, action, current_fingerprint) _, completed = _run_bridge( tmp_path, action=action, profile=profile, command=command, initial_part_number="NEW-1", initial_modified=True, reuse=True, ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert status.state == "manual_action_required" assert dict(status.details)["manual_route"] == manual_route @pytest.mark.parametrize( ("action", "manual_route"), (("undo", "manual_native_undo"), ("save", "manual_native_save")), ) def test_unverified_profile_never_authorizes_automatic_control_route( tmp_path: Path, action: str, manual_route: str, ) -> None: # Catches unchecked probe evidence authorizing Undo/Save or implying automatic verification. run_dir, replace_command, current_fingerprint = _start_applied_operation(tmp_path) command = _control_command(replace_command, action, current_fingerprint) _, completed = _run_bridge( tmp_path, action=action, profile=_profile(live_checked=False), command=command, initial_part_number="NEW-1", initial_modified=True, reuse=True, ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert status.state == "manual_action_required" details = dict(status.details) assert details["manual_route"] == manual_route assert details["instruction"] == ( f"Use native {action} manually; completion is not automatically verified" ) @pytest.mark.parametrize( ("action", "observed_part", "observed_modified", "final_state"), ( ("undo", "OLD-1", True, "undo_verified"), ("save", "NEW-1", False, "saved"), ), ) def test_manual_control_continuation_observes_live_result_without_route_replay( tmp_path: Path, action: str, observed_part: str, observed_modified: bool, final_state: str, ) -> None: # Catches the manual Undo/Save fallback replacing applied status with a permanent dead end. run_dir, replace_command, current_fingerprint = _start_applied_operation(tmp_path) command = _control_command(replace_command, action, current_fingerprint) profile = _profile() profile["routes"][action] = _route_record(action, _ROUTES[action], available=False) _, first = _run_bridge( tmp_path, action=action, profile=profile, command=command, initial_part_number="NEW-1", initial_modified=True, reuse=True, ) _assert_cscript_ok(first) assert load_status(run_dir / "status.json").state == "manual_action_required" _, second = _run_bridge( tmp_path, action=action, profile=profile, command=command, initial_part_number=observed_part, initial_modified=observed_modified, reuse=True, ) _assert_cscript_ok(second) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" snapshot = load_snapshot(run_dir / "snapshot.json") assert snapshot.components[1].part_number == observed_part assert load_status(run_dir / "status.json").state == final_state def test_clean_close_publishes_complete_snapshot_and_proves_project_closed( tmp_path: Path, ) -> None: # Catches backup authorization from a close call without correlated live-state evidence. project_path = tmp_path / "fixture" / "design.prj" command = _snapshot_command(project_path, "close_project") run_dir, completed = _run_bridge( tmp_path, action="close_project", command=command, ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "close_project|" snapshot = load_snapshot(run_dir / "snapshot.json") assert snapshot.fingerprint == command["expected_fingerprint"] status = load_status(run_dir / "status.json") assert status.state == "project_closed" assert status.snapshot_path == str((run_dir / "snapshot.json").resolve()) def test_clean_close_rejects_dirty_project_before_route(tmp_path: Path) -> None: # Catches a dirty in-memory project being treated as safe input for the backup boundary. project_path = tmp_path / "fixture" / "design.prj" command = _snapshot_command(project_path, "close_project") run_dir, completed = _run_bridge( tmp_path, action="close_project", command=command, initial_modified=True, ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ("blocked", "dirty_project") def test_close_without_save_exports_discarded_state_even_when_fingerprint_differs( tmp_path: Path, ) -> None: # Catches fail-safe discard being blocked because the uncertain live state differs from baseline. project_path = tmp_path / "fixture" / "design.prj" command = _snapshot_command(project_path, "close_without_save") command["expected_fingerprint"] = "0" * 64 run_dir, completed = _run_bridge( tmp_path, action="close_without_save", command=command, initial_part_number="NEW-1", initial_modified=True, ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "close_project|" snapshot = load_snapshot(run_dir / "snapshot.json") assert snapshot.components[1].part_number == "NEW-1" assert snapshot.fingerprint != command["expected_fingerprint"] assert load_status(run_dir / "status.json").state == "project_closed" def test_close_blocks_when_route_returns_without_closing_project(tmp_path: Path) -> None: # Catches trusting a successful API return without observing that the active project disappeared. project_path = tmp_path / "fixture" / "design.prj" command = _snapshot_command(project_path, "close_project") run_dir, completed = _run_bridge( tmp_path, action="close_project", command=command, failure_operation="Application.CloseProjectLeavesOpen", ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "close_project|" status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ("blocked", "project_close_incomplete") def test_manual_close_continuation_uses_preclose_snapshot_after_project_disappears( tmp_path: Path, ) -> None: # Catches manual Close overwriting its evidence status with no route to confirm closure. project_path = tmp_path / "fixture" / "design.prj" command = _snapshot_command(project_path, "close_project") profile = _profile() profile["routes"]["close_project"] = _route_record( "close_project", _ROUTES["close_project"], available=False, ) run_dir, first = _run_bridge( tmp_path, action="close_project", profile=profile, command=command, ) _assert_cscript_ok(first) assert load_status(run_dir / "status.json").state == "manual_action_required" assert load_snapshot(run_dir / "snapshot.json").fingerprint == command["expected_fingerprint"] _, second = _run_bridge( tmp_path, action="close_project", profile=profile, command=command, start_closed=True, reuse=True, ) _assert_cscript_ok(second) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert status.state == "project_closed" assert status.snapshot_path == str((run_dir / "snapshot.json").resolve()) def test_project_navigation_rejects_a_noncanonical_route_name(tmp_path: Path) -> None: # Catches a similarly named navigation route being accepted as profile evidence. current_path = tmp_path / "fixture" / "design.prj" next_path = tmp_path / "next" / "next.prj" next_path.parent.mkdir() next_path.write_text("next fake project\n", encoding="ascii") command = _snapshot_command(next_path, "open_project") profile = _profile() profile["routes"]["close_project"]["route"] = "Application.CloseAnything" run_dir, completed = _run_bridge( tmp_path, action="open_project", profile=profile, command=command, project_path_argument=str(next_path), ) _assert_cscript_ok(completed) assert current_path.exists() assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ( "blocked", "compatibility_profile_invalid", ) assert dict(status.details)["operation"] == "profile.routes.close_project.route" def test_project_open_requires_closed_host_and_publishes_verified_snapshot( tmp_path: Path, ) -> None: # Catches an open result without a complete target-bound snapshot and stale-state check. next_path = tmp_path / "next" / "next.prj" next_path.parent.mkdir() next_path.write_text("next fake project\n", encoding="ascii") command = _snapshot_command(next_path, "open_project") run_dir, completed = _run_bridge( tmp_path, action="open_project", command=command, project_path_argument=str(next_path), start_closed=True, ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == ( f"open_project:{next_path.resolve()}|" ) snapshot = load_snapshot(run_dir / "snapshot.json") assert Path(snapshot.project_path) == next_path.resolve() assert snapshot.fingerprint == command["expected_fingerprint"] status = load_status(run_dir / "status.json") assert status.state == "project_opened" assert status.project_id == _project_id(next_path) assert status.snapshot_path == str((run_dir / "snapshot.json").resolve()) def test_project_open_blocks_before_route_when_a_project_is_already_active( tmp_path: Path, ) -> None: # Catches open implicitly closing or replacing an active project outside the close/backup gate. next_path = tmp_path / "next" / "next.prj" next_path.parent.mkdir() next_path.write_text("next fake project\n", encoding="ascii") command = _snapshot_command(next_path, "open_project") run_dir, completed = _run_bridge( tmp_path, action="open_project", command=command, project_path_argument=str(next_path), ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ("blocked", "project_already_open") def test_manual_open_continuation_verifies_operator_opened_project(tmp_path: Path) -> None: # Catches manual Open status becoming a dead end instead of observing target identity and contents. project_path = tmp_path / "fixture" / "design.prj" command = _snapshot_command(project_path, "open_project") profile = _profile() profile["routes"]["open_project"] = _route_record( "open_project", _ROUTES["open_project"], available=False, ) run_dir, first = _run_bridge( tmp_path, action="open_project", profile=profile, command=command, project_path_argument=str(project_path), start_closed=True, ) _assert_cscript_ok(first) assert load_status(run_dir / "status.json").state == "manual_project_open_required" _, second = _run_bridge( tmp_path, action="open_project", profile=profile, command=command, project_path_argument=str(project_path), reuse=True, ) _assert_cscript_ok(second) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" snapshot = load_snapshot(run_dir / "snapshot.json") assert snapshot.fingerprint == command["expected_fingerprint"] assert load_status(run_dir / "status.json").state == "project_opened" @pytest.mark.parametrize( ("action", "route_call"), (("packager", "packager|"), ("erc", "erc|"), ("netlist", "netlist|")), ) def test_external_check_requires_true_result_and_unchanged_complete_snapshot( tmp_path: Path, action: str, route_call: str, ) -> None: # Catches a check being accepted without exact route success and post-check design evidence. project_path = tmp_path / "fixture" / "design.prj" command = _snapshot_command(project_path, action, part_number="NEW-1") run_dir, completed = _run_bridge( tmp_path, action=action, command=command, initial_part_number="NEW-1", ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == route_call snapshot = load_snapshot(run_dir / "snapshot.json") assert snapshot.fingerprint == command["expected_fingerprint"] status = load_status(run_dir / "status.json") assert status.state == "external_check_passed" assert status.snapshot_path == str((run_dir / "snapshot.json").resolve()) def test_external_check_blocks_when_verified_route_returns_false(tmp_path: Path) -> None: # Catches a non-throwing but explicitly failed native check being treated as success. project_path = tmp_path / "fixture" / "design.prj" command = _snapshot_command(project_path, "packager", part_number="NEW-1") run_dir, completed = _run_bridge( tmp_path, action="packager", command=command, initial_part_number="NEW-1", failure_operation="Application.RunPackagerFailed", ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "packager|" status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ("blocked", "external_check_failed") def test_external_check_blocks_when_erc_changes_the_design(tmp_path: Path) -> None: # Catches a successful diagnostic route legitimizing a modified saved design. project_path = tmp_path / "fixture" / "design.prj" command = _snapshot_command(project_path, "erc", part_number="NEW-1") run_dir, completed = _run_bridge( tmp_path, action="erc", command=command, initial_part_number="NEW-1", failure_operation="Application.RunERCChangesDesign", ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "erc|" status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ( "blocked", "external_check_modified_design", ) def test_external_check_without_live_accepted_route_cannot_be_confirmed_manually( tmp_path: Path, ) -> None: # Catches a human Boolean replacing executable Packager/ERC/netlist evidence. project_path = tmp_path / "fixture" / "design.prj" command = _snapshot_command(project_path, "packager", part_number="NEW-1") profile = _profile() profile["routes"]["packager"] = _route_record( "packager", _ROUTES["packager"], available=False, ) run_dir, completed = _run_bridge( tmp_path, action="packager", profile=profile, command=command, initial_part_number="NEW-1", ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ( "blocked", "external_check_unverified", ) @pytest.mark.parametrize( "action", ("close_project", "close_without_save", "open_project", "packager", "erc", "netlist"), ) def test_snapshot_only_actions_reject_component_selection_fields( tmp_path: Path, action: str, ) -> None: # Catches unrelated component-selection authority leaking into navigation/check commands. project_path = tmp_path / "fixture" / "design.prj" command = _snapshot_command(project_path, action) command.update( { "expected_count": 1, "expected_logical_keys": ["/MAIN|U1"], "old_part_number": "OLD-1", "new_part_number": "NEW-1", } ) run_dir, completed = _run_bridge( tmp_path, action=action, command=command, project_path_argument=str(project_path), start_closed=action == "open_project", ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ("blocked", "invalid_command") @pytest.mark.parametrize( "action", ("close_project", "close_without_save", "open_project", "packager", "erc", "netlist"), ) def test_snapshot_only_actions_require_complete_fingerprint( tmp_path: Path, action: str, ) -> None: # Catches an unbound project state crossing close/open/check trust boundaries. project_path = tmp_path / "fixture" / "design.prj" command = _snapshot_command(project_path, action) command["expected_fingerprint"] = "" run_dir, completed = _run_bridge( tmp_path, action=action, command=command, project_path_argument=str(project_path), start_closed=action == "open_project", ) _assert_cscript_ok(completed) assert (run_dir / "route_calls.txt").read_text(encoding="ascii") == "" status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ("blocked", "invalid_command") @pytest.mark.parametrize( ("action", "operation", "number", "source", "start_closed", "part_number"), ( ( "close_project", "Application.CloseProject", 53007, "FakeApplication.CloseProject", False, "OLD-1", ), ( "open_project", "Application.OpenProject", 53006, "FakeApplication.OpenProject", True, "OLD-1", ), ( "packager", "Application.RunPackager", 53011, "FakeApplication.RunPackager", False, "NEW-1", ), ), ) def test_snapshot_only_actions_preserve_exact_api_error_evidence( tmp_path: Path, action: str, operation: str, number: int, source: str, start_closed: bool, part_number: str, ) -> None: # Catches status publication replacing the first exact navigation/check API error. project_path = tmp_path / "fixture" / "design.prj" command = _snapshot_command(project_path, action, part_number=part_number) run_dir, completed = _run_bridge( tmp_path, action=action, command=command, project_path_argument=str(project_path), failure_operation=operation, initial_part_number=part_number, start_closed=start_closed, ) _assert_cscript_ok(completed) status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ("blocked", "api_error") details = dict(status.details) assert details["error_number"] == str(number) assert details["error_source"] == source @pytest.mark.parametrize( ("operation", "action", "number", "source", "description"), ( ( "Application.DesignComponents", "inventory", 53001, "FakeApplication.DesignComponents", "enumeration unavailable", ), ( "ActiveView.SelectExactSet", "replace_part", 53002, "FakeActiveView.SelectExactSet", "selection unavailable", ), ( "Application.OpenReplacePartDialog", "replace_part", 53003, "FakeApplication.OpenReplacePartDialog", "dialog unavailable", ), ("Application.Undo", "undo", 53004, "FakeApplication.Undo", "undo unavailable"), ("Application.Save", "save", 53005, "FakeApplication.Save", "save unavailable"), ), ) def test_bridge_preserves_exact_api_error_evidence( tmp_path: Path, operation: str, action: str, number: int, source: str, description: str, ) -> None: # Catches a later error scope overwriting number/source/description from the failed API call. project_path = tmp_path / "fixture" / "design.prj" if action == "inventory": command = _command(project_path, action) reuse = False elif action == "replace_part": command = _replace_command(project_path) reuse = False else: run_dir, replace_command, current_fingerprint = _start_applied_operation(tmp_path) command = _control_command(replace_command, action, current_fingerprint) reuse = True run_dir, completed = _run_bridge( tmp_path, action=action, command=command, failure_operation=operation, initial_part_number="NEW-1" if action in {"undo", "save"} else "OLD-1", initial_modified=action in {"undo", "save"}, reuse=reuse, ) _assert_cscript_ok(completed) status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ("blocked", "api_error") details = dict(status.details) assert details["error_number"] == str(number) assert details["error_source"] == source assert details["error_description"] == description def test_collection_access_preserves_the_first_exact_api_error(tmp_path: Path) -> None: # Catches the variant retry overwriting the original collection property failure. run_dir, completed = _run_bridge( tmp_path, action="inventory", failure_operation="Application.DesignComponentsChanging", ) _assert_cscript_ok(completed) status = load_status(run_dir / "status.json") assert (status.state, status.error_code) == ("blocked", "api_error") details = dict(status.details) assert details["error_number"] == "54001" assert details["error_source"] == "FakeApplication.DesignComponents.first" assert details["error_description"] == "first collection access failed" def test_bridge_source_is_ascii_and_contains_no_prohibited_production_route() -> None: # Safety lint only. Functional behavior is covered by the cscript tests above. source = BRIDGE.read_bytes() text = source.decode("ascii") casefolded = text.casefold() assert all(byte <= 0x7F for byte in source) for prohibited in ( "ChangeComponentPreserveRefdes", ".ChangeComponent ", "ViewDraw.Application", "GetObject", "SendKeys", "WScript.Sleep", "AppActivate", "DoEvents", ): assert prohibited.casefold() not in casefolded executable_text = re.sub(r'"(?:[^"]|"")*"', '""', casefolded) assert "ccomp" not in executable_text