feat: define independent verification contracts and verdicts

This commit is contained in:
阿白叔 committed 2026-11-17 15:19:38 +08:00
1 parent dbb264f679
commit 0406028a02
3 files changed
+189

No files matched your search

@@ -0,0 +1 @@
"""Independent, read-only project verification and traceable evidence."""
@@ -0,0 +1,109 @@
"""Versioned input contracts and conclusions independent of execution status."""
import copy
import hashlib
import json
import re
from ..errors import TaskCenterError
CHECKS = frozenset(('inputs','coverage','components','physical_pins','connections','net_names',
'declared_attributes','attribute_changes','pin_text','pin_semantics','footprint_mapping','export_identity'))
STATES = frozenset(('equal','expected_change','warning','error','unknown','not_requested'))
ACTIVE = ('queued','running','publishing','stopping')
TERMINAL = ('succeeded','failed','cancelled','interrupted')
def fail(message, code='verification_input'):
raise TaskCenterError(code, message)
def digest(value):
return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False,
separators=(',', ':'), allow_nan=False).encode('utf-8')).hexdigest()
def identifier(value):
if not isinstance(value, str) or not value.strip() or len(value) > 256 or any(ord(c) < 32 for c in value):
fail('标识不能为空或包含控制字符。')
return value
def artifact_ref(value):
if value is None:
return None
if (not isinstance(value, dict) or set(value) != {'manifest_id','sha256'}
or re.fullmatch('[0-9a-f]{32}', str(value['manifest_id'])) is None
or re.fullmatch('[0-9a-f]{64}', str(value['sha256'])) is None):
fail('校验证据引用无效。')
return dict(value)
def default_plan():
return {'policy_version': 'verification-v1',
'required_checks': ['inputs','coverage','components','physical_pins','connections','net_names'],
'optional_checks': ['attribute_changes','pin_text','pin_semantics','export_identity'],
'excluded_checks': ['footprint_mapping']}
def validate_plan(plan):
if not isinstance(plan, dict) or set(plan) != {'policy_version','required_checks','optional_checks','excluded_checks'}:
fail('检查计划字段不完整。')
if plan['policy_version'] != 'verification-v1':
fail('不支持的校验策略版本。')
groups = [plan[key] for key in ('required_checks','optional_checks','excluded_checks')]
if any(not isinstance(group, (list,tuple)) for group in groups):
fail('检查范围必须为列表。')
flat = [key for group in groups for key in group]
if not groups[0] or any(not isinstance(key,str) or key not in CHECKS for key in flat) or len(set(flat)) != len(flat):
fail('检查范围为空、重复或包含未知项目。')
return copy.deepcopy(plan)
def validate_input(value):
allowed = {'item_key','project_key','input_version','before_ref','after_ref','expectation_ref',
'check_plan','display_name','unavailable_reason'}
required = {'item_key','project_key','input_version','before_ref','after_ref','expectation_ref','check_plan'}
if not isinstance(value,dict) or set(value) - allowed or not required <= set(value):
fail('校验输入字段不完整或包含不支持字段。')
result = copy.deepcopy(value)
for key in ('item_key','project_key'):
identifier(result[key])
if type(result['input_version']) is not int or not 1 <= result['input_version'] <= 2**31-1:
fail('输入版本必须为正整数。')
for key in ('before_ref','after_ref','expectation_ref'):
result[key] = artifact_ref(result[key])
result['check_plan'] = validate_plan(result['check_plan'])
result['display_name'] = identifier(result.get('display_name') or result['project_key'])
reason = result.get('unavailable_reason','')
if not isinstance(reason,str) or len(reason)>4000:
fail('不可用原因无效。')
if not result['before_ref'] or not result['after_ref']:
reason = reason or '缺少替换前或替换后的可信副本。'
result.update(input_state='unavailable' if reason else 'ready', unavailable_reason=reason)
result['payload_digest'] = digest(result)
return result
def rollup_results(checks, *, required_checks, optional_checks=()):
if not required_checks or any(key not in CHECKS for key in (*required_checks,*optional_checks)):
fail('必查项目不能为空。', 'verification_check_plan')
states = {}
for row in checks:
key, state = row.get('check_id'), row.get('state')
if key not in CHECKS or state not in STATES or key in states:
fail('检查结果包含重复或未知项目。', 'verification_result')
states[key] = state
requested = tuple(dict.fromkeys((*required_checks,*optional_checks)))
unknown = [key for key in requested if states.get(key, 'unknown') in {'unknown','not_requested'}]
if any(state=='error' for state in states.values()):
verdict = 'DIFFERENT'
elif any(states.get(key,'unknown') in {'unknown','not_requested'} for key in required_checks):
verdict = 'INCOMPLETE'
elif any(state=='warning' for state in states.values()):
verdict = 'WARNING'
else:
verdict = 'CONSISTENT'
return {'verdict': verdict, 'coverage': 'partial' if unknown else 'complete',
'unknown_checks': unknown, 'checked': [key for key in requested if key not in unknown],
'warnings': sum(state=='warning' for state in states.values()),
'errors': sum(state=='error' for state in states.values())}