Files
cbb-refresh-verify-795/src/cbb_refresh_verify/dialog_rules.py
T

277 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Declarative, phase-aware rules for Mentor dialog decisions."""
from __future__ import annotations
from dataclasses import dataclass, fields, replace
import json
import re
from pathlib import Path
import sys
from typing import Any, Sequence
from .dialog_models import DialogPhase, RuleDecision, WindowSnapshot, normalize_text
class RuleConfigError(ValueError):
pass
def default_rules_path() -> Path:
source = Path(__file__).resolve().parent / "assets" / "dialog_rules.v1.json"
frozen = Path(getattr(sys, "_MEIPASS", source.parent.parent)) / "cbb_refresh_verify" / "assets" / "dialog_rules.v1.json"
return frozen if frozen.is_file() else source
_CATEGORIES = {"OBSERVE_PROGRESS", "SAFE_RECOVERY", "SAFE_CONFIRM", "FATAL_ACK"}
_CHANNELS = {"interface", "uia_invoke", "uia_select", "uia_toggle", "win32_button_click", "win32_mouse_click"}
_POSTCONDITIONS = {"", "window_gone", "control_selected", "control_enabled", "signature_changed", "next_phase"}
@dataclass(frozen=True)
class DialogRule:
rule_id: str
priority: int
category: str
phases: tuple[DialogPhase, ...]
enabled: bool = True
process_names: tuple[str, ...] = ()
process_roles: tuple[str, ...] = ()
window_classes: tuple[str, ...] = ()
semantic_all: tuple[str, ...] = ()
semantic_any: tuple[str, ...] = ()
semantic_none: tuple[str, ...] = ()
required_control_types: tuple[str, ...] = ()
required_control_classes: tuple[str, ...] = ()
action: str = ""
channels: tuple[str, ...] = ()
target: tuple[tuple[str, object], ...] = ()
postcondition: str = ""
error_code: str = ""
def _tuple_strings(value: Any) -> tuple[str, ...]:
if value is None:
return ()
if not isinstance(value, list):
raise RuleConfigError("规则列表字段必须是 JSON array")
return tuple(str(item) for item in value)
def _parse_rule(raw: dict[str, Any]) -> DialogRule:
known = {field.name for field in fields(DialogRule)}
unknown = set(raw) - known
if unknown:
raise RuleConfigError(f"规则包含未知字段: {', '.join(sorted(unknown))}")
try:
phases = tuple(DialogPhase(value) for value in raw["phases"])
target_value = raw.get("target", {})
if not isinstance(target_value, dict):
raise RuleConfigError("target 必须是 JSON object")
rule = DialogRule(
rule_id=str(raw["rule_id"]),
priority=int(raw["priority"]),
category=str(raw["category"]),
phases=phases,
enabled=bool(raw.get("enabled", True)),
process_names=_tuple_strings(raw.get("process_names")),
process_roles=_tuple_strings(raw.get("process_roles")),
window_classes=_tuple_strings(raw.get("window_classes")),
semantic_all=_tuple_strings(raw.get("semantic_all")),
semantic_any=_tuple_strings(raw.get("semantic_any")),
semantic_none=_tuple_strings(raw.get("semantic_none")),
required_control_types=_tuple_strings(raw.get("required_control_types")),
required_control_classes=_tuple_strings(raw.get("required_control_classes")),
action=str(raw.get("action", "")),
channels=_tuple_strings(raw.get("channels")),
target=tuple(sorted(target_value.items())),
postcondition=str(raw.get("postcondition", "")),
error_code=str(raw.get("error_code", "")),
)
except (KeyError, TypeError, ValueError) as error:
if isinstance(error, RuleConfigError):
raise
raise RuleConfigError(f"无效规则: {raw.get('rule_id', '<missing>')}: {error}") from error
if not rule.rule_id or not rule.phases:
raise RuleConfigError("rule_id 和 phases 不能为空")
if rule.category not in _CATEGORIES:
raise RuleConfigError(f"未知 category: {rule.category}")
unknown_channels = set(rule.channels) - _CHANNELS
if unknown_channels:
raise RuleConfigError(f"未知 action channel: {', '.join(sorted(unknown_channels))}")
if rule.postcondition not in _POSTCONDITIONS:
raise RuleConfigError(f"未知 postcondition: {rule.postcondition}")
return rule
def _read_document(path: Path) -> list[dict[str, Any]]:
try:
document = json.loads(Path(path).read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as error:
raise RuleConfigError(f"无法读取规则 {path}: {error}") from error
if document.get("schema_version") != 1:
raise RuleConfigError(f"不支持的 schema_version: {document.get('schema_version')}")
rules = document.get("rules")
if not isinstance(rules, list):
raise RuleConfigError("rules 必须是 JSON array")
return rules
def load_rules(default_path: Path, override_path: Path | None = None) -> tuple[DialogRule, ...]:
ordered: list[str] = []
raw_by_id: dict[str, dict[str, Any]] = {}
for raw in _read_document(default_path):
rule_id = str(raw.get("rule_id", ""))
if not rule_id or rule_id in raw_by_id:
raise RuleConfigError(f"默认规则 ID 重复或为空: {rule_id}")
ordered.append(rule_id)
raw_by_id[rule_id] = dict(raw)
if override_path is not None and Path(override_path).is_file():
seen: set[str] = set()
for override in _read_document(override_path):
rule_id = str(override.get("rule_id", ""))
if not rule_id or rule_id in seen:
raise RuleConfigError(f"现场规则 ID 重复或为空: {rule_id}")
seen.add(rule_id)
if rule_id in raw_by_id:
raw_by_id[rule_id].update(override)
else:
ordered.append(rule_id)
raw_by_id[rule_id] = dict(override)
return tuple(_parse_rule(raw_by_id[rule_id]) for rule_id in ordered)
def _semantic_text(snapshot: WindowSnapshot) -> str:
return normalize_text(" ".join((snapshot.title, *snapshot.texts)))
def _matches(rule: DialogRule, snapshot: WindowSnapshot, *, include_phase: bool) -> bool:
if not rule.enabled:
return False
if include_phase and snapshot.phase not in rule.phases:
return False
if rule.process_names and snapshot.process_name.casefold() not in {v.casefold() for v in rule.process_names}:
return False
if rule.process_roles and snapshot.process_role.casefold() not in {v.casefold() for v in rule.process_roles}:
return False
if rule.window_classes and snapshot.window_class.casefold() not in {v.casefold() for v in rule.window_classes}:
return False
semantic = _semantic_text(snapshot)
all_tokens = tuple(normalize_text(value) for value in rule.semantic_all)
any_tokens = tuple(normalize_text(value) for value in rule.semantic_any)
none_tokens = tuple(normalize_text(value) for value in rule.semantic_none)
if any(token not in semantic for token in all_tokens):
return False
if any_tokens and not any(token in semantic for token in any_tokens):
return False
if any(token in semantic for token in none_tokens):
return False
control_types = {control.control_type.casefold() for control in snapshot.controls}
control_classes = {control.class_name.casefold() for control in snapshot.controls}
if not {value.casefold() for value in rule.required_control_types}.issubset(control_types):
return False
if not {value.casefold() for value in rule.required_control_classes}.issubset(control_classes):
return False
return True
def _decision(rule: DialogRule) -> RuleDecision:
return RuleDecision(
rule_id=rule.rule_id,
category=rule.category,
action=rule.action,
channels=rule.channels,
target=rule.target,
postcondition=rule.postcondition,
error_code=rule.error_code if rule.category == "FATAL_ACK" else "",
)
def pcb_version_choice(snapshot):
"""Describe the captured native choice; never select or approve a version."""
if (snapshot.title != 'Database Restoration' or snapshot.window_class != '#32770'
or snapshot.process_name.casefold() != 'expeditionpcb.exe' or snapshot.process_role != 'pcb'
or snapshot.phase != DialogPhase.PCB_STARTING):
return None
explanation = ('The system has detected this design abnormally terminated the last time it was used. '
'The user has to decide what database (if any) to associate with the design.')
if not any(c.control_id == 6208 and ' '.join(c.name.split()) == explanation for c in snapshot.controls):
return None
candidates = []
for identifier, kind, prefix in ((6213, 'last_user_saved', 'Load the last user saved database dated '),
(6206, 'autosave', 'Load the autosave database dated ')):
controls = [c for c in snapshot.controls if c.control_id == identifier and c.class_name == 'Button']
if len(controls) != 1: return None
control = controls[0]
match = re.fullmatch(re.escape(prefix) + r'(.+)\.', ' '.join(control.name.split()))
if not match: return None
candidates.append({'kind': kind, 'control_id': identifier, 'label': control.name,
'date': match.group(1), 'enabled': control.enabled,
'selected': control.selected or control.checked})
return {'candidates': candidates, 'automatic_selection': False}
def archive_version_choice(snapshot, root):
choice = pcb_version_choice(snapshot)
if choice is None: raise ValueError('Not the recognized native PCB version choice')
path = Path(root)/'pcb-version-choice.json'
path.write_text(json.dumps({**choice, 'snapshot': snapshot.to_record()},
ensure_ascii=False, indent=2), encoding='utf-8')
return path
def decide(snapshot: WindowSnapshot, rules: Sequence[DialogRule]) -> RuleDecision:
# Windows Text Services Framework language-bar window exposed by Mentor's
# process is not a Mentor modal: it has no controls and must not abort a run.
if (snapshot.window_class.casefold() == 'cicerouiwndframe'
and normalize_text(snapshot.title) == 'tf_floatinglangbar_wndtitle'
and not snapshot.controls):
return RuleDecision(rule_id='ime-floating-language-bar', category='OBSERVE_PROGRESS')
combined = normalize_text(' '.join((snapshot.title, *snapshot.texts)))
from .icdb_recovery import ERROR_CODE, parse_session_loss
if parse_session_loss(combined):
return RuleDecision(error_code=ERROR_CODE,
detail=' | '.join(snapshot.texts) or snapshot.title)
choice = pcb_version_choice(snapshot)
if choice is not None:
labels = {'last_user_saved': '最后用户保存', 'autosave': '自动保存'}
detail = ';'.join(f'{labels[c["kind"]]}:{c["date"]}' for c in choice['candidates'])
return RuleDecision(error_code='PCB_VERSION_CHOICE_REQUIRED',
detail=f'PCB需选择恢复版本,尚未校验通过。候选版本:{detail}。未自动选择或确认任何版本。')
# These prompts require knowledge of database ownership or a recovery
# choice. A generic Yes/restore rule cannot establish either fact.
if any(marker in combined for marker in (
'continue to open the design with read/write access permission',
'confirm that no other users have the design open',
'database restoration', 'last user saved database', '数据库恢复')):
return RuleDecision(error_code='DATABASE_RECOVERY_REQUIRED',
detail=' | '.join(snapshot.texts) or snapshot.title)
if ('problem encountered while opening one of the database files' in combined
and 'loading of the job has failed' in combined):
return RuleDecision(
rule_id='mentor-database-open-failed', category='FATAL_ACK',
action='acknowledge_fatal',
channels=('win32_button_click', 'uia_invoke'),
target=(('control_id', 7),), postcondition='window_gone',
error_code='MENTOR_DATABASE_LOAD_FAILED', detail=' | '.join(snapshot.texts))
matches = [rule for rule in rules if _matches(rule, snapshot, include_phase=True)]
if matches:
best_priority = max(rule.priority for rule in matches)
best = [rule for rule in matches if rule.priority == best_priority]
if len(best) != 1:
ids = ", ".join(sorted(rule.rule_id for rule in best))
return RuleDecision(error_code="DIALOG_RULE_CONFLICT", detail=f"同优先级规则冲突: {ids}")
return _decision(best[0])
out_of_phase = [rule for rule in rules if _matches(rule, snapshot, include_phase=False)]
if out_of_phase:
best = max(out_of_phase, key=lambda rule: rule.priority)
return RuleDecision(
rule_id=best.rule_id,
category=best.category,
error_code="DIALOG_OUT_OF_PHASE",
detail=f"规则 {best.rule_id} 不允许在阶段 {snapshot.phase.value} 执行",
)
return RuleDecision(
error_code="UNKNOWN_DIALOG",
detail=" | ".join(snapshot.texts) or snapshot.title or "无标题窗口",
)