Compare commits

..
Author SHA1 Message Date
阿白叔 32d7a63828 fix: apply reviewed ownership and release follow-up to umbrella 2026-11-06 12:08:59 +08:00
阿白叔 9970635f7e docs: record published review chain and completed verification 2026-11-05 23:33:45 +08:00
阿白叔 e53c5d0e92 fix: restrict explicit force release to verified user document clients 2026-11-05 23:31:35 +08:00
阿白叔 e4266ae88c docs: plan scoped release contract and ordered PR reviews 2026-11-05 22:53:29 +08:00
阿白叔 9a9fbce9b2 merge: reconcile main desktop cleanup and record 1582 passing tests 2026-11-05 21:58:27 +08:00
阿白叔 1bd7589fef fix: isolate ICDB checks and recover scoped native sessions 2026-11-05 21:52:38 +08:00
阿白叔 1acfbd6374 fix: allow native inspection and backup entry after batch errors 2026-11-05 08:24:53 +08:00
阿白叔 aea6192ef9 fix: narrow cross-item and cross-library blockers 2026-11-05 07:42:49 +08:00
阿白叔 53118bae19 feat: replace automatic ICDB maintenance with batch inspection 2026-11-04 23:40:46 +08:00
阿白叔 beb2b06fdf fix: diagnose PCB startup before ICDB maintenance 2026-11-04 22:53:16 +08:00
阿白叔 4ebe098ef0 feat: open native project history and backup interface 2026-11-04 22:12:24 +08:00
阿白叔 00db1cf5f2 fix: continue released verify batches and bound automation shutdown 2026-11-04 20:51:35 +08:00
阿白叔 477a5a46e3 fix: separate verification and ICDB maintenance with live session leases 2026-11-04 19:16:08 +08:00
阿白叔 2587d33c5a fix: keep maintenance results concise and catalog readable 2026-11-04 17:26:35 +08:00
阿白叔 223655fe00 fix: stabilize ICDB preflight and organize UI into tabs 2026-11-04 17:06:27 +08:00
阿白叔 29959e2988 feat: offer explicit copy recovery after failed ICDB maintenance 2026-11-04 14:16:00 +08:00
阿白叔 e14a864b37 fix: inspect native ICDB occupancy before bounded repair 2026-11-04 12:26:09 +08:00
阿白叔 cb1326688b docs: record reviewed ICDB candidate validation 2026-11-04 10:37:10 +08:00
阿白叔 ef652f3ada fix: guard ICDB diagnostics and exclude READY maintenance targets 2026-11-04 10:27:53 +08:00
阿白叔 8180a8a302 fix: diagnose ICDB before repeatable maintenance repair 2026-11-04 09:14:40 +08:00
阿白叔 c902ffbe9a docs: record frozen ICDB recovery with user-selected PCB version 2026-11-03 18:11:00 +08:00
阿白叔 de952a68d6 fix: inspect addressless ICDB projects and ask for PCB recovery version 2026-11-03 17:42:33 +08:00
阿白叔 c85696080d perf: replace automatic backups with manual backup reminders 2026-11-03 16:44:30 +08:00
阿白叔 7527800128 fix: complete legacy CBB import recovery and guard late native submission 2026-11-03 16:03:14 +08:00
阿白叔 d36b6bcad0 fix: admit linked legacy ICDB projects and explain blocked actions 2026-11-03 13:51:05 +08:00
阿白叔 5eac654c36 docs: record native CRUD frozen acceptance and candidate limits 2026-11-03 13:06:07 +08:00
阿白叔 b26e2f2f62 test: create source fixture for native UIA path admission 2026-11-03 12:54:21 +08:00
阿白叔 9ac2f91dde fix: reject legacy copy paths and surface native Add failures 2026-11-03 12:51:35 +08:00
阿白叔 e915aaa865 feat: enable validated pinned native Add and replacement routes 2026-11-03 12:29:42 +08:00
阿白叔 f21781f170 fix: preserve unknown assets and retained export-copy ownership 2026-11-03 12:24:54 +08:00
阿白叔 55a82fdc5f feat: bind native CRUD to prepared engine identity transactions 2026-11-03 11:54:56 +08:00
阿白叔 89500cbb5f feat: require native EDIF geometry in engineering identity 2026-11-03 11:43:45 +08:00
阿白叔 63f3417f19 feat: capture gated native logical and physical identity evidence 2026-11-03 11:39:38 +08:00
阿白叔 ca84bce24f fix: retain uncertain fixture owners and reject source overlap 2026-11-03 11:27:34 +08:00
阿白叔 b97556dcc1 fix: require owned fixture authority for native Add research 2026-11-03 11:22:27 +08:00
阿白叔 07a9c1eaaf feat: integrate shared native Add worker behind identity gate 2026-11-03 11:11:36 +08:00
阿白叔 f8f2dd53aa docs: record actual maintenance button and user-selected recovery validation 2026-11-03 10:25:59 +08:00
阿白叔 2085ec770f docs: explain pending PCB recovery version decision 2026-11-03 09:55:24 +08:00
阿白叔 d76475a1d7 fix: report pending PCB recovery version without obscuring native repair 2026-11-03 09:54:01 +08:00
阿白叔 99a708b40c fix: distinguish UIA dialog chrome from native consent controls 2026-11-03 09:43:16 +08:00
阿白叔 9806ef8f66 docs: record local-only post-repair consent boundary 2026-11-03 09:37:52 +08:00
阿白叔 aa6684b588 fix: bound post-repair readwrite consent to proven local startup 2026-11-03 09:36:33 +08:00
阿白叔 5a758ee3b6 fix: separate maintenance release from safe queue continuation 2026-11-03 09:18:36 +08:00
阿白叔 b635432cff fix: scope maintenance addresses to selected project and shared stores 2026-11-03 09:16:13 +08:00
阿白叔 4cbca0b5a6 docs: explain explicit maintenance for existing ICDB addresses 2026-11-03 09:15:06 +08:00
阿白叔 e39dc63ded fix: admit explicit ICDB maintenance with preserved address evidence 2026-11-03 09:13:32 +08:00
阿白叔 4f741cd176 docs: record final issue 2 candidate evidence and acceptance gaps 2026-11-02 22:59:50 +08:00
阿白叔 122bafcc7a test: scope deletion safeguard to authorized runtime checkpoints 2026-11-02 22:56:30 +08:00
阿白叔 8e486c1097 fix: bound native edit messages and identify empty IE infrastructure 2026-11-02 22:44:50 +08:00
阿白叔 bb98fe66dd fix: normalize native editor handles before UIA calls 2026-11-02 22:36:23 +08:00
阿白叔 1f69480ed8 fix: preload UIA before native proxies and package timezone support 2026-11-02 22:32:32 +08:00
阿白叔 ffa7e84d43 fix: retain unknown startup windows and expose native dispatch errors 2026-11-02 22:19:59 +08:00
阿白叔 46c3e72364 fix: preserve mapped native paths and retain probe ownership guards 2026-11-02 21:48:40 +08:00
阿白叔 dd1fcea7e2 fix: accept layout-based PCB projects without optional icdb path 2026-11-02 21:19:57 +08:00
阿白叔 797a79c30e feat: add guarded native CBB management and recovery coordination 2026-11-02 21:13:24 +08:00
阿白叔 3415e010ff fix: preserve engineering identity in scoped runtime exclusions 2026-11-02 19:50:26 +08:00
阿白叔 29c154d2ca feat: scope recovery manifests while verifying complete backups 2026-11-02 19:32:07 +08:00
阿白叔 877e3b4c76 fix: wait for native repair project shell and ignore known input indicators 2026-11-02 19:12:12 +08:00
阿白叔 b90a9bbfab fix: allow explicit native repair owner process queries 2026-11-02 18:52:04 +08:00
阿白叔 747ce1add2 feat: scope CBB search selection and maintenance to visible non-READY rows 2026-11-02 18:47:25 +08:00
阿白叔 c823a4b92d fix: fail closed on busy or unconfirmed native repair evidence 2026-11-02 18:27:19 +08:00
阿白叔 aa760c2839 fix: classify ICDB repair outcomes and gate released recovery 2026-11-02 18:14:38 +08:00
阿白叔 44b808b8e2 docs: record approved issue 2 implementation plan 2026-11-02 17:52:50 +08:00
阿白叔 ec78dd722c fix: close owned PCB startup failures before ICDB recovery 2026-11-02 17:40:18 +08:00
8 changed files with 51 additions and 466 deletions

