Import CBB refresh verify r4 stability baseline
Preserve tested Verify source, authoritative READY checks, bounded bridge retries, diagnostics and failure-only reporting. Include 336-test suite and packaging assets; exclude live Mentor samples, field logs, backups and distributions.
This commit is contained in:
commit
11a2b2e46e
130 files changed
+19267
No files matched your search
@@ -0,0 +1,224 @@
|
||||
"""Declarative, phase-aware rules for Mentor dialog decisions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, fields, replace
|
||||
import json
|
||||
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 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)))
|
||||
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 "无标题窗口",
|
||||
)
|
||||
Reference in new issue
Block a user