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

+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: