From 2f6060dfe33f75991912d0fbbb41235c181dcee7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Mon, 19 Oct 2026 10:54:25 +0800 Subject: [PATCH] feat(native): add correlated read-only snapshot adapter --- .../2026-10-19-native-readonly-snapshot.md | 65 ++++++ .../2026-10-19-native-readonly-snapshot.md | 19 ++ .../dxdesigner795/NativeSnapshotReader.vbs | 190 ++++++++++++++++++ tests/v1_1/test_native_snapshot_reader.py | 166 +++++++++++++++ 4 files changed, 440 insertions(+) create mode 100644 docs/superpowers/plans/2026-10-19-native-readonly-snapshot.md create mode 100644 docs/superpowers/specs/2026-10-19-native-readonly-snapshot.md create mode 100644 integration/dxdesigner795/NativeSnapshotReader.vbs create mode 100644 tests/v1_1/test_native_snapshot_reader.py diff --git a/docs/superpowers/plans/2026-10-19-native-readonly-snapshot.md b/docs/superpowers/plans/2026-10-19-native-readonly-snapshot.md new file mode 100644 index 0000000..fa5d4fb --- /dev/null +++ b/docs/superpowers/plans/2026-10-19-native-readonly-snapshot.md @@ -0,0 +1,65 @@ +# Native Readonly Snapshot Implementation Plan + +> **For agentic workers:** Execute this plan inline with existing user authorization; use independent requesting-code-review for the final boundaries. Steps use checkbox syntax for tracking. + +**Goal:** Speed up complete unselected-state acquisition without removing any save/reopen verification. + +**Architecture:** A separate VBScript adapter builds a native-host script from the existing read-only production routines. Python combines the adapter with the main worker at preparation time. Correlated, complete U/G frames are checked before capture or verification consumes them. + +**Tech Stack:** Python 3.12, VBScript, installed DxDesigner 7.9.5 script host, existing private desktop supervisor. + +**Spec:** ../specs/2026-10-19-native-readonly-snapshot.md + +## Global Constraints + +- Only owned private-desktop batches use the adapter; manual/legacy paths retain external COM. +- Keep original full fields, live pin owners, context checks, save/reopen and recovery boundaries. +- Native error or incomplete proof fails closed after dispatch; no CAD writes from the reader. +- Do not package/release, modify feedback/, or run real CAD on source projects. + +## Task 1: Correlated read frame and native script adapter + +Files: create integration/dxdesigner795/NativeSnapshotReader.vbs and tests/v1_1/test_native_snapshot_reader.py. + +Interfaces: + +- QPNativeReadUntouched(SelectedUids): dictionary with total, text, and rows keyed by unselected UID. +- QPParseNativeSnapshot(Text, Token, Project, Sheet, SelectedUids): validates NR1/header, U/G pairs, END/token/count and exact pair identity; returns the dictionary above. +- QPNativeCollect(SelectedUids, Token, Project, Sheet, Guid): freshly queries the owned view and produces the complete frame with existing QPUntouchedComponent. +- QPBuildNativeSnapshotScript(SelectedUids, Token, Project, Sheet, Guid, ResultPath): emits native bootstrap plus an explicit whitelist of original read-only routines; native QPProgress checks cancellation only. + +- [ ] Write literal frame tests: one zero-pin unselected component, one selected UID, total=2; expected rows["u2"] equals its original U/G pair. + +```python +assert parsed_total == 2 +assert parsed_uids == ['u2'] +``` + +- [ ] Run tests and observe missing adapter failure. Add negative fixtures for stale token, wrong context, truncation, duplicate UID, wrong G owner, inconsistent U/G, extra selected UID, malformed count and propagated error frame. +- [ ] Implement strict parsing and script generation; collect with the same read functions and no selection/save operations. Exercise generated code using COM-shaped fakes, including cancellation and missing targets. +- [ ] Run the adapter tests and commit after they pass. + +## Task 2: Runtime composition and capture/verification integration + +Files: modify src/dx_productivity/trial_task_center/quick_run.py, integration/dxdesigner795/QuickPartReplace.vbs, packaging/DxPartReplace.spec and focused runtime tests. + +Interfaces: + +- _copy_worker_script(source: Path, destination: Path): copy source and append its sibling NativeSnapshotReader.vbs when present; preserve custom script compatibility. +- QPUseNativeSnapshot(): true only for owned batches with a private-desktop environment and an available adapter function. +- QPVerifyNativeUntouched(Records): compare complete actual rows, total and unselected UID set to existing persisted baselines. + +- [ ] Reproduce a prepared default worker missing the adapter and a custom worker that must remain unchanged. +- [ ] Compose all three existing source-copy callsites through _copy_worker_script; include the adapter in the frozen resource specification without building. +- [ ] Route capture and QPVerifyUntouched through native reads only behind QPUseNativeSnapshot. Retain original external loops for other modes and all invalidation calls. +- [ ] Run focused runtime, VBS, execution/recovery and existing accuracy tests. Review any failures before continuing; commit tested integration. + +## Task 3: Independent review and real BOM acceptance + +Files: add docs/reviews/2026-10-19-native-snapshot.md and sanitized docs/testing/evidence/2026-10-19-native-snapshot.json. + +- [ ] Request an independent read-only review of ownership gating, native function whitelist, nonce/context checks, failure propagation and exact full-baseline comparison. +- [ ] Run the established default-template BOM harness on a fresh build/ copy with RV05 and RV14, recording script hashes and timings. +- [ ] Compare initial snapshots with the 120-row previous baseline; independently export hier/flat and verify 55 untouched components, 103 pin connections and 22 nets, plus exact target changes. +- [ ] Exercise read-only recovery on the disposable successful queue because it also calls full verification; confirm no additional replacement/save and safe release. +- [ ] Record failed research probes and remaining release gaps honestly, update plan checkboxes, commit evidence and push. Verify remote HEAD equals local and only feedback/ remains untracked. diff --git a/docs/superpowers/specs/2026-10-19-native-readonly-snapshot.md b/docs/superpowers/specs/2026-10-19-native-readonly-snapshot.md new file mode 100644 index 0000000..5376deb --- /dev/null +++ b/docs/superpowers/specs/2026-10-19-native-readonly-snapshot.md @@ -0,0 +1,19 @@ +# 原生宿主只读完整快照 + +目标是在自有私有桌面的正式批次中,把完整未选中器件快照交给 CAD 自带 VBS 宿主执行,消除逐字段跨进程 COM 开销。替换窗口、恢复写入、逐项保存和磁盘重开协议保持原样。 + +只读探针已取得两轮证据:57 个器件的 114 行 U/G 完整快照与外部采集一致;连续运行也一致。批量属性接口因空格/空串差异及缺失样式字段不接入。 + +约束: + +- 仅在已确认拥有工程的私有桌面批次启用。手动模式、旧运行时或缺少适配模块时使用原采集路径。 +- 单独维护 NativeSnapshotReader.vbs;准备运行时时与主脚本合成一个可执行文件,不复制完整快照实现。原生脚本从该文件提取限定的只读函数。 +- 每次调用使用独立令牌、结果路径和 CAD GUID;核对工程与图页,重新建立引脚索引,保留逐引脚归属、全部属性/样式/连接读取和上下文检查。 +- 结果有版本头、令牌、工程、图页和完整结束标记。拒绝旧令牌、截断、重复 UID、U/G 不一致、未选中集合变化、丢失目标和错误总数。 +- 目标 UID 只用于排除未选中集合;原生读前后核对目标集合存在。保存前及磁盘重开后均重新执行完整读取。 +- 原生错误、命令失败、缺失结果、取消均不得生成成功证明;命令已发出后不静默回退。原生读取不写 CAD、不改选择、不保存。 +- 原生宿主预定义 Vd 枚举,不重复声明;支持同一 CAD 会话连续调用。 +- 取消检查使用当前监控令牌,在原有可安全中止的边界响应;外层监控和自有进程释放仍保留。 +- 不打包发布;不触碰 feedback/,实机只用 build/ 下新副本。 + +验收使用默认 BOM 的两条正式替换,覆盖错误行拒绝、导入确认、每项保存重开、独立库存及完整层级/扁平导出、原始工程哈希与桌面释放。性能只报告实际测得的同源样例,不承诺普遍倍数。 diff --git a/integration/dxdesigner795/NativeSnapshotReader.vbs b/integration/dxdesigner795/NativeSnapshotReader.vbs new file mode 100644 index 0000000..ffb9754 --- /dev/null +++ b/integration/dxdesigner795/NativeSnapshotReader.vbs @@ -0,0 +1,190 @@ +' Read-only native-host adapter. Appended to the external worker at preparation. + +Function QPNativeReadUntouched(ByRef SelectedUids) + Dim Token, Base, ScriptPath, ResultPath, Stream, CommandPath, Text + Dim Project, Sheet, Guid, Safe, Result + Set QPNativeReadUntouched = Nothing + Project = QPProjectPath() + Sheet = QPSheetIdentity() + Guid = CStr(QP_App.Guid()) + Token = CStr(QP_AttemptToken) & "-" & CStr(QP_ProgressSequence) & "-" & QP_Fso.GetTempName() + Base = QP_Fso.BuildPath(QP_Root, "native-read-" & Token) + ScriptPath = Base & ".vbs" + ResultPath = Base & ".tsv" + Safe = Not CBool(QP_NativeMutationPossible) And Not CBool(QP_RestoreTransactionOpen) And Not CBool(QP_NativeCallActive) + Text = QPBuildNativeSnapshotScript(QPReadUtf8(WScript.ScriptFullName), SelectedUids, _ + Token, Project, Sheet, Guid, ResultPath, CStr(QP_AttemptToken), Safe) + ' Generated source is ASCII; Unicode values are escaped with QPEncode. + Set Stream = QP_Fso.CreateTextFile(ScriptPath, False, False) + Stream.Write Text + Stream.Close + CommandPath = QP_Fso.GetFile(ScriptPath).ShortPath + If Not QPNativeCommandPathSupported(CommandPath) Then + QPLog QP_Root, "INFO", "native_read_path_unavailable; using external full read" + Exit Function + End If + QPProgress "native_snapshot_read", 0, 0 + If Not QP_App.ExecuteCommand("run " & CommandPath) Then _ + Err.Raise vbObjectError + 875, "QuickPartReplace.NativeRead", "native script command failed" + If Not QP_Fso.FileExists(ResultPath) Then _ + Err.Raise vbObjectError + 875, "QuickPartReplace.NativeRead", "native script returned no complete result" + Set Result = QPParseNativeSnapshot(QPReadUtf8(ResultPath), Token, Project, Sheet, SelectedUids) + If CStr(QP_App.Guid()) <> Guid Or QPProjectPath() <> Project Or QPSheetIdentity() <> Sheet Then _ + Err.Raise vbObjectError + 875, "QuickPartReplace.NativeRead", "context changed after native read" + QPProgress "native_snapshot_read", Result("total"), Result("total") + QPLog QP_Root, "INFO", "native_snapshot_verified components=" & CStr(Result("total")) & " token=" & Token + Set QPNativeReadUntouched = Result +End Function + +Function QPNativeCommandPathSupported(ByVal Path) + Dim Index, Code + QPNativeCommandPathSupported = False + For Index = 1 To Len(Path) + Code = AscW(Mid(Path, Index, 1)) + If Code <= 32 Or Code > 126 Or Code = 34 Then Exit Function + Next + QPNativeCommandPathSupported = (Len(Path) > 0) +End Function + +Function QPParseNativeSnapshot(ByVal Text, ByVal Token, ByVal Project, ByVal Sheet, ByRef SelectedUids) + Dim Lines, Fields, Last, Index, Uid, Identity, State, Pair, Rows, Result, Total + Set Rows = CreateObject("Scripting.Dictionary") + Lines = Split(Text, vbCrLf) + Last = UBound(Lines) + If Last > 0 Then + If Lines(Last) = "" Then Last = Last - 1 + End If + Fields = Split(Lines(0), vbTab) + If Fields(0) = "ERROR" Then + If UBound(Fields) <> 4 Then QPNativeReadInvalid "malformed error frame" + If Fields(1) <> Token Then QPNativeReadInvalid "stale error token" + Err.Raise CLng(Fields(2)), QPDecode(Fields(3)), QPDecode(Fields(4)) + End If + If UBound(Fields) <> 3 Then QPNativeReadInvalid "missing native header" + If Fields(0) <> "NR1" Or Fields(1) <> Token Or QPDecode(Fields(2)) <> Project Or _ + QPDecode(Fields(3)) <> Sheet Then QPNativeReadInvalid "native header context mismatch" + If Last < 1 Then QPNativeReadInvalid "truncated native result" + Fields = Split(Lines(Last), vbTab) + If UBound(Fields) <> 2 Then QPNativeReadInvalid "missing completion frame" + If Fields(0) <> "END" Or Fields(1) <> Token Then QPNativeReadInvalid "missing completion token" + If Len(Fields(2)) = 0 Then QPNativeReadInvalid "invalid component count" + For Index = 1 To Len(Fields(2)) + If InStr(1, "0123456789", Mid(Fields(2), Index, 1), vbBinaryCompare) = 0 Then _ + QPNativeReadInvalid "invalid component count" + Next + Total = CLng(Fields(2)) + Index = 1 + Do While Index < Last + If Index + 1 >= Last Then QPNativeReadInvalid "incomplete U/G pair" + Fields = Split(Lines(Index), vbTab) + If UBound(Fields) <> 6 Then QPNativeReadInvalid "malformed identity row" + If Fields(0) <> "U" Then QPNativeReadInvalid "unexpected native row" + Uid = QPDecode(Fields(1)) + If Len(Uid) = 0 Then QPNativeReadInvalid "empty component UID" + If SelectedUids.Exists(Uid) Or Rows.Exists(Uid) Then QPNativeReadInvalid "duplicate or selected UID in unselected result" + Identity = Lines(Index) + Fields = Split(Lines(Index + 1), vbTab) + If UBound(Fields) <> 2 Then QPNativeReadInvalid "malformed full-state row" + If Fields(0) <> "G" Or QPDecode(Fields(1)) <> Uid Then QPNativeReadInvalid "full-state owner mismatch" + State = QPDecode(Fields(2)) + If Len(State) = 0 Or QPUntouchedIdentity(State) <> Identity Then QPNativeReadInvalid "full-state identity mismatch" + Pair = Identity & vbCrLf & Lines(Index + 1) & vbCrLf + Rows.Add Uid, Pair + Index = Index + 2 + Loop + If Rows.Count + SelectedUids.Count <> Total Then QPNativeReadInvalid "component total mismatch" + Set Result = CreateObject("Scripting.Dictionary") + Result.Add "total", Total + Result.Add "rows", Rows + Text = "" + For Each Uid In Rows.Keys + Text = Text & Rows(Uid) + Next + Result.Add "text", Text + Set QPParseNativeSnapshot = Result +End Function + +Sub QPNativeReadInvalid(ByVal Description) + Err.Raise vbObjectError + 875, "QuickPartReplace.NativeRead", Description +End Sub + +Function QPNativeCollect(ByRef SelectedUids, ByVal Token, ByVal Project, ByVal Sheet, ByVal Guid) + Dim Components, Comp, Uid, Seen, Found, Text, Count + QPNativeRequireContext Project, Sheet, Guid + QPInvalidatePinIndex + Set Components = QP_App.ActiveView.Query(VDM_COMP, VD_ALL) + Set Seen = CreateObject("Scripting.Dictionary") + Set Found = CreateObject("Scripting.Dictionary") + Text = "NR1" & vbTab & Token & vbTab & QPEncode(Project) & vbTab & QPEncode(Sheet) & vbCrLf + Count = 0 + QPProgress "native_snapshot_read", 0, Components.Count + For Each Comp In Components + Uid = CStr(Comp.UID) + If Len(Uid) = 0 Or Seen.Exists(Uid) Then QPNativeReadInvalid "duplicate or empty component UID" + Seen.Add Uid, True + If SelectedUids.Exists(Uid) Then + Found.Add Uid, True + Else + Text = Text & QPUntouchedComponent(Comp) + End If + Count = Count + 1 + QPProgress "native_snapshot_read", Count, Components.Count + Next + If Found.Count <> SelectedUids.Count Then QPNativeReadInvalid "selected component missing from native read" + QPNativeRequireContext Project, Sheet, Guid + QPNativeCollect = Text & "END" & vbTab & Token & vbTab & CStr(Count) & vbCrLf +End Function + +Sub QPNativeRequireContext(ByVal Project, ByVal Sheet, ByVal Guid) + If CStr(QP_App.Guid()) <> Guid Then QPNativeReadInvalid "foreign CAD GUID" + If QPProjectPath() <> Project Or QPSheetIdentity() <> Sheet Then QPNativeReadInvalid "native CAD context mismatch" +End Sub + +Function QPBuildNativeSnapshotScript(ByVal Source, ByRef SelectedUids, ByVal Token, ByVal Project, ByVal Sheet, ByVal Guid, ByVal ResultPath, ByVal StopToken, ByVal Safe) + Dim Header, Body, Names, Name, Uid, Pattern, Matches + Header = Left(Source, InStr(Source, "Set QP_Fso =") - 1) + Set Pattern = CreateObject("VBScript.RegExp") + Pattern.Global = True + Pattern.MultiLine = True + Pattern.Pattern = "^Const (VDM_COMP|VDM_COMPPIN|VD_ALL) = [^\r\n]*\r?\n" + Header = Pattern.Replace(Header, "") + Body = Header & vbCrLf & "Dim QP_NR_Selected, QP_NR_Text, QP_NR_Code, QP_NR_Source, QP_NR_Description, QP_NR_Safe" & vbCrLf & _ + "Set QP_Fso=CreateObject(""Scripting.FileSystemObject"")" & vbCrLf & _ + "QP_Root=" & QPNativeExpression(QP_Root) & vbCrLf & _ + "QP_AttemptToken=" & QPNativeExpression(StopToken) & vbCrLf & _ + "QP_NR_Safe=" & CStr(CBool(Safe)) & vbCrLf & _ + "Set QP_NR_Selected=CreateObject(""Scripting.Dictionary"")" & vbCrLf + For Each Uid In SelectedUids.Keys + Body = Body & "QP_NR_Selected.Add " & QPNativeExpression(Uid) & ",True" & vbCrLf + Next + Body = Body & "On Error Resume Next" & vbCrLf & _ + "Set QP_App=GetObject(,""Viewdraw.Application"")" & vbCrLf & _ + "If Err.Number=0 Then QP_NR_Text=QPNativeCollect(QP_NR_Selected," & _ + QPNativeExpression(Token) & "," & QPNativeExpression(Project) & "," & QPNativeExpression(Sheet) & "," & QPNativeExpression(Guid) & ")" & vbCrLf & _ + "QP_NR_Code=Err.Number: QP_NR_Source=Err.Source: QP_NR_Description=Err.Description" & vbCrLf & _ + "Err.Clear" & vbCrLf & _ + "If QP_NR_Code<>0 Then QP_NR_Text=""ERROR"" & vbTab & " & QPNativeExpression(Token) & _ + " & vbTab & CStr(QP_NR_Code) & vbTab & QPEncode(QP_NR_Source) & vbTab & QPEncode(QP_NR_Description) & vbCrLf" & vbCrLf & _ + "QPWriteUtf8 " & QPNativeExpression(ResultPath) & ",QP_NR_Text" & vbCrLf & "On Error GoTo 0" & vbCrLf + Names = Split("QPNativeCollect QPNativeRequireContext QPNativeReadInvalid QPUntouchedComponent QPUntouchedFullState QPUntouchedIdentity QPComponentPins QPInvalidatePinIndex QPConnectionSignatureFromPins QPAddSortedSignature QPSnapshotAttribute QPOptionalAttributeField QPSortSnapshotLines QPEncode QPDecode QPProjectPath QPSheetIdentity QPCanonicalPath QPEnsureProjectAccess QPReadUtf8 QPWriteUtf8", " ") + Pattern.Global = False + For Each Name In Names + Pattern.Pattern = "^(Function|Sub) " & Name & "\([^\n]*\n[\s\S]*?^End \1[ \t]*" + Set Matches = Pattern.Execute(Source) + If Matches.Count <> 1 Then QPNativeReadInvalid "missing native read routine: " & Name + Body = Body & vbCrLf & Matches(0).Value & vbCrLf + Next + Body = Body & vbCrLf & "Sub QPLog(ByVal Root,ByVal Level,ByVal Message)" & vbCrLf & "End Sub" & vbCrLf & _ + "Sub QPProgress(ByVal Stage,ByVal Done,ByVal Total)" & vbCrLf & _ + " Dim StopPath" & vbCrLf & _ + " If QP_NR_Safe And Len(QP_AttemptToken)>0 Then" & vbCrLf & _ + " StopPath=QP_Fso.BuildPath(QP_Root,""monitor-"" & QP_AttemptToken & "".stop"")" & vbCrLf & _ + " If QP_Fso.FileExists(StopPath) Then" & vbCrLf & _ + " If Trim(QPReadUtf8(StopPath))=QP_AttemptToken Then Err.Raise vbObjectError+860,""QuickPartReplace.SafeStop"",""native read stopped at safe boundary""" & vbCrLf & _ + " End If" & vbCrLf & " End If" & vbCrLf & "End Sub" & vbCrLf + QPBuildNativeSnapshotScript = Body +End Function + +Function QPNativeExpression(ByVal Value) + QPNativeExpression = "QPDecode(" & Chr(34) & Replace(QPEncode(Value), Chr(34), Chr(34) & Chr(34)) & Chr(34) & ")" +End Function diff --git a/tests/v1_1/test_native_snapshot_reader.py b/tests/v1_1/test_native_snapshot_reader.py new file mode 100644 index 0000000..013b6fc --- /dev/null +++ b/tests/v1_1/test_native_snapshot_reader.py @@ -0,0 +1,166 @@ +"""Correlated full-read frames and execution of the generated read-only script.""" +from pathlib import Path +import re +import subprocess + +import pytest + +import test_accuracy_vbs_guards as guards + + +ROOT = Path(__file__).resolve().parents[2] +MAIN = ROOT / 'integration/dxdesigner795/QuickPartReplace.vbs' +ADAPTER = MAIN.with_name('NativeSnapshotReader.vbs') +PAIR = ('U\tu2\tR2\t\t\t\t\r\n' + 'G\tu2\tC%0009u2%0009R2%00090%00090%00090%00091%0009NO_PINS%000D%000A\r\n') +FRAME = 'NR1\tnonce\tc:\\board.prj\tMAIN:1\r\n' + PAIR + 'END\tnonce\t2\r\n' + + +def quote(value): + return '"' + str(value).replace('"', '""') + '"' + + +def run(tmp_path, body, *, prelude=''): + assert ADAPTER.is_file(), 'native snapshot adapter is missing' + source = ADAPTER.read_text(encoding='ascii') + common = '\n'.join(guards.routine(n) for n in ('QPEncode', 'QPDecode', 'QPUntouchedIdentity', 'QPReadUtf8', 'QPWriteUtf8')) + script = tmp_path / 'native-reader-test.vbs' + script.write_text(prelude + '\n' + common + '\n' + source + '\n' + body, encoding='ascii') + result = subprocess.run(['cscript.exe', '//nologo', str(script)], capture_output=True, text=True, timeout=15) + assert result.returncode == 0, result.stdout + result.stderr + return result.stdout.strip() + + +@pytest.mark.parametrize('mutation', [ + '', 'token', 'project', 'sheet', 'truncated', 'duplicate', 'wrong_g_uid', + 'identity', 'count', 'selected', 'error', 'extra_after_end', 'no_header', +]) +def test_native_snapshot_frame_requires_exact_complete_proof(tmp_path, mutation): + text = FRAME + if mutation == 'token': + text = text.replace('NR1\tnonce', 'NR1\told') + elif mutation == 'project': + text = text.replace('c:\\board.prj', 'c:\\other.prj') + elif mutation == 'sheet': + text = text.replace('MAIN:1', 'MAIN:2') + elif mutation == 'truncated': + text = text[:text.index('END\t')] + elif mutation == 'duplicate': + text = text.replace('END\t', PAIR + 'END\t') + elif mutation == 'wrong_g_uid': + text = text.replace('G\tu2\t', 'G\tother\t') + elif mutation == 'identity': + text = text.replace('U\tu2\tR2', 'U\tu2\tR99') + elif mutation == 'count': + text = text.replace('END\tnonce\t2', 'END\tnonce\t3') + elif mutation == 'selected': + text = text.replace('u2', 'u1') + elif mutation == 'error': + text = 'ERROR\tnonce\t1234\tFakeCOM\tread denied\r\n' + elif mutation == 'extra_after_end': + text += PAIR + elif mutation == 'no_header': + text = text[text.index('U\t'):] + path = tmp_path / 'frame.tsv' + path.write_bytes(text.encode('ascii')) + output = run(tmp_path, ''' +Dim Selected, Result, Failure +Set Selected=CreateObject("Scripting.Dictionary"): Selected.Add "u1",True +On Error Resume Next +Set Result=QPParseNativeSnapshot(QPReadUtf8(''' + quote(path) + '''),"nonce","c:\\board.prj","MAIN:1",Selected) +Failure=Err.Number +Err.Clear +On Error GoTo 0 +WScript.Echo CStr(Failure<>0) +If Failure=0 Then + WScript.Echo Result("total") + WScript.Echo Join(Result("rows").Keys,",") +ElseIf Failure=1234 Then + WScript.Echo "read error propagated" +End If +''') + expected = ['False', '2', 'u2'] if not mutation else ['True'] + if mutation == 'error': + expected.append('read error propagated') + assert output.splitlines() == expected + + +NATIVE_FAKES = guards.FULL_FAKE[guards.FULL_FAKE.index('Class FakePoint'):guards.FULL_FAKE.index('Function QPProjectPath()')] + ''' +Class OwnedNativeApp + Public ActiveView + Private Sub Class_Initialize() + Set ActiveView=New OwnedNativeView + End Sub + Function Guid() + Guid="OWNED" + End Function + Function GetProjectData() + Set GetProjectData=Me + End Function + Function GetProjectFilePath() + GetProjectFilePath="C:\\board.prj" + End Function +End Class +Class OwnedNativeView + Public Components, Pins + Private Sub Class_Initialize() + Set Components=CreateObject("Scripting.Dictionary") + Set Pins=CreateObject("Scripting.Dictionary") + End Sub + Function Query(ByVal Kind,ByVal Scope) + If Kind=128 Then Set Query=Components Else Set Query=Pins + End Function + Function GetName(ByVal Flags) + GetName="MAIN" + End Function + Public Property Get Block + Set Block=Me + End Property + Public Property Get SheetNum + SheetNum="1" + End Property +End Class +Function MakeNativeFake() + Dim App,Comp + Set App=New OwnedNativeApp + Set Comp=New FullComponent: Comp.UID="u1": Comp.Refdes="R1" + App.ActiveView.Components.Add Comp,True + Set Comp=New FullComponent: Comp.UID="u2": Comp.Refdes="R2" + App.ActiveView.Components.Add Comp,True + Set MakeNativeFake=App +End Function +''' + + +@pytest.mark.parametrize('fault', ['', 'foreign_guid', 'cancel', 'missing_target']) +def test_generated_native_script_collects_complete_readonly_frame(tmp_path, fault): + source = tmp_path / 'combined.vbs' + assert ADAPTER.is_file(), 'native snapshot adapter is missing' + source.write_text(MAIN.read_text(encoding='ascii') + '\n' + ADAPTER.read_text(encoding='ascii'), encoding='ascii') + generated, result = tmp_path/'generated.vbs', tmp_path/'result.tsv' + selected = 'missing' if fault == 'missing_target' else 'u1' + guid = 'FOREIGN' if fault == 'foreign_guid' else 'OWNED' + if fault == 'cancel': + (tmp_path/'monitor-stop-token.stop').write_text('stop-token', encoding='ascii') + run(tmp_path, ''' +Dim QP_Root,Selected,Text +QP_Root=''' + quote(tmp_path) + ''' +Set Selected=CreateObject("Scripting.Dictionary"): Selected.Add "''' + selected + '''",True +Text=QPBuildNativeSnapshotScript(QPReadUtf8(''' + quote(source) + '''),Selected,"nonce","c:\\board.prj","MAIN:1","''' + guid + '''",''' + quote(result) + ''',"stop-token",True) +QPWriteUtf8 ''' + quote(generated) + ''',Text +''') + text = generated.read_text(encoding='utf-8-sig') + text = text.replace('Set QP_App=GetObject(,"Viewdraw.Application")', 'Set QP_App=MakeNativeFake()') + # Supply the enum constants provided by the real CAD script host. + text += '\nConst VDM_COMP=128\nConst VDM_COMPPIN=4096\nConst VD_ALL=0\n' + NATIVE_FAKES + generated.write_text(text, encoding='ascii') + completed = subprocess.run(['cscript.exe', '//nologo', str(generated)], capture_output=True, text=True, timeout=15) + assert completed.returncode == 0, completed.stdout + completed.stderr + actual = result.read_bytes().decode('utf-8-sig') + if fault: + assert actual.startswith('ERROR\tnonce\t') + assert 'END\t' not in actual + if fault == 'cancel': + assert 'QuickPartReplace.SafeStop' in actual + else: + assert actual == FRAME