From 07a9c1eaafe040b4a6eb657f86678fdda965b041 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: Tue, 3 Nov 2026 11:11:36 +0800 Subject: [PATCH] feat: integrate shared native Add worker behind identity gate --- .../task-5-native-add-report.md | 7 ++ src/cbb_refresh_verify/management.py | 2 + src/cbb_refresh_verify/native_management.py | 98 +++++++++++++++--- tests/test_native_management.py | 99 +++++++++++++++++++ 4 files changed, 193 insertions(+), 13 deletions(-) create mode 100644 .superpowers/sdd/2026-11-02-issue-2-management/task-5-native-add-report.md diff --git a/.superpowers/sdd/2026-11-02-issue-2-management/task-5-native-add-report.md b/.superpowers/sdd/2026-11-02-issue-2-management/task-5-native-add-report.md new file mode 100644 index 0000000..e8a144b --- /dev/null +++ b/.superpowers/sdd/2026-11-02-issue-2-management/task-5-native-add-report.md @@ -0,0 +1,7 @@ +# Task 5: shared native Add route + +The adapter now routes Add on an existing owned library through the same private-desktop UIA executor used by the isolated probe. Worker startup checks the pinned route and staged source identity; the executor retains bounded field readback, exact native success message, child-first close, then closes/reopens the library for strict catalog readback. Exact name/partition absence is a native failure; registered content with different raw engineering identity is native success with `identity_matches=False` and an evidence directory. + +`route_capabilities()['add']` reports binary-pinned route readiness independently of `capabilities()`. Production Add remains disabled with the explicit engineering-identity reason. Update remains disabled and the management engine still composes remove plus Add. Probe CreateLibrary and readd token/fixture guards remain unchanged. No native tools, Mentor processes, or builds were launched in this task. + +Verification: three new boundary tests failed for the missing route method before implementation, then passed. The focused native/management/source/probe-guard/UI suite passed 86 tests. Two additional mocked COM tests passed for close/reopen ordering and strict name/partition versus identity mismatch. Source bytes remained unchanged at the adapter boundary. `git diff --check` passed. Full suite and serialized native validation remain with the coordinator. diff --git a/src/cbb_refresh_verify/management.py b/src/cbb_refresh_verify/management.py index de85280..e5ccee9 100644 --- a/src/cbb_refresh_verify/management.py +++ b/src/cbb_refresh_verify/management.py @@ -51,6 +51,8 @@ class NativeOutcome: success: bool safe_to_continue: bool detail: str + identity_matches: bool | None = None + evidence_path: Path | None = None @dataclass(frozen=True) diff --git a/src/cbb_refresh_verify/native_management.py b/src/cbb_refresh_verify/native_management.py index 5bb908f..017fc5f 100644 --- a/src/cbb_refresh_verify/native_management.py +++ b/src/cbb_refresh_verify/native_management.py @@ -39,7 +39,7 @@ def removal_input(name, partition): def removal_output_ok(code, output, name, partition): return (code == 0 and '# Warning:' not in output and '# Error:' not in output - and re.search(r"# Note: Removed [^\r\n]+ '" + re.escape(name) + and re.search(r"# Note: Removed [^\n]+ '" + re.escape(name) + r"' from partition '" + re.escape(partition) + r"'\.", output) is not None) @@ -63,7 +63,7 @@ class NativeManagementAdapter: self.mapped_drive = drive or '' self.mapped_remote_root = remote_root or '' - def capabilities(self): + def _binary_capability(self): reason = '' for relative, expected in _BINARY_PROOF.items(): path = self.home/relative if self.home else Path(relative) @@ -74,9 +74,22 @@ class NativeManagementAdapter: except OSError as error: reason = f'无法核对原生程序 {path}: {error}' break + return reason + + def route_capabilities(self): + """Report the proven native transport separately from production gates.""" + reason = self._binary_capability() + return { + 'remove': Capability(not reason, reason or 'CleanWGLib/F4 route ready.'), + 'add': Capability(not reason, reason or 'Library Manager Logical-Physical Add route ready.'), + 'update': Capability(False, 'Update remains remove plus Add while identity readback is gated.'), + } + + def capabilities(self): + reason = self._binary_capability() return { 'remove': Capability(not reason, reason or '已验证 CleanWGLib/F4;仅 ASCII 名称、Logical-Physical 和 DxDesigner 库。'), - 'add': Capability(False, '原生新增尚未完成隔离注册及工程内容复读验证;请先运行独立诊断。'), + 'add': Capability(False, '原生新增已调用并注册,但工程身份复读尚未通过;生产新增保持禁用。'), 'update': Capability(False, '同名更新需要原生移除、重新导入及完整端到端隔离验证,目前不可用。'), } @@ -161,7 +174,41 @@ class NativeManagementAdapter: raise ValueError('仅验证了 DxDesigner / Logical-Physical 管理操作。') def add(self, request, evidence): - return NativeOutcome(False, True, self.capabilities()['add'].reason) + evidence = Path(evidence) + validate_name(request.name) + if request.partition != 'Logical-Physical': + return NativeOutcome(False, True, 'Only the verified Logical-Physical native Add route is supported.', + evidence_path=evidence) + source = Path(request.source) if request.source is not None else None + if source is None or not source.is_file(): + return NativeOutcome(False, True, 'Native Add requires an existing staged PRJ source project.', + evidence_path=evidence) + try: + source_identity = engineering_identity(source) + except (ValueError, OSError) as error: + return NativeOutcome(False, True, f'Unable to read source engineering identity: {error}', + evidence_path=evidence) + route = self.route_capabilities()['add'] + if not route.supported: + return NativeOutcome(False, True, route.reason, evidence_path=evidence) + result = self._worker({ + 'operation': 'add', + 'library': str(absolute_preserving_drive(request.library)), + 'source': str(source), + 'name': request.name, + 'partition': request.partition, + 'top_level_block': request.top_level_block, + 'mapped_drive': request.mapped_drive or self.mapped_drive, + 'mapped_remote_root': request.mapped_remote_root or self.mapped_remote_root, + 'timeout_seconds': request.timeout_seconds, + 'source_identity': source_identity, + }, evidence) + identity_matches = result.get('identity_matches') + detail = result.get('detail', '') + if result.get('success') and identity_matches is False and not detail: + detail = 'Native Add registered the block, but engineering identity readback differs from the staged source.' + return NativeOutcome(bool(result.get('success')), bool(result.get('safe_to_continue')), + detail, identity_matches=identity_matches, evidence_path=evidence) def prepare_probe_library(job, root): @@ -292,11 +339,7 @@ def _probe_add_dialog(app, job, desktop, owned_pids, root, *, library=None): def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None): - """Diagnostic only: proven editor/UIA tab and resource1103 controls. - - This function has no production capability override. It is called only - after this worker itself creates a new disposable library. - """ + """Submit the proven Logical-Physical Add dialog on an owned library.""" import pythoncom, win32con, win32gui, win32process _dispatch_diagnostics(root, 'before-pywinauto-import', app, library) from pywinauto import Desktop @@ -345,7 +388,8 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None) raise RuntimeError('原生 New 按钮不可用。') win32gui.PostMessage(new_button, win32con.BM_CLICK, 0, 0) dialog = await_window('New Reusable Block') - fields = {1217: str(source), 1215: job['name'], 1218: top, 1216: 'Isolated CBB management validation'} + fields = {1217: str(source), 1215: job['name'], 1218: top, + 1216: job.get('description', 'CBB native management validation')} for control, value in fields.items(): hwnd = win32gui.GetDlgItem(dialog, control) if not hwnd or win32gui.GetClassName(hwnd) != 'Edit': @@ -538,7 +582,7 @@ def _wait_native_exit(pids, timeout=10): def _catalog_native(job, root): import gc, pythoncom from .com_runtime import initialize_com, uninitialize_com - if job.get('operation') in ('probe_create_add', 'probe_readd'): + if job.get('operation') in ('add', 'probe_create_add', 'probe_readd'): # The installed UIA import disconnects existing Mentor proxies # (CO_E_OBJNOTCONNECTED). Finish its initialization before creating any. from pywinauto import Desktop @@ -614,8 +658,16 @@ def _catalog_com(job, root): raise RuntimeError('目录读取需要升级中心库或选择流程;已拒绝,目标未获准自动升级。') if library is None or Path(str(library.FullName)).resolve() != Path(job['library']).resolve(): raise RuntimeError('原生返回中心库身份不一致。') - if job['operation'] in ('probe_create_add', 'probe_readd'): + if int(library.FlowType) != 1: + raise RuntimeError('Native Add requires the DxDesigner Logical-Physical library flow.') + if job['operation'] in ('add', 'probe_create_add', 'probe_readd'): _probe_add_dialog(app, job, desktop, owned_pids, root, library=library) + library.Close() + library = None + library = app.OpenLibrary(str(absolute_preserving_drive(job['library']))) + if (library is None or Path(str(library.FullName)).resolve() != Path(job['library']).resolve() + or int(library.FlowType) != 1): + raise RuntimeError('Native Add reopen did not confirm the exact library and flow.') entries = [] parts = library.Partitions(7) for i in range(1, int(parts.Count) + 1): @@ -637,6 +689,17 @@ def _catalog_com(job, root): partition = None parts = None result.update(success=True, library=str(library.FullName), flow=int(library.FlowType), entries=entries) + if job['operation'] == 'add': + matches = [entry for entry in entries + if entry['name'] == job['name'] and entry['partition'] == job['partition']] + identity_matches = (len(matches) == 1 + and matches[0]['engineering_identity'] == job.get('source_identity')) + result['identity_matches'] = identity_matches + if len(matches) != 1: + result.update(success=False, detail='Native Add reopen did not confirm the exact name and partition.') + elif not identity_matches: + result['detail'] = ('Native Add registered the block, but engineering identity readback ' + 'differs from the staged source.') except Exception as error: result['detail'] = str(error) result['exception'] = _exception_details(error) @@ -675,7 +738,16 @@ def management_worker_main(request_path): if job.get('mapped_drive') and job.get('mapped_remote_root'): from .network_path import ensure_mapped_drive_visible ensure_mapped_drive_visible(job['mapped_drive'], job['mapped_remote_root']) - if job['operation'] in ('catalog', 'probe_create_add', 'probe_readd'): + if job['operation'] in ('catalog', 'add', 'probe_create_add', 'probe_readd'): + if job['operation'] == 'add': + route = NativeManagementAdapter(mentor_home=job['mentor_home']).route_capabilities()['add'] + if not route.supported: + raise RuntimeError(route.reason) + validate_name(job['name']) + if job.get('partition') != 'Logical-Physical': + raise ValueError('Native Add requires Logical-Physical.') + if engineering_identity(job['source']) != job.get('source_identity'): + raise ValueError('Staged source engineering identity changed before native Add.') result = _catalog_native(job, root) elif job['operation'] == 'remove': adapter = NativeManagementAdapter(mentor_home=job['mentor_home']) diff --git a/tests/test_native_management.py b/tests/test_native_management.py index 0597702..add05ba 100644 --- a/tests/test_native_management.py +++ b/tests/test_native_management.py @@ -13,6 +13,66 @@ def test_installed_binary_mismatch_disables_removal(tmp_path): assert not caps['add'].supported and not caps['update'].supported +def test_add_route_readiness_is_separate_from_conservative_capability_gate(tmp_path, monkeypatch): + import hashlib + import cbb_refresh_verify.native_management as native + proof = {'lm/win32/bin/CleanWGLib.exe': hashlib.sha256(b'verified').hexdigest()} + monkeypatch.setattr(native, '_BINARY_PROOF', proof) + path = tmp_path/next(iter(proof)); path.parent.mkdir(parents=True); path.write_bytes(b'verified') + adapter = native.NativeManagementAdapter(mentor_home=tmp_path) + assert adapter.route_capabilities()['add'].supported + assert not adapter.capabilities()['add'].supported + assert '身份' in adapter.capabilities()['add'].reason + + +def test_native_add_passes_existing_library_and_staged_source_to_worker(tmp_path, monkeypatch): + from cbb_refresh_verify.management import ManagementRequest + import cbb_refresh_verify.native_management as native + source = tmp_path/'source.prj'; source.write_bytes(b'source') + library = tmp_path/'library.lmc'; library.write_bytes(b'library') + seen = {} + adapter = native.NativeManagementAdapter(mentor_home=tmp_path) + monkeypatch.setattr(adapter, 'route_capabilities', lambda: { + 'add': native.Capability(True, 'route ready')}) + monkeypatch.setattr(native, 'engineering_identity', lambda path: {'source': str(path)}) + def worker(job, evidence): + seen.update(job=job, evidence=evidence) + return {'success': True, 'safe_to_continue': True, 'identity_matches': True, + 'detail': 'native add accepted'} + monkeypatch.setattr(adapter, '_worker', worker) + request = ManagementRequest('add', library, 'Block', source=source, + mapped_drive='S:', mapped_remote_root=r'\\server\share', timeout_seconds=23) + result = adapter.add(request, tmp_path/'evidence') + assert result.success and result.safe_to_continue and result.identity_matches is True + assert seen['job'] == { + 'operation': 'add', 'library': str(library), 'source': str(source), + 'name': 'Block', 'partition': 'Logical-Physical', 'top_level_block': '', + 'mapped_drive': 'S:', 'mapped_remote_root': r'\\server\share', + 'timeout_seconds': 23, 'source_identity': {'source': str(source)}, + } + + +def test_native_add_identity_mismatch_is_native_success_with_evidence(tmp_path, monkeypatch): + from cbb_refresh_verify.management import ManagementRequest + import cbb_refresh_verify.native_management as native + source = tmp_path/'source.prj'; source.write_bytes(b'source') + library = tmp_path/'library.lmc'; library.write_bytes(b'library') + adapter = native.NativeManagementAdapter(mentor_home=tmp_path) + monkeypatch.setattr(adapter, 'route_capabilities', lambda: { + 'add': native.Capability(True, 'route ready')}) + monkeypatch.setattr(native, 'engineering_identity', lambda path: {'source': str(path)}) + monkeypatch.setattr(adapter, '_worker', lambda job, evidence: { + 'success': True, 'safe_to_continue': True, 'identity_matches': False, + 'detail': 'engineering identity readback mismatch', + }) + original = source.read_bytes() + result = adapter.add(ManagementRequest('add', library, 'Block', source=source), tmp_path/'evidence') + assert result.success and result.identity_matches is False + assert 'identity' in result.detail + assert result.evidence_path == tmp_path/'evidence' + assert source.read_bytes() == original + + @pytest.mark.parametrize('name', ['A\tB', 'A\nB', '../A', '中文']) def test_delete_record_rejects_ambiguous_encoding_or_injection(name): from cbb_refresh_verify.native_management import removal_input @@ -176,3 +236,42 @@ def test_com_failure_without_owner_identity_cannot_claim_release(tmp_path, monke monkeypatch.setattr(native, '_catalog_com', lambda *a: {'success': False, 'safe_to_continue': False, 'native_pids': [], 'detail': 'COM startup ambiguous'}) assert native._catalog_native({}, tmp_path)['safe_to_continue'] is False + + +@pytest.mark.parametrize('registered', [True, False]) +def test_shared_add_reopens_exact_catalog_and_reports_identity_mismatch(tmp_path, monkeypatch, registered): + import cbb_refresh_verify.native_management as native + import cbb_refresh_verify.mentor_adapter as mentor + import win32com.client + library_path = tmp_path/'lib.lmc'; library_path.touch() + events = [] + class Collection: + def __init__(self, items): self.items = items; self.Count = len(items) + def Item(self, index): return self.items[index - 1] + class Library: + FullName = str(library_path) + FlowType = 1 + def Partitions(self, kind): + events.append('catalog') + return Collection([Collection([SimpleNamespace(Name='Block', PartitionName='Logical-Physical')] + if registered else [])]) + def Close(self): events.append('close') + state = {'running': False} + class App: + def OpenLibrary(self, path): + assert path == str(library_path) + events.append('open') + return Library() + def Quit(self): state['running'] = False + def dispatch(_): state['running'] = True; return App() + monkeypatch.setattr(win32com.client, 'DispatchEx', dispatch) + monkeypatch.setattr(native, '_current_desktop', lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test')) + monkeypatch.setattr(mentor, '_process_details', lambda _: [(123, str(tmp_path/'lm/win32/bin/LibraryManager.exe'), '', 0)] if state['running'] else []) + monkeypatch.setattr(native, '_probe_add_dialog', lambda *a, **k: events.append('add')) + result = native._catalog_com({'operation': 'add', 'library': str(library_path), + 'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path), + 'name': 'Block', 'partition': 'Logical-Physical', 'source_identity': {'expected': 'bytes'}}, tmp_path) + assert events == ['open', 'add', 'close', 'open', 'catalog', 'close'] + assert result['success'] is registered + assert result['identity_matches'] is False + assert ('engineering identity' if registered else 'exact name and partition') in result['detail']