feat: bind native CRUD to prepared engine identity transactions

This commit is contained in:
阿白叔 committed 2026-11-03 11:54:56 +08:00
1 parent 89500cbb5f
commit 55a82fdc5f
8 files changed
+492 -13

No files matched your search

+6
View File
@@ -11,3 +11,9 @@ Verification is mocked/file-only: the original focused suite passed 86 tests plu
The follow-up focused suite passed 99 tests. After restoring ordinary catalog queries for non-DxDesigner flow readback, the native boundary/field subset passed 47 tests (including four additional flow cases). `git diff --check` passed. The original ignored scratch report remains on disk but is removed from version control.
A second review found ownership lifetime and reverse containment gaps. The fixture route now nests the already-proven caller lease around worker dispatch and retains that same exclusive handle/checkpoint on unsafe return or exception, including callers that supply no release callback. It also rejects a fixture nested anywhere inside the original source tree before staging. Three new failure cases were observed before the fix; the final native-boundary/field subset passed 51 tests, including normal release and uploader-handle denial after uncertain release. No native processes were launched.
The subsequent `mentor795-native-content-v1` contract requires pinned native hierarchy/flat ASCII, CSV/property tables and schematic EDIF exports on disposable copies, plus exact raw physical/primary assets. Only the three observed ASCII metadata headers, CSV `System_Date` field and root EDIF `status/written/timestamp` node are normalized. All project library references must resolve to an approved library before their values can be normalized. Unknown primary files, layout data, drawing coordinates, properties and EDIF userData remain part of the comparison. Unsupported exports fail closed; this is not a claim of arbitrary unexported CES equivalence.
The real management engine now captures a source baseline before any removal. Native Add requires a prepared transaction binding the verified full backup, staged source, baseline proof, exact target/name/partition, supervisor and exclusive lease. After normal native release, it corrects imported PRJ/PCB library references using the existing documented text helpers, reopens the exact native catalog and compares a target-only identity. Update remains remove plus Add; failures retain the recovery snapshot and checkpoint. The UI action is explicitly labeled “用工程替换已选 CBB…(原生重新导入)”; backup Work restoration is unchanged.
Coordinator-native source/registered capture matched all three exports and primary assets after correcting the observed imported PCB reference; original source manifests were unchanged. Implementation verification remains file-only: 114 focused tests passed before the final bootstrap/lease refinement. `create_owned_fixture` and `run_owned_fixture_management` provide a token-bound empty-library/real-engine route for the coordinator's actual CRUD cycle. Production Add/Update remain disabled until that separate acceptance and promotion step.
+14 -1
View File
@@ -29,6 +29,7 @@ class ManagementRequest:
timeout_seconds: float = 180
mapped_drive: str = ''
mapped_remote_root: str = ''
transaction_token: str = ''
@dataclass(frozen=True)
@@ -53,6 +54,7 @@ class NativeOutcome:
detail: str
identity_matches: bool | None = None
evidence_path: Path | None = None
identity_proof: dict | None = None
@dataclass(frozen=True)
@@ -268,6 +270,14 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
identity = engineering_identity(staged.source)
if build_manifest(source.parent) != source_manifest:
raise OSError('来源工程在暂存期间变化。')
if source and hasattr(adapter, 'prepare_add_transaction'):
checkpoint('prepare_identity')
owner_safe = False
staged, proof = adapter.prepare_add_transaction(staged, root, original_source=source)
owner_safe = proof.safe_to_continue
if not owner_safe or proof.identity is None:
return finish('UPLOAD_FAILED', proof.detail, owner_safe)
identity = proof.identity
if build_manifest(library_root, scope=scope) != original:
raise OSError('备份后中心库内容变化,停止写入。')
if request.operation in ('remove', 'update'):
@@ -302,8 +312,11 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
owner_safe = after.safe_to_continue
matches = [entry for entry in after.entries if entry.name == request.name
and entry.partition == request.partition]
proof_matches = (native.identity_matches is True and native.identity_proof == identity
if hasattr(adapter, 'prepare_add_transaction') else
len(matches) == 1 and matches[0].engineering_identity == identity)
if (not owner_safe or Path(after.library).resolve() != canonical_library or after.flow != 1
or len(matches) != 1 or matches[0].engineering_identity != identity):
or len(matches) != 1 or not proof_matches):
return finish('RECOVERY_REQUIRED', '原生新增后名称、分区或来源工程内容未确认一致。', False)
uploaded = True
checkpoint('uploaded')
@@ -0,0 +1,127 @@
"""Prepared Add authority bound to the engine checkpoint, snapshot and live lease."""
import json
import os
from pathlib import Path
import threading
from uuid import uuid4
from .management import _write_json, engineering_identity
from .scoped_manifest import build_manifest, ManifestScope
def _read(path):
return json.loads(Path(path).read_text(encoding='utf-8'))
def fixture_authority(root, library, token):
root = Path(root).resolve()
expected = root/'native-add/fixture/mentor_lib.lmc'
owner = _read(root/'probe-owner.json')
if (not token or owner.get('token') != token or not expected.is_file()
or Path(library).resolve() != expected.resolve()
or Path(owner.get('library', '')).resolve() != expected.resolve()):
raise ValueError('Management research requires the exact newly created owned fixture.')
return {'root': str(root), 'token': token}
def current_lease(library):
from .library_lock import LibraryLock, _guard, _owners, blocker_path, checkpoint_record
lease = LibraryLock(library)
with _guard:
owner = _owners.get(lease.key)
guard = checkpoint_record(blocker_path(library))
if (owner is None or owner['retained'] or owner['thread'] != threading.get_ident()
or guard is None or guard['pid'] != os.getpid()
or guard['status'] != 'OPERATION_IN_PROGRESS'
or owner['lease_id'] != guard['lease_id']
or Path(guard['library']).resolve() != Path(library).resolve()):
raise ValueError('Management transaction requires the current thread exact active library lease.')
return {'lease_id': owner['lease_id'], 'lease_handle': int(owner['handle']), 'supervisor_pid': os.getpid()}
def _authorize(record, mentor_home):
fixture = record.get('fixture')
if fixture is not None:
fixture_authority(fixture['root'], record['library'], fixture['token'])
else:
from .native_management import NativeManagementAdapter
capability = NativeManagementAdapter(mentor_home=mentor_home).capabilities()['add']
if not capability.supported: raise ValueError(capability.reason)
def prepare_transaction(request, root, expected_identity, *, mentor_home, fixture=None):
root = Path(root).resolve()
source = Path(request.source).resolve()
if source.parent != root/'source':
raise ValueError('Native Add accepts only the management engine staged source.')
library = Path(request.library).resolve()
if root.is_relative_to(library.parent) or library.parent.is_relative_to(root):
raise ValueError('Management transaction evidence overlaps the target library.')
checkpoint = _read(root/'checkpoint.json')
stages = {item['stage'] for item in checkpoint.get('history', [])}
if (checkpoint.get('status') != 'RUNNING' or checkpoint.get('stage') != 'prepare_identity'
or Path(checkpoint['library']).resolve() != library
or checkpoint['name'] != request.name or checkpoint['partition'] != request.partition
or not {'backup', 'stage_source'}.issubset(stages)):
raise ValueError('Native Add requires the engine backup/staging checkpoint.')
backup = _read(root/'library-before-manifest.json')
if build_manifest(root/'library-before', scope=ManifestScope.library(request.name, library.name)) != backup:
raise ValueError('Management backup has not been verified.')
baseline = _read(root/'source-identity/identity.json')
if baseline.get('safe_to_continue') is not True or baseline.get('identity') != expected_identity:
raise ValueError('Native source identity evidence is missing or changed.')
record = {**current_lease(library), 'nonce': uuid4().hex, 'library': str(library),
'name': request.name, 'partition': request.partition, 'top_level_block': request.top_level_block,
'source_name': source.name, 'source_identity': engineering_identity(source),
'source_manifest': build_manifest(source.parent), 'backup_manifest': backup,
'expected_identity': expected_identity, 'fixture': fixture}
_authorize(record, mentor_home)
_write_json(root/'native-add-prepared.json', record)
return record['nonce']
def validate_transaction(job, root, *, check_source=True):
from .library_lock import blocker_path, checkpoint_record, _supervisor_alive
import win32api, win32con, win32file
root = Path(root).resolve()
record = _read(root/'native-add-prepared.json')
library = Path(job['library']).resolve()
source = root/'source'/record['source_name']
guard = checkpoint_record(blocker_path(library))
checkpoint = _read(root/'checkpoint.json')
if (not job.get('transaction_nonce') or job['transaction_nonce'] != record['nonce']
or Path(record['library']).resolve() != library
or any(job.get(key) != record[key] for key in ('name', 'partition', 'top_level_block', 'source_identity'))
or source.parent != root/'source' or source.resolve().parent != (root/'source').resolve()
or Path(job['source']).resolve() != source.resolve()
or guard is None or guard['lease_id'] != record['lease_id']
or guard['pid'] != record['supervisor_pid'] or guard['pid'] != job['supervisor_pid']
or guard['status'] != 'OPERATION_IN_PROGRESS'
or Path(guard['library']).resolve() != library or not _supervisor_alive(guard['pid'])
or checkpoint.get('status') != 'RUNNING' or checkpoint.get('stage') != 'native_add'
or Path(checkpoint['library']).resolve() != library
or checkpoint['name'] != record['name'] or checkpoint['partition'] != record['partition']):
raise ValueError('Native Add transaction authority is missing, stale or foreign.')
_authorize(record, job['mentor_home'])
baseline = _read(root/'source-identity/identity.json')
if (baseline.get('safe_to_continue') is not True or baseline.get('identity') != record['expected_identity']
or build_manifest(root/'library-before', scope=ManifestScope.library(record['name'], library.name))
!= record['backup_manifest']
or check_source and (build_manifest(source.parent) != record['source_manifest']
or engineering_identity(source) != record['source_identity'])):
raise ValueError('Native Add baseline, backup or staged source proof changed.')
process = win32api.OpenProcess(win32con.PROCESS_DUP_HANDLE, False, record['supervisor_pid'])
duplicate = None
try:
duplicate = win32api.DuplicateHandle(process, record['lease_handle'], win32api.GetCurrentProcess(),
0, False, win32con.DUPLICATE_SAME_ACCESS)
final_path = win32file.GetFinalPathNameByHandle(duplicate, 0)
if final_path.startswith('\\\\?\\UNC\\'): final_path = '\\\\'+final_path[8:]
elif final_path.startswith('\\\\?\\'): final_path = final_path[4:]
expected_lock = library.with_name('.'+library.stem+'.cbb-upload.lock')
if Path(final_path).resolve() != expected_lock.resolve():
raise ValueError('Native Add supervisor lease belongs to another library.')
finally:
if duplicate is not None: duplicate.Close()
process.Close()
return record
+168 -11
View File
@@ -3,7 +3,7 @@
The installed Tcl CleanWGLib/F4 contract has isolated removal proof. Discovery
of an Add dialog is deliberately insufficient to enable production Add/Update.
"""
from dataclasses import asdict
from dataclasses import asdict, replace
import ctypes
import json
import os
@@ -21,6 +21,9 @@ from .scoped_manifest import hash_file
from .network_path import absolute_preserving_drive
_retained_workers = []
# Promotion requires coordinator-owned native CRUD evidence, in a separate change.
_PRODUCTION_ADD_VALIDATED = False
_PRODUCTION_UPDATE_VALIDATED = False
_BINARY_PROOF = {
'lm/win32/bin/CleanWGLib.exe': '7808ded326555f1fd5d5c14f68803dbb4f970d624f9ad6e1c7982dc9ed867917',
'lm/win32/bin/LibraryManager.exe': 'a9c4c3d806794dbdc56d2bc4c637a1cf25e87e98644a7d5fd4eb0067ca5845e0',
@@ -89,8 +92,9 @@ class NativeManagementAdapter:
reason = self._binary_capability()
return {
'remove': Capability(not reason, reason or '已验证 CleanWGLib/F4;仅 ASCII 名称、Logical-Physical 和 DxDesigner 库。'),
'add': Capability(False, '原生新增已调用并注册,但工程身份复读尚未通过;生产新增保持禁用。'),
'update': Capability(False, '同名更新需要原生移除、重新导入及完整端到端隔离验证,目前不可用。'),
'add': Capability(not reason and _PRODUCTION_ADD_VALIDATED, '原生新增及工程身份已有隔离证据;完整事务验证通过前生产新增保持禁用。'),
'update': Capability(not reason and _PRODUCTION_ADD_VALIDATED and _PRODUCTION_UPDATE_VALIDATED,
'同名更新需要原生移除、重新导入及完整端到端隔离验证,目前不可用。'),
}
def _worker(self, job, evidence):
@@ -111,7 +115,11 @@ class NativeManagementAdapter:
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired:
raise RuntimeError('Another CBB operation owns the management mutex.')
job = prepare_owned_fixture_add(job, evidence)
if job.get('authority_kind') == 'management':
from .management_transaction import validate_transaction
validate_transaction(job, evidence.parent)
else:
job = prepare_owned_fixture_add(job, evidence)
from .library_lock import LibraryLock
owner_safe = False
# Nest only after preparation proves an existing caller lease.
@@ -124,7 +132,7 @@ class NativeManagementAdapter:
finally:
if acquired: win32event.ReleaseMutex(mutex)
mutex.Close()
if job['operation'] == 'probe_create_add':
if job['operation'] in ('probe_create_add', 'probe_create'):
# Prepare the fixed NEW fixture before a native owner can start.
# The parent owns its sidecar for the entire create/add invocation.
from .library_lock import LibraryLock
@@ -197,8 +205,93 @@ class NativeManagementAdapter:
def add(self, request, evidence):
# Route readiness never grants production mutation authority.
return NativeOutcome(False, True, self.capabilities()['add'].reason,
evidence_path=Path(evidence))
capability = self.capabilities()['add']
if not capability.supported:
return NativeOutcome(False, True, capability.reason, evidence_path=Path(evidence))
return self._add_transaction(request, Path(evidence))
def prepare_add_transaction(self, request, root, *, original_source):
from .native_engineering_identity import project_library, asset_identity, capture_identity
from .management_transaction import current_lease, prepare_transaction
from .management import source_project
from .backup_recovery import _align_library
if not self.capabilities()['add'].supported:
raise ValueError(self.capabilities()['add'].reason)
current_lease(request.library)
original_assets = asset_identity(original_source, project_library(original_source))
staged, pcb, _ = source_project(request.source, request.top_level_block)
if staged.parent != Path(root).resolve()/'source':
raise ValueError('Only the engine staged source can be aligned for native Add.')
_align_library(staged, pcb, request.library)
if asset_identity(staged, request.library) != original_assets:
raise ValueError('Staged engineering assets differ from the original source.')
proof = capture_identity(staged, Path(root)/'source-identity', expected_library=request.library,
owner_library=request.library, mentor_home=self.home, timeout_seconds=request.timeout_seconds)
if proof.identity is None or not proof.safe_to_continue:
return request, proof
token = prepare_transaction(request, root, proof.identity, mentor_home=self.home,
fixture=getattr(self, '_fixture_authority', None))
return replace(request, transaction_token=token), proof
def _add_transaction(self, request, evidence):
from .management_transaction import validate_transaction
from .library_lock import LibraryLock
from .native_engineering_identity import capture_identity, project_library
from .management import source_project
from .backup_recovery import _align_library, _idle_check
job = {'operation': 'add', 'authority_kind': 'management', 'transaction_nonce': request.transaction_token,
'library': str(absolute_preserving_drive(request.library)), 'source': str(request.source),
'name': request.name, 'partition': request.partition, 'top_level_block': request.top_level_block,
'source_identity': engineering_identity(request.source), 'supervisor_pid': os.getpid(),
'mentor_home': str(self.home), 'timeout_seconds': request.timeout_seconds,
'mapped_drive': request.mapped_drive, 'mapped_remote_root': request.mapped_remote_root}
prepared = validate_transaction(job, evidence.parent)
owner_safe = False
with LibraryLock(request.library, safe_to_release=lambda: owner_safe):
result = self._worker(job, evidence)
owner_safe = result.get('safe_to_continue') is True
if not owner_safe or not result.get('success'):
return NativeOutcome(False, owner_safe, result.get('detail', 'Native Add failed.'), evidence_path=evidence)
owner_safe = False
# The native editor may leave PCB/pcb.prj relative to the staged
# location. Correct only documented library-reference tokens after
# its owner has exited, then reopen the native catalog independently.
validate_transaction(job, evidence.parent, check_source=False)
work = Path(request.library).parent/'ReusableBlocksLP'/request.name/'Work'
projects = list(work.glob('*.prj'))
if len(projects) != 1:
owner_safe = False
return NativeOutcome(True, False, 'Registered engineering project is not unique.',
identity_matches=False, evidence_path=evidence)
target, pcb, _ = source_project(projects[0], request.top_level_block)
_idle_check(request.library, target, pcb)
owner_safe = False
before_refs = {str(p): hash_file(p) for p in (target, pcb.parent/'pcb.prj')}
_align_library(target, pcb, request.library)
if project_library(target) != Path(request.library).resolve():
raise ValueError('Registered project references do not resolve to the exact target library.')
_write_json(evidence/'reference-alignment.json', {'before': before_refs,
'after': {str(p): hash_file(p) for p in (target, pcb.parent/'pcb.prj')}, 'library': job['library']})
catalog = self.catalog(request.library, evidence/'reopen-aligned')
owner_safe = catalog.safe_to_continue
entries = [entry for entry in catalog.entries if entry.name == request.name and entry.partition == request.partition]
if (not owner_safe or Path(catalog.library).resolve() != Path(request.library).resolve()
or catalog.flow != 1 or len(entries) != 1):
owner_safe = False
return NativeOutcome(True, False, 'Aligned target did not reopen with the exact catalog identity.',
identity_matches=False, evidence_path=evidence)
owner_safe = False
proof = capture_identity(target, evidence/'registered-identity', expected_library=request.library,
owner_library=request.library, mentor_home=self.home, timeout_seconds=request.timeout_seconds)
owner_safe = proof.safe_to_continue
matched = proof.identity is not None and proof.identity == prepared['expected_identity']
_write_json(evidence/'identity-comparison.json', {'identity_matches': matched,
'expected': prepared['expected_identity'], 'registered': proof.identity,
'safe_to_continue': owner_safe, 'detail': proof.detail})
return NativeOutcome(True, owner_safe,
'Native ASCII/CSV/EDIF, physical assets and library references match.' if matched else
'Native registration succeeded but complete engineering identity proof did not match: '+proof.detail,
identity_matches=matched, evidence_path=evidence, identity_proof=proof.identity)
def add_owned_fixture(self, request, evidence, *, probe_token):
"""Research only: stage and back up a token-bound, actively leased fixture."""
@@ -240,6 +333,64 @@ class NativeManagementAdapter:
detail, identity_matches=identity_matches, evidence_path=evidence)
class _OwnedFixtureManagementAdapter(NativeManagementAdapter):
"""Diagnostic capability grant restricted to a token-bound created fixture."""
def __init__(self, root, token, **kwargs):
super().__init__(**kwargs)
from .management_transaction import fixture_authority
self._fixture_authority = fixture_authority(root, Path(root)/'native-add/fixture/mentor_lib.lmc', token)
def capabilities(self):
from .management_transaction import fixture_authority
from .native_engineering_identity import check_exporters
fixture = self._fixture_authority
fixture_authority(fixture['root'], Path(fixture['root'])/'native-add/fixture/mentor_lib.lmc', fixture['token'])
caps = super().capabilities()
reason = self._binary_capability()
try: check_exporters(self.home)
except (ValueError, OSError) as error: reason = str(error)
for operation in ('add', 'update'):
caps[operation] = Capability(not reason, reason or 'Owned fixture engine validation only; production capability unchanged.')
return caps
def preflight(self, request, catalog):
from .management_transaction import fixture_authority
fixture = self._fixture_authority
fixture_authority(fixture['root'], request.library, fixture['token'])
super().preflight(request, catalog)
def run_owned_fixture_management(request, root, *, probe_token, mentor_home=None, **kwargs):
"""Run the real engine with a narrow fixture grant, never a public override."""
from .management import run_management
from .management_transaction import fixture_authority
fixture_authority(root, request.library, probe_token)
adapter = _OwnedFixtureManagementAdapter(root, probe_token, mentor_home=mentor_home)
return run_management(request, adapter=adapter, **kwargs)
def create_owned_fixture(root, *, mentor_home=None):
"""Diagnostic-only empty native library, guarded by the existing creation protocol."""
import win32con, win32event
root = absolute_preserving_drive(root)
if root.exists(): raise ValueError('Native fixture root must be entirely new.')
adapter = NativeManagementAdapter(mentor_home=mentor_home)
if not adapter.route_capabilities()['add'].supported:
raise ValueError(adapter.route_capabilities()['add'].reason)
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
token = uuid4().hex
try:
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired: raise RuntimeError('Another CBB operation owns the management mutex.')
library = root/'native-add/fixture/mentor_lib.lmc'
result = adapter._worker({'operation': 'probe_create', 'library': str(library), 'probe_token': token}, root/'native-add')
return {**result, 'probe_token': token, 'fixture_root': str(root)}
finally:
if acquired: win32event.ReleaseMutex(mutex)
mutex.Close()
def prepare_owned_fixture_add(job, root):
"""Create fresh transaction evidence while this thread owns the fixture."""
from .library_lock import LibraryLock, owned_snapshot, checkpoint_record, blocker_path, _guard, _owners
@@ -461,7 +612,9 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
from .management import source_project
source, pcb, top = source_project(job['source'], job.get('top_level_block', ''))
source_folder = 'source-replacement' if job['operation'] == 'probe_readd' else 'source'
source_root = Path(root).resolve()/'source' if job['operation'] == 'add' else Path(root).parent.resolve()/source_folder
source_root = (Path(root).resolve()/'source'
if job['operation'] == 'add' and job.get('authority_kind') != 'management'
else Path(root).parent.resolve()/source_folder)
if not source.is_relative_to(source_root):
raise ValueError('隔离新增只允许使用本次复制的来源工程。')
_align_library(source, pcb, Path(job['library']))
@@ -716,7 +869,11 @@ def _catalog_com(job, root):
import pythoncom, win32com.client, win32con, win32gui, win32process
from .mentor_adapter import _process_details
if job['operation'] == 'add':
validate_owned_fixture_add(job, root)
if job.get('authority_kind') == 'management':
from .management_transaction import validate_transaction
validate_transaction(job, root.parent)
else:
validate_owned_fixture_add(job, root)
desktop, name = _current_desktop()
if name != job['desktop'] or not name.startswith('CbbManagement_'):
raise RuntimeError('拒绝在非本次私有桌面读取原生目录。')
@@ -762,7 +919,7 @@ def _catalog_com(job, root):
raise RuntimeError('COM 注册指向不同的 Library Manager 安装,拒绝打开中心库。')
watcher = threading.Thread(target=observe_dialogs, daemon=True)
watcher.start()
if job['operation'] == 'probe_create_add':
if job['operation'] in ('probe_create_add', 'probe_create'):
target = prepare_probe_library(job, root)
library = app.CreateLibrary(str(target), 1)
_write_json(root.parent/'probe-owner.json', {'library': str(target), 'token': job['probe_token']})
@@ -854,7 +1011,7 @@ 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', 'add', 'probe_create_add', 'probe_readd'):
if job['operation'] in ('catalog', 'add', 'probe_create', 'probe_create_add', 'probe_readd'):
if job['operation'] == 'add':
route = NativeManagementAdapter(mentor_home=job['mentor_home']).route_capabilities()['add']
if not route.supported:
+1 -1
View File
@@ -200,7 +200,7 @@ class MainWindow(QWidget):
management_layout = QVBoxLayout(management)
management_buttons = QHBoxLayout()
self.add_button = QPushButton('新增 CBB…')
self.update_button = QPushButton('同名更新已选…')
self.update_button = QPushButton('用工程替换已选 CBB…(原生重新导入)')
self.remove_button = QPushButton('移除已选…')
for operation, widget in (('add', self.add_button), ('update', self.update_button), ('remove', self.remove_button)):
widget.clicked.connect(lambda _=False, op=operation: self.manage_cbb(op))
+23
View File
@@ -301,3 +301,26 @@ def test_source_inside_target_library_rejected_before_catalog(setup):
adapter.catalog = lambda *a: pytest.fail('overlapping source reached native catalog')
result = execute(replace(request, operation='add', name='New', source=source), adapter)
assert result.status == 'BLOCKED' and not request.evidence_dir.exists()
@pytest.mark.parametrize('matched', [True, False])
def test_prepared_native_identity_is_required_after_exact_catalog(setup, matched):
from cbb_refresh_verify.native_engineering_identity import IdentityOutcome
from cbb_refresh_verify.management import NativeOutcome
request, adapter, source = setup
expected = {'policy': 'native-test', 'logical': 'same', 'physical': 'same'}
def prepare(staged, root, *, original_source):
assert original_source == source and staged.source != source
assert (root/'library-before/mentor.lmc').exists()
adapter.calls.append('prepare_identity')
return staged, IdentityOutcome(expected, True, 'baseline captured', root)
adapter.prepare_add_transaction = prepare
original_add = adapter.add
def add(staged, evidence):
original_add(staged, evidence)
return NativeOutcome(True, True, 'native registered', identity_matches=matched,
identity_proof=expected if matched else {'different': True})
adapter.add = add
result = execute(replace(request, operation='update', source=source, auto_verify=False), adapter)
assert adapter.calls[0:2] == ['prepare_identity', 'remove']
assert result.status == ('UPLOADED' if matched else 'RECOVERY_REQUIRED')
+135
View File
@@ -0,0 +1,135 @@
"""Run the real management engine with only the native/export boundaries faked."""
from dataclasses import replace
import json
from pathlib import Path
import shutil
import pytest
@pytest.fixture
def transaction(tmp_path, monkeypatch):
from test_management import project
import cbb_refresh_verify.native_management as native
import cbb_refresh_verify.native_engineering_identity as identity
import cbb_refresh_verify.backup_recovery as recovery
from cbb_refresh_verify.management import ManagementRequest, engineering_identity, _write_json
from cbb_refresh_verify.management_transaction import validate_transaction
root = tmp_path/'probe'
library = root/'native-add/fixture/mentor_lib.lmc'
library.parent.mkdir(parents=True); library.write_bytes(b'fixture library')
(root/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned'}), encoding='utf-8')
source = project(tmp_path/'source')
for path in (source, source.parent/'PCB/pcb.prj'):
with path.open('a') as stream: stream.write(f'KEY CentralLibrary "{library}"\n')
state = {'entries': [], 'calls': [], 'corrupt': False, 'fail_add': False}
monkeypatch.setattr(native.NativeManagementAdapter, '_binary_capability', lambda _: '')
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
monkeypatch.setattr(recovery, '_idle_check', lambda *_: None)
def capture(source, evidence, *, expected_library, **kwargs):
evidence = Path(evidence); evidence.mkdir(parents=True, exist_ok=False)
value = identity.asset_identity(source, expected_library)
value.update(ascii_sha256='logical', csv={'work/identity': 'tables'}, edif_sha256='geometry')
_write_json(evidence/'identity.json', {'identity': value, 'safe_to_continue': True})
return identity.IdentityOutcome(value, True, 'file-only export proof', evidence)
monkeypatch.setattr(identity, 'capture_identity', capture)
def worker(adapter, job, evidence):
evidence = Path(evidence); evidence.mkdir(parents=True, exist_ok=False)
state['calls'].append(job['operation'])
if job['operation'] == 'catalog':
return {'success': True, 'safe_to_continue': True, 'library': str(library), 'flow': 1,
'entries': list(state['entries'])}
if job['operation'] == 'add':
if state.get('tamper') == 'nonce': job['transaction_nonce'] = 'foreign'
if state.get('tamper') == 'supervisor': job['supervisor_pid'] = -1
if state.get('tamper') == 'backup':
(evidence.parent/'library-before'/library.name).write_bytes(b'corrupted backup')
if state.get('tamper') == 'source':
(Path(job['source']).parent/'database/icdb.dat').write_bytes(b'changed staged input')
validate_transaction(job, evidence.parent)
if state['fail_add']: return {'success': False, 'safe_to_continue': True, 'detail': 'native failure'}
staged = Path(job['source'])
(staged.parent/'database/icdb.dat').write_bytes(b'native database normalization')
work = library.parent/'ReusableBlocksLP'/job['name']/'Work'
shutil.copytree(staged.parent, work)
pcb_project = work/'PCB/pcb.prj'
text = pcb_project.read_text()
import re
pcb_project.write_text(re.sub(r'KEY CentralLibrary "[^"]*"', 'KEY CentralLibrary "wrong-relative.lmc"', text))
if state['corrupt']: (work/'PCB/Layout/LayoutDB.lyt').write_bytes(b'wrong physical design')
state['entries'] = [{'name': job['name'], 'partition': job['partition'],
'engineering_identity': engineering_identity(work/staged.name)}]
return {'success': True, 'safe_to_continue': True, 'identity_matches': False}
if job['operation'] == 'remove':
state['entries'] = []
shutil.rmtree(library.parent/'ReusableBlocksLP'/job['name'])
return {'success': True, 'safe_to_continue': True}
pytest.fail('unexpected native operation')
monkeypatch.setattr(native.NativeManagementAdapter, '_worker', worker)
request = ManagementRequest('add', library, 'Block', source=source, auto_verify=False,
evidence_dir=tmp_path/'evidence')
yield root, request, state
from cbb_refresh_verify.library_lock import LibraryLock, _owners, _guard, blocker_path
with _guard:
owner = _owners.pop(LibraryLock(library).key, None)
if owner: owner['handle'].Close()
blocker_path(library).unlink(missing_ok=True)
def execute(root, request):
from cbb_refresh_verify.native_management import run_owned_fixture_management
return run_owned_fixture_management(request, root, probe_token='owned', idle_check=lambda *_: None)
def test_owned_fixture_engine_add_conflict_update_remove_and_identity(transaction):
from cbb_refresh_verify.native_engineering_identity import project_library
root, request, state = transaction
original = request.source.read_bytes()
assert execute(root, request).status == 'UPLOADED'
registered = request.library.parent/'ReusableBlocksLP/Block/Work/Source.prj'
assert project_library(registered) == request.library.resolve()
calls = len(state['calls'])
assert execute(root, request).status == 'UPLOAD_FAILED'
assert state['calls'][calls:] == ['catalog']
(request.source.parent/'PCB/Layout/LayoutDB.lyt').write_bytes(b'replacement physical design')
assert execute(root, replace(request, operation='update')).status == 'UPLOADED'
assert (registered.parent/'PCB/Layout/LayoutDB.lyt').read_bytes() == b'replacement physical design'
assert execute(root, replace(request, operation='remove', source=None)).status == 'REMOVED'
assert execute(root, request).status == 'UPLOADED'
assert request.source.read_bytes() == original
def test_native_registered_but_asset_mismatch_retains_recovery(transaction):
root, request, state = transaction
state['corrupt'] = True
result = execute(root, request)
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
def test_update_readd_failure_preserves_snapshot_and_removed_checkpoint(transaction):
root, request, state = transaction
assert execute(root, request).status == 'UPLOADED'
state['fail_add'] = True
result = execute(root, replace(request, operation='update'))
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
assert (result.evidence_path.parent/'library-before/ReusableBlocksLP/Block/Work/Source.prj').exists()
assert 'removed' in [entry['stage'] for entry in json.loads(result.evidence_path.read_text())['history']]
def test_fixture_grant_cannot_authorize_arbitrary_library(transaction, tmp_path):
from cbb_refresh_verify.native_management import run_owned_fixture_management
root, request, state = transaction
other = tmp_path/'production.lmc'; other.write_bytes(b'unchanged')
with pytest.raises(ValueError):
run_owned_fixture_management(replace(request, library=other), root, probe_token='owned')
assert other.read_bytes() == b'unchanged' and not state['calls']
@pytest.mark.parametrize('tamper', ['nonce', 'supervisor', 'backup', 'source'])
def test_worker_rejects_modified_management_authority_before_add(transaction, tamper):
root, request, state = transaction
state['tamper'] = tamper
original = request.source.read_bytes()
result = execute(root, request)
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
assert state['entries'] == [] and request.source.read_bytes() == original
+18
View File
@@ -24,6 +24,24 @@ def test_public_add_cannot_bypass_disabled_capability(tmp_path, monkeypatch):
assert not result.success and result.safe_to_continue
def test_empty_fixture_creation_uses_existing_new_library_guard_route(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
seen = []
monkeypatch.setattr(native.NativeManagementAdapter, '_binary_capability', lambda _: '')
monkeypatch.setattr(native.NativeManagementAdapter, '_worker',
lambda adapter, job, evidence: (seen.append((job, evidence)) or
{'success': True, 'safe_to_continue': True, 'entries': []}))
root = tmp_path/'fresh'
result = native.create_owned_fixture(root)
assert result['success'] and result['entries'] == []
assert seen[0][0]['operation'] == 'probe_create'
assert Path(seen[0][0]['library']) == root/'native-add/fixture/mentor_lib.lmc'
assert seen[0][0]['probe_token'] == result['probe_token']
existing = tmp_path/'existing'; existing.mkdir()
with pytest.raises(ValueError): native.create_owned_fixture(existing)
assert len(seen) == 1
def test_unprepared_add_rejected_before_native_activation(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
import win32com.client