No files matched your search

@@ -1,7 +0,0 @@
# PR #10 comment 309
Release proof now records the requested CBB, effective BLOCK/LIBRARY proof scope, identities/statuses of archived checkpoints and retained owners, and `reconciled_foreign_blockers`. For example, a BlockA operation which safely reconciles BlockB's historical checkpoint explicitly lists BlockB and the full-library proof. `data_recovery_confirmed` remains false. No extra gate, automatic backup or native action was added.
Three regressions first failed on missing evidence fields. After the fix, 94 backend/lease/release regressions passed; compileall and git diff --check passed. The tests use real temporary file/lease handles with the process-query boundary replaced; no production library was opened. Full regression is run again at the integrated chain tip. Real Mentor/shared-network acceptance and a rebuilt package remain outstanding.
Review: https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/10#issuecomment-309
@@ -1,21 +0,0 @@
# PR #12 comment 313
## Behavior
Window inspection takes a Windows thread snapshot for the requested processes, finds the desktops assigned to those threads, and opens only those desktops. Failures are recorded per affected PID outside the real window list. Unrelated inaccessible desktops no longer disable healthy rows. Preview, cooperative close, forced close, native Cancel and save-prompt responses all use the same per-PID incomplete-read fact during their fresh action-time observation.
Unknown or active native writes still prohibit forced termination. The review's suggested blanket force override for unreadable windows is not implemented: exact identity and private-desktop ownership do not establish that Save/Repair has returned. A failed read names that session and can be retried, while other sessions remain actionable.
Disk evidence retains window identity and a UTF-8 output excerpt of at most 4,096 bytes, original output length and SHA-256. It omits child-control trees and duplicated native-activity output. The complete preview remains in memory for the existing details action.
Native Cancel carries the preview's `block_names` and checks the same Work + SymbolLibs scope before the exact-process/control checks. It no longer silently widens a scoped preview to the full library.
## Verification
The initial five regressions failed against the old implementation. After the fix, 116 residual/backend/UI/background-queue regressions passed; compileall and git diff --check passed. This includes a real controlled Windows window on a private CbbManagement desktop, read from another process, with clean fixture exit and no Mentor/native database actions.
The real fixture caught a platform limitation missed by API doubles: EnumThreadWindows silently omits windows on another desktop. The final implementation maps threads to desktop names and uses OpenDesktop/EnumDesktopWindows for only those mapped desktops. GetThreadDesktop's borrowed handle is never closed; owned OpenDesktop handles and the thread snapshot are closed.
Independent review and the full integrated-chain run are recorded at the final PR #13 tip. Older deep-review comments #297-#300 remain outside this explicitly selected scope. No candidate was rebuilt; real Mentor, Windows 10 and shared/network release scenarios remain unverified.
Review: https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/12#issuecomment-313
@@ -1,25 +0,0 @@
# Latest reviews for PR #10/#11/#12
Scope: user selected only the 2026-11-09 comments #309/#310/#313. Earlier deep-review backlog stays out of scope. Preserve ICDB automatic Repair OFF, serial writes, current icon and independent-library admission. No merge to main, issue closure or release.
## PR #10
- [ ] Reproduce BlockA releasing historical BlockB checkpoints and retained owners without naming BlockB in proof.
- [ ] Record requested block, actual proof scope, checkpoint identities and foreign names in existing release proof. Preserve original checkpoint bytes and data_recovery_confirmed=False; no new blocking gate.
- [ ] Run backend/lease regressions, compile/diff checks, commit on codex/review-native-backend.
## PR #11/#12
- [ ] Forward-merge backend into UI, then UI into residual branch; no history rewriting.
- [ ] Test one unreadable process/thread not affecting another, without fabricated modal windows; cover preview and action-time rechecks.
- [ ] Enumerate only target-process threads/windows, store incomplete-read metadata per PID. Keep unknown/active writers protected rather than adding a blind force override.
- [ ] Persist window identities and at most a 4 KiB output excerpt, preserve full preview in memory, stop duplicating activity output.
- [ ] Carry exact preview block scope into native Cancel and recheck identity/scope before clicking.
- [ ] Run residual/UI regressions, compile/diff checks, commit on residual branch.
## Chain tip
- [ ] Merge residual fixes into PR #13, preserving ca39fb3 and icon.
- [ ] Address #11's line-ending note once at the tip: application.py to LF; pin it and main_window.py in EditorConfig. Preserve all other file endings and the global * -text rule.
- [ ] Independent review, integrated full suite, compile/diff checks, validation records and fast-forward pushes to existing PR branches.
- [ ] Update PR descriptions with precise results and no new package/native acceptance. Leave #3 as historical umbrella, without merging or closing it.
-13
View File
@@ -559,16 +559,6 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
records = [checkpoint_record(path) for path, data in before.items() if data is not None]
scoped = (block_name if block_name and all(record and record.get('block_name') == block_name
for record in records) and (owner is None or owner.get('block_name') == block_name) else None)
reconciled = [{'kind': 'checkpoint', 'path': str(path), 'recognized': metadata is not None,
**{key: (metadata or {}).get(key) for key in ('block_name', 'lease_id', 'pid', 'status', 'time')}}
for path, data in before.items() if data is not None
for metadata in (checkpoint_record(path),)]
if owner:
reconciled.append({'kind': 'retained_owner', 'path': str(lease.path),
'block_name': owner.get('block_name'), 'lease_id': owner['lease_id'],
'status': 'OWNER_RELEASE_UNCONFIRMED'})
foreign = sorted({item['block_name'] for item in reconciled
if block_name and item.get('block_name') and item['block_name'] != block_name})
proof_context = (_prove_library_released(library, allow_unknown_checkpoint=True) if unknown else
_prove_library_released(library, block_name=scoped)
if scoped else _prove_library_released(library))
@@ -580,9 +570,6 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
root = evidence/('release-' + uuid4().hex)
root.mkdir(parents=True, exist_ok=False)
record = {'library': str(library), 'status': 'RELEASE_CONFIRMED', **proof,
'requested_block_name': block_name, 'proof_scope': 'BLOCK' if scoped else 'LIBRARY',
'proof_block_name': scoped, 'reconciled_checkpoints': reconciled,
'reconciled_foreign_blockers': foreign,
'unknown_checkpoint_archived': unknown,
'data_recovery_confirmed': False, 'evidence_path': str(root/'release.json')}
(root/'release.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
+48 -173
View File
@@ -1,7 +1,6 @@
"""Preview and cooperatively close the exact native sessions a user confirms."""
from contextlib import contextmanager
import json
import hashlib
import os
from pathlib import Path
import re
@@ -40,8 +39,8 @@ def force_block_reason(row):
return ''
def native_activity(name, windows, *, incomplete=None):
if incomplete or any(w['class'] == 'UNCONFIRMED' for w in windows):
def native_activity(name, windows):
if any(w['class'] == 'UNCONFIRMED' for w in windows):
return {'status': 'UNCONFIRMED', 'detail': '原生窗口读取不完整'}
if any((name.casefold() == 'icdbprojectbackup.exe' and not w['enabled'])
or any(c['class'].casefold() == 'msctls_progress32' for c in w['children']) for w in windows):
@@ -113,85 +112,16 @@ def _force_ownership(handle, pid):
and session == win32ts.ProcessIdToSessionId(os.getpid())}
class _WindowSnapshot(dict):
def __init__(self, pids):
super().__init__((pid, []) for pid in pids)
self.incomplete = {}
def _process_threads(pids):
import ctypes
from ctypes import wintypes
class ThreadEntry(ctypes.Structure):
_fields_ = [('size', wintypes.DWORD), ('usage', wintypes.DWORD), ('tid', wintypes.DWORD),
('pid', wintypes.DWORD), ('base', wintypes.LONG), ('delta', wintypes.LONG),
('flags', wintypes.DWORD)]
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
kernel.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
kernel.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
kernel.CloseHandle.argtypes = [wintypes.HANDLE]
for name in ('Thread32First', 'Thread32Next'):
function = getattr(kernel, name)
function.argtypes = [wintypes.HANDLE, ctypes.POINTER(ThreadEntry)]
function.restype = wintypes.BOOL
snapshot = kernel.CreateToolhelp32Snapshot(4, 0) # TH32CS_SNAPTHREAD
if snapshot == ctypes.c_void_p(-1).value:
raise ctypes.WinError(ctypes.get_last_error())
result = {pid: [] for pid in pids}
try:
entry = ThreadEntry(); entry.size = ctypes.sizeof(entry)
more = kernel.Thread32First(snapshot, ctypes.byref(entry))
while more:
if entry.pid in result:
result[entry.pid].append(int(entry.tid))
entry.size = ctypes.sizeof(entry)
more = kernel.Thread32Next(snapshot, ctypes.byref(entry))
if ctypes.get_last_error() != 18: # ERROR_NO_MORE_FILES
raise ctypes.WinError(ctypes.get_last_error())
finally:
kernel.CloseHandle(snapshot)
return result
def _thread_desktop_name(tid):
import ctypes
from ctypes import wintypes
user = ctypes.WinDLL('user32', use_last_error=True)
user.GetThreadDesktop.argtypes = [wintypes.DWORD]
user.GetThreadDesktop.restype = wintypes.HANDLE
user.GetUserObjectInformationW.argtypes = [wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID,
wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)]
user.GetUserObjectInformationW.restype = wintypes.BOOL
ctypes.set_last_error(0)
desktop = user.GetThreadDesktop(tid)
if not desktop:
if error := ctypes.get_last_error():
raise ctypes.WinError(error)
return None # A non-GUI thread need not have an assigned desktop.
# GetThreadDesktop returns a borrowed handle; never CloseDesktop it.
name, needed = ctypes.create_unicode_buffer(512), wintypes.DWORD()
if not user.GetUserObjectInformationW(desktop, 2, name, ctypes.sizeof(name), ctypes.byref(needed)):
raise ctypes.WinError(ctypes.get_last_error())
return name.value
def _window_error(snapshot, pid):
return getattr(snapshot, 'incomplete', {}).get(pid)
def _process_windows(pids):
result = _WindowSnapshot(pids)
if not pids: return result
if not pids: return {}
import win32api, win32con, win32gui, win32process, win32service
from .native_repair_ui import _native_output
result = {pid: [] for pid in pids}
observed = set()
def capture(hwnd, _, *, pid, desktop_name):
if win32process.GetWindowThreadProcessId(hwnd)[1] != pid:
raise ValueError('窗口所属进程已变化')
if hwnd in observed or not win32gui.IsWindowVisible(hwnd):
def capture(hwnd, _=None, *, desktop_name='Default'):
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
if pid not in result or hwnd in observed or not win32gui.IsWindowVisible(hwnd):
return
if desktop_name is None:
raise ValueError('窗口所属桌面无法读取')
observed.add(hwnd)
children, documents = [], []
def child(handle, _):
@@ -211,46 +141,31 @@ def _process_windows(pids):
if any(c['class'].casefold().startswith('richedit') for c in children):
window['output'] = _native_output([window])
result[pid].append(window)
win32api.SetLastError(0)
def incomplete():
for pid in result:
result[pid].append({'hwnd': 0, 'title': '窗口状态读取不完整', 'class': 'UNCONFIRMED',
'enabled': False, 'children': []})
try:
threads = _process_threads(pids)
except Exception as error:
result.incomplete = {pid: str(error)[:500] for pid in pids}
win32gui.EnumWindows(capture, None)
except Exception:
incomplete()
try:
desktops = win32service.GetProcessWindowStation().EnumDesktops()
except Exception:
incomplete()
return result
desktops = {}
for pid in pids:
if not threads.get(pid):
result.incomplete[pid] = '进程线程已退出或暂时无法读取'
for tid in threads.get(pid, ()):
try:
desktop = _thread_desktop_name(tid)
if desktop:
desktops.setdefault(desktop, set()).add(pid)
except Exception as error:
result.incomplete.setdefault(pid, str(error)[:500])
if not any(pid in members for members in desktops.values()):
result.incomplete.setdefault(pid, '窗口所属桌面暂时无法确认')
# EnumThreadWindows silently omits windows on other desktops. Enumerate
# only desktops actually assigned to the target processes' threads.
for name, members in desktops.items():
for name in desktops:
if name != 'Default' and not name.startswith(('CbbVerify_', 'CbbRepair_', 'CbbManagement_', 'CbbStatusRead_', 'CbbFlagRead_')):
continue
desktop = None
try:
desktop = win32service.OpenDesktop(name, 0, False, win32con.DESKTOP_READOBJECTS)
win32api.SetLastError(0)
for hwnd in desktop.EnumDesktopWindows():
pid = None
try:
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
if pid in members:
capture(hwnd, None, pid=pid, desktop_name=name)
except Exception as error:
for affected in (members if pid is None else {pid} & members):
result.incomplete.setdefault(affected, str(error)[:500])
except Exception as error:
for pid in members:
result.incomplete.setdefault(pid, str(error)[:500])
for hwnd in desktop.EnumDesktopWindows(): capture(int(hwnd), desktop_name=name)
except Exception:
incomplete()
finally:
if desktop is not None:
desktop.CloseDesktop()
if desktop is not None: desktop.CloseDesktop()
return result
@@ -266,10 +181,8 @@ def _project_name(row, library):
return '当前库关联会话'
def close_target(name, windows, *, incomplete=None):
def close_target(name, windows):
"""No save/restore approval and no close against an unknown modal/window."""
if incomplete:
return None, '该会话窗口读取不完整,请重新检查:'+str(incomplete)
main = [w for w in windows if w['class'].startswith('Afx:') and (
name.casefold() == 'icdbprojectbackup.exe' and w['title'].startswith('iCDB Project Backup')
or name.casefold() == 'librarymanager.exe' and w['title'].startswith('Library Manager')
@@ -299,9 +212,7 @@ def close_target(name, windows, *, incomplete=None):
return window, ('将正常关闭工程;未保存时等待确认' if window.get('documents') else '可正常关闭')
def _save_question(windows, *, incomplete=None):
if incomplete:
return None
def _save_question(windows):
for window in windows:
text = '\n'.join(c['text'] for c in window['children'] if c['class'] == 'Static')
buttons = {c['id']: c for c in window['children'] if c['class'] == 'Button' and c['enabled']}
@@ -313,9 +224,8 @@ def _save_question(windows, *, incomplete=None):
return None
def _cancel_question(name, windows, *, incomplete=None):
if (name.casefold() != 'icdbprojectbackup.exe'
or native_activity(name, windows, incomplete=incomplete)['status'] != 'ACTIVE'):
def _cancel_question(name, windows):
if name.casefold() != 'icdbprojectbackup.exe' or native_activity(name, windows)['status'] != 'ACTIVE':
return None
candidates = []
for window in windows:
@@ -358,23 +268,20 @@ def inspect_residual_sessions(library, *, block_names=()):
sessions = []
for row in candidates:
item = dict(row)
item['block_names'] = list(blocks)
error = _window_error(windows, row['pid'])
item.update(windows_incomplete=bool(error), window_read_error=error)
try:
item.update(_process_identity(row))
target, detail = close_target(row['name'], windows.get(row['pid'], []), incomplete=error) if row['scope_confirmed'] else (
target, detail = close_target(row['name'], windows.get(row['pid'], [])) if row['scope_confirmed'] else (
None, '归属未确认,请在原生窗口确认工程并关闭后重新检查')
item.update(can_close=target is not None, detail=detail)
except Exception as identity_error:
item.update(can_close=False, detail=f'进程已变化或暂时无法确认:{identity_error}')
except Exception as error:
item.update(can_close=False, detail=f'进程已变化或暂时无法确认:{error}')
item['project'] = _project_name(row, library) if row['scope_confirmed'] else '归属未确认'
item['prompt'] = _save_question(windows.get(row['pid'], []), incomplete=error) if row['scope_confirmed'] else None
item['prompt'] = _save_question(windows.get(row['pid'], [])) if row['scope_confirmed'] else None
observed = windows.get(row['pid'], [])
item['windows'] = observed
item['desktops'] = sorted({w.get('desktop', '') for w in observed if w.get('desktop')})
item['native_activity'] = native_activity(row['name'], observed, incomplete=error)
item['cancel_prompt'] = (_cancel_question(row['name'], observed, incomplete=error)
item['native_activity'] = native_activity(row['name'], observed)
item['cancel_prompt'] = (_cancel_question(row['name'], observed)
if row['scope_confirmed'] and item.get('force_user_confirmed') is True else None)
if any(name.startswith('Cbb') for name in item['desktops']) and not item['can_close']:
item['detail'] += ';窗口在后台,可查看原生提示并使用已提供的保存/取消操作'
@@ -407,10 +314,7 @@ def _request_close(row, *, stop=None):
identity = _handle_identity(handle)
if identity != {key: row.get(key) for key in ('created_handle', 'image')}:
return {'release_status': 'IDENTITY_CHANGED', 'detail': '进程身份已变化,未关闭'}
snapshot = _process_windows({row['pid']})
windows, error = snapshot.get(row['pid'], []), _window_error(snapshot, row['pid'])
if error:
return {'release_status': 'WAITING', 'detail': '该会话窗口读取不完整,请重新检查:'+error}
windows = _process_windows({row['pid']}).get(row['pid'], [])
if row['name'].casefold() == 'expeditionpcb.exe':
from .failed_session import _startup_snapshot, _cancel_target
for window in windows:
@@ -424,13 +328,10 @@ def _request_close(row, *, stop=None):
return {'release_status': 'RELEASED', 'detail': '已取消启动并退出'}
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
snapshot = _process_windows({row['pid']})
windows, error = snapshot.get(row['pid'], []), _window_error(snapshot, row['pid'])
if error:
break
windows = _process_windows({row['pid']}).get(row['pid'], [])
if close_target(row['name'], windows)[0] is not None: break
break
target, detail = close_target(row['name'], windows, incomplete=error)
target, detail = close_target(row['name'], windows)
if target is None: return {'release_status': 'WAITING', 'detail': detail}
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
@@ -461,9 +362,7 @@ def _force_close(row, *, stop=None):
if (not ownership['force_user_confirmed'] or
any(ownership[k] != row.get(k) for k in ('owner_sid', 'session_id'))):
return {'release_status': 'IDENTITY_CHANGED', 'detail': '用户或 Windows 会话已变化,未结束'}
snapshot = _process_windows({row['pid']})
activity = native_activity(row['name'], snapshot.get(row['pid'], []),
incomplete=_window_error(snapshot, row['pid']))
activity = native_activity(row['name'], _process_windows({row['pid']}).get(row['pid'], []))
if reason := force_block_reason({**row, 'native_activity': activity}):
return {'release_status': 'WAITING', 'detail': reason, 'native_activity': activity}
if stop is not None and stop.is_set():
@@ -493,9 +392,7 @@ def _request_native_cancel(row, *, stop=None):
owner = _force_ownership(handle, row['pid'])
if not owner['force_user_confirmed'] or any(owner[k] != row.get(k) for k in ('owner_sid', 'session_id')):
raise ValueError('取消目标用户/会话已变化')
snapshot = _process_windows({row['pid']})
prompt = _cancel_question(row['name'], snapshot.get(row['pid'], []),
incomplete=_window_error(snapshot, row['pid']))
prompt = _cancel_question(row['name'], _process_windows({row['pid']}).get(row['pid'], []))
if not prompt or prompt != row.get('cancel_prompt'):
raise ValueError('原生取消按钮已变化,请重新检查')
button = prompt['button']
@@ -509,29 +406,10 @@ def _request_native_cancel(row, *, stop=None):
def request_native_cancel(row, library, evidence_dir, *, stop=None):
# Reuse serialized admission, consent and incremental evidence for cancellation.
plan = {'library': str(library), 'sessions': [row], 'block_names': row.get('block_names', [])}
plan = {'library': str(library), 'sessions': [row]}
return release_residual_sessions(plan, evidence_dir, stop=stop, cancel_native=True)
def _session_evidence(row):
"""Keep the full preview in memory, but bound repeatedly written Output."""
value = dict(row)
if 'native_activity' in value:
value['native_activity'] = {k: v for k, v in value['native_activity'].items() if k != 'output'}
if 'windows' in value:
value['windows'] = []
for window in row['windows']:
saved = {k: window[k] for k in ('hwnd', 'title', 'class', 'desktop', 'enabled') if k in window}
output = window.get('output')
if isinstance(output, str):
data = output.encode('utf-8')
saved.update(output_excerpt=data[:4096].decode('utf-8', errors='ignore'),
output_bytes=len(data), output_sha256=hashlib.sha256(data).hexdigest(),
output_truncated=len(data) > 4096)
value['windows'].append(saved)
return value
def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, cancel_native=False):
library = Path(plan['library']).resolve()
root = Path(evidence_dir).resolve()/('sessions-'+uuid4().hex[:12])
@@ -547,7 +425,7 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
from .management import _write_json
try:
result['report_saved'] = True
_write_json(root/'result.json', {**result, 'sessions': [_session_evidence(row) for row in result['sessions']]})
_write_json(root/'result.json', result)
return True
except OSError as error:
result.update(status='PARTIAL', report_saved=False, evidence_error=str(error))
@@ -558,7 +436,7 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
consent_path = root/'consent.json'
consent = {'version': 1, 'mode': 'cancel_native' if cancel_native else 'force_document_clients', 'library': str(library),
'time_ns': time.time_ns(), 'sessions': [
{**_session_evidence(row), 'force_allowed': not force_block_reason(row),
{**row, 'force_allowed': not force_block_reason(row),
'cancel_allowed': bool(row.get('cancel_prompt')) and row.get('scope_confirmed') is True,
'force_block_reason': force_block_reason(row)} for row in plan['sessions']]}
try:
@@ -612,12 +490,10 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
row.update(release_status='RELEASED', detail='已退出')
elif row['release_status'] == 'WAITING':
windows = remaining_windows.get(row['pid'], [])
error = _window_error(remaining_windows, row['pid'])
row.update(prompt=_save_question(windows, incomplete=error), windows=windows,
windows_incomplete=bool(error), window_read_error=error,
cancel_prompt=(_cancel_question(row['name'], windows, incomplete=error)
row.update(prompt=_save_question(windows), windows=windows,
cancel_prompt=(_cancel_question(row['name'], windows)
if row.get('force_user_confirmed') is True else None),
native_activity=native_activity(row['name'], windows, incomplete=error))
native_activity=native_activity(row['name'], windows))
if all(row['release_status'] == 'RELEASED' for row in result['sessions']) and not (stop and stop.is_set()):
result['proof'] = _finish_library_release(library, root/'library-proof')
proof = result['proof']
@@ -678,8 +554,7 @@ def _answer_save_question(row, choice):
with _process_handle(row['pid']) as handle:
if _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}:
raise ValueError('进程已变化,请重新检查')
snapshot = _process_windows({row['pid']})
prompt = _save_question(snapshot.get(row['pid'], []), incomplete=_window_error(snapshot, row['pid']))
prompt = _save_question(_process_windows({row['pid']}).get(row['pid'], []))
if not prompt or prompt != row.get('prompt'):
raise ValueError('原生提示已变化,请重新检查')
button = prompt['buttons'][choice]
+3 -4
View File
@@ -329,12 +329,11 @@ def test_partial_desktop_enumeration_never_offers_normal_close(monkeypatch):
def failed(*_): raise OSError('desktop disappeared')
monkeypatch.setattr(win32gui, 'EnumWindows', failed)
monkeypatch.setattr(win32service, 'GetProcessWindowStation', lambda: SimpleNamespace(EnumDesktops=lambda: []))
snapshot = _process_windows({10})
windows = snapshot[10]
assert snapshot.incomplete[10]
windows = _process_windows({10})[10]
assert any(w['class'] == 'UNCONFIRMED' for w in windows)
windows.append({'hwnd': 100, 'class': 'Afx:main', 'title': 'Design - Expedition PCB',
'children': [], 'enabled': True})
assert close_target('ExpeditionPCB.exe', windows, incomplete=snapshot.incomplete[10])[0] is None
assert close_target('ExpeditionPCB.exe', windows)[0] is None
@pytest.mark.parametrize('choice', [6, 7, 2])
-171
View File
@@ -1,171 +0,0 @@
from contextlib import nullcontext
import json
import sys
import time
from pathlib import Path
from types import SimpleNamespace
from uuid import uuid4
import pytest
from cbb_refresh_verify import residual_sessions as sessions
from test_residual_sessions import row, OWNERSHIP
def window():
return dict(hwnd=100, title='Design - Expedition PCB', desktop='Default',
**{'class': 'Afx:main'}, enabled=True, children=[], documents=[])
class PartialWindows(dict):
incomplete = {10: 'target thread inaccessible'}
def test_thread_read_failure_does_not_poison_another_process(monkeypatch):
import win32gui, win32process, win32service
def global_failure(*args):
raise OSError('an unrelated desktop is inaccessible')
monkeypatch.setattr(win32gui, 'EnumWindows', global_failure)
monkeypatch.setattr(win32service, 'GetProcessWindowStation',
lambda: SimpleNamespace(EnumDesktops=lambda: ['Default', 'CbbManagement_Unrelated']))
monkeypatch.setattr(sessions, '_process_threads', lambda _: {10: [100], 20: [200]}, raising=False)
monkeypatch.setattr(sessions, '_thread_desktop_name',
lambda tid: 'Default' if tid == 100 else 'CbbManagement_Broken', raising=False)
def open_desktop(name, *args):
if name == 'CbbManagement_Broken':
raise PermissionError('only process 20 is unreadable')
assert name == 'Default', 'an unrelated desktop must not be inspected'
return SimpleNamespace(EnumDesktopWindows=lambda: [1000], CloseDesktop=lambda: None)
monkeypatch.setattr(win32service, 'OpenDesktop', open_desktop)
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda _: (100, 10))
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda _: True)
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda *args: None)
monkeypatch.setattr(win32gui, 'GetWindowText', lambda _: 'Design - Expedition PCB')
monkeypatch.setattr(win32gui, 'GetClassName', lambda _: 'Afx:main')
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda _: True)
monkeypatch.setattr(win32gui, 'GetWindowRect', lambda _: (0, 0, 100, 100))
result = sessions._process_windows({10, 20})
assert [w['hwnd'] for w in result[10]] == [1000]
assert 10 not in result.incomplete and 'unreadable' in result.incomplete[20]
assert result[20] == [], 'a read error must not be represented as a native modal window'
assert sessions.close_target('ExpeditionPCB.exe', result[10])[0]
def test_preview_exposes_only_target_process_incomplete_state(tmp_path, monkeypatch):
library = tmp_path/'lib.lmc'; library.touch()
processes = [row(pid, tmp_path/f'ReusableBlocksLP/{pid}/Work/{pid}.prj', name='ExpeditionPCB.exe')
for pid in (10, 20)]
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: processes)
monkeypatch.setattr(sessions, '_process_identity', lambda r: dict(created_handle='creation',
image=r['executable'], **OWNERSHIP))
monkeypatch.setattr(sessions, '_process_windows', lambda _: PartialWindows({10: [window()], 20: [window()]}))
affected, healthy = sessions.inspect_residual_sessions(library)['sessions']
assert affected['windows_incomplete'] and not affected['can_close'] and not affected['force_allowed']
assert affected['native_activity']['status'] == 'UNCONFIRMED'
assert '读取' in affected['detail'] and '弹窗' not in affected['detail']
assert healthy['can_close'] and healthy['force_allowed']
def test_action_rechecks_incomplete_read_before_force_termination(monkeypatch):
import win32api, win32con, win32event
process = dict(row(10, 'C:/library/A.prj', name='ExpeditionPCB.exe'),
created_handle='creation', image='C:/Mentor/ExpeditionPCB.exe', scope_confirmed=True, **OWNERSHIP)
monkeypatch.setattr(sessions, '_process_handle', lambda *a, **kw: nullcontext(123))
monkeypatch.setattr(sessions, '_handle_identity', lambda _: {k: process[k] for k in ('created_handle', 'image')})
monkeypatch.setattr(sessions, '_force_ownership', lambda *args: dict(OWNERSHIP))
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *args: win32con.WAIT_TIMEOUT)
monkeypatch.setattr(sessions, '_process_windows', lambda _: PartialWindows({10: [window()]}))
monkeypatch.setattr(win32api, 'TerminateProcess', lambda *args: pytest.fail('unreadable target was ended'))
result = sessions._force_close(process)
assert result['release_status'] == 'WAITING' and result['native_activity']['status'] == 'UNCONFIRMED'
def test_identity_read_failure_keeps_the_other_preview_row_available(tmp_path, monkeypatch):
library = tmp_path/'lib.lmc'; library.touch()
processes = [row(pid, tmp_path/f'ReusableBlocksLP/{pid}/Work/A.prj', name='ExpeditionPCB.exe')
for pid in (10, 20)]
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: processes)
def identity(process):
if process['pid'] == 10:
raise PermissionError('token inaccessible')
return dict(created_handle='creation', image=process['executable'], **OWNERSHIP)
monkeypatch.setattr(sessions, '_process_identity', identity)
monkeypatch.setattr(sessions, '_process_windows', lambda _: {pid: [window()] for pid in (10, 20)})
affected, healthy = sessions.inspect_residual_sessions(library)['sessions']
assert not affected['force_allowed'] and 'token inaccessible' in affected['detail']
assert healthy['force_allowed'] and healthy['can_close']
def test_native_cancel_retains_exact_preview_scope(tmp_path, monkeypatch):
from cbb_refresh_verify import library_lock
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
process = dict(row(10, library.parent/'ReusableBlocksLP/A/Work/A.prj'),
scope_confirmed=True, block_names=['A'], cancel_prompt={'hwnd': 100})
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process])
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
expected = (library.parent/'ReusableBlocksLP/A/Work', library.parent/'SymbolLibs')
def scoped(actual, selected_library, roots):
assert roots == expected, 'Cancel widened the scope from its preview'
return True
monkeypatch.setattr(library_lock, '_owner_matches_scope', scoped)
monkeypatch.setattr(sessions, '_request_native_cancel', lambda *a, **kw:
dict(release_status='WAITING', detail='cancel requested'))
result = sessions.request_native_cancel(process, library, tmp_path/'evidence')
assert result['sessions'][0]['detail'] == 'cancel requested'
def test_persisted_release_evidence_is_bounded_without_changing_preview(tmp_path, monkeypatch):
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
output = '原生输出' * 100000
observed = dict(window(), output=output, children=[dict(text=output, **{'class': 'RichEdit'})])
process = dict(row(10, library.parent/'ReusableBlocksLP/A/Work/A.prj', name='ExpeditionPCB.exe'),
created_handle='creation', image='C:/Mentor/ExpeditionPCB.exe', scope_confirmed=True,
windows=[observed], native_activity={'status': 'IDLE', 'output': output}, **OWNERSHIP)
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process])
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
monkeypatch.setattr(sessions, '_force_close', lambda *a, **kw: dict(release_status='RELEASED', detail='ended'))
monkeypatch.setattr(sessions, '_finish_library_release', lambda *args:
dict(status='RELEASE_CONFIRMED', library=str(library)))
result = sessions.release_residual_sessions(dict(library=str(library), sessions=[process]),
tmp_path/'evidence', force=True)
assert result['status'] == 'RELEASE_CONFIRMED'
for path in (Path(result['evidence_path']), Path(result['consent_path'])):
assert path.stat().st_size < 20000
saved = json.loads(path.read_text('utf-8'))['sessions'][0]
assert 'output' not in saved['native_activity']
assert 'children' not in saved['windows'][0] and 'output' not in saved['windows'][0]
assert len(saved['windows'][0]['output_excerpt'].encode('utf-8')) <= 4096
assert saved['windows'][0]['output_truncated'] is True
assert process['windows'][0]['output'] == output
def test_real_private_desktop_is_read_through_its_process_threads(tmp_path):
from cbb_refresh_verify.desktop_worker import DesktopWorker
ready, stop = tmp_path/'ready.json', tmp_path/'stop'
script = tmp_path/'window.py'
name = 'CbbManagement_Review_'+uuid4().hex[:10]
script.write_text('import json,time,win32api,win32con,win32gui\nfrom pathlib import Path\n'
'wc=win32gui.WNDCLASS()\nwc.hInstance=win32api.GetModuleHandle(None)\n'
'wc.lpszClassName="CbbReviewWindow"\nwc.lpfnWndProc=win32gui.DefWindowProc\n'
'atom=win32gui.RegisterClass(wc)\n'
'hwnd=win32gui.CreateWindow(atom,"Controlled review fixture",'
'win32con.WS_OVERLAPPEDWINDOW|win32con.WS_VISIBLE,0,0,300,200,0,0,wc.hInstance,None)\n'
f'Path({str(ready)!r}).write_text(json.dumps(dict(hwnd=hwnd)))\n'
f'while not Path({str(stop)!r}).exists():\n'
' win32gui.PumpWaitingMessages();time.sleep(.02)\n'
'win32gui.DestroyWindow(hwnd)\n', encoding='utf-8')
worker = DesktopWorker([sys.executable, str(script)], name)
try:
deadline = time.monotonic()+8
while not ready.exists() and worker.poll() is None and time.monotonic()<deadline:
time.sleep(.02)
assert ready.exists()
hwnd = json.loads(ready.read_text())['hwnd']
snapshot = sessions._process_windows({worker.pid})
assert worker.pid not in snapshot.incomplete, snapshot.incomplete
target = next(w for w in snapshot[worker.pid] if w['hwnd'] == hwnd)
assert target['desktop'] == name and target['title'] == 'Controlled review fixture'
finally:
stop.touch()
worker.wait(5)
worker.close()
@@ -1,52 +0,0 @@
import json
from pathlib import Path
import pytest
from cbb_refresh_verify import library_lock as locks
@pytest.mark.parametrize('retained_owner', [False, True])
def test_releasing_another_blocks_checkpoint_names_its_owner(tmp_path, monkeypatch, retained_owner):
library = tmp_path/'library/lib.lmc'
library.parent.mkdir(); library.touch()
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
lease = None
if retained_owner:
with locks.LibraryLock(library, block_name='BlockB', safe_to_release=lambda: False) as lease:
pass
else:
locks._persist_blocker(library, lease_id='b'*32, block_name='BlockB')
before = locks.blocker_path(library).read_bytes()
try:
proof = locks.release_retained_library(library, tmp_path/'evidence', block_name='BlockA')
assert proof['requested_block_name'] == 'BlockA'
assert proof['proof_scope'] == 'LIBRARY'
assert proof['reconciled_foreign_blockers'] == ['BlockB']
assert proof['data_recovery_confirmed'] is False
checkpoint = next(r for r in proof['reconciled_checkpoints'] if r['kind'] == 'checkpoint')
assert checkpoint['block_name'] == 'BlockB' and checkpoint['status'] == 'OWNER_RELEASE_UNCONFIRMED'
assert checkpoint['lease_id']
proof_path = Path(proof['evidence_path'])
assert json.loads(proof_path.read_text('utf-8'))['reconciled_foreign_blockers'] == ['BlockB']
assert (proof_path.parent/'blocker-before-0.json').read_bytes() == before
assert not locks.blocker_path(library).exists()
if retained_owner:
assert any(r['kind'] == 'retained_owner' and r['block_name'] == 'BlockB'
for r in proof['reconciled_checkpoints'])
finally:
if lease:
with locks._guard:
owner = locks._owners.pop(lease.key, None)
if owner:
owner['handle'].Close()
def test_matching_checkpoint_uses_block_scope_without_foreign_targets(tmp_path, monkeypatch):
library = tmp_path/'library/lib.lmc'
library.parent.mkdir(); library.touch()
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
locks._persist_blocker(library, lease_id='a'*32, block_name='BlockA')
proof = locks.release_retained_library(library, tmp_path/'evidence', block_name='BlockA')
assert proof['proof_scope'] == 'BLOCK' and proof['proof_block_name'] == 'BlockA'
assert proof['reconciled_foreign_blockers'] == []