|
| 1 | +"""Declarative event rule matching (sync + async parity with CDK evaluator).""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from dataclasses import dataclass, field |
| 6 | +from typing import Any |
| 7 | + |
| 8 | + |
| 9 | +@dataclass(frozen=True) |
| 10 | +class EventRule: |
| 11 | + """One event governance rule from blueprint or registry pack.""" |
| 12 | + |
| 13 | + id: str |
| 14 | + on: str |
| 15 | + action: str |
| 16 | + mode: str |
| 17 | + evaluation: str |
| 18 | + when: dict[str, Any] = field(default_factory=dict) |
| 19 | + reason: str = "" |
| 20 | + severity: str = "medium" |
| 21 | + timeout_s: int | None = None |
| 22 | + notify_channels: list[str] = field(default_factory=list) |
| 23 | + rule_pack_id: str | None = None |
| 24 | + |
| 25 | + |
| 26 | +def _event_name(event_type: str, metadata: dict[str, Any]) -> str: |
| 27 | + """Resolve the rule ``on`` key for an incoming event.""" |
| 28 | + if event_type == "agent_milestone": |
| 29 | + milestone = metadata.get("milestone") |
| 30 | + if isinstance(milestone, str): |
| 31 | + return milestone |
| 32 | + checkpoint = metadata.get("checkpoint") |
| 33 | + if isinstance(checkpoint, str): |
| 34 | + return checkpoint |
| 35 | + return event_type |
| 36 | + |
| 37 | + |
| 38 | +def _fields_match(rule_when: dict[str, Any], metadata: dict[str, Any]) -> bool: |
| 39 | + expected = rule_when.get("fields") |
| 40 | + if not expected: |
| 41 | + return True |
| 42 | + if not isinstance(expected, dict): |
| 43 | + return False |
| 44 | + for key, want in expected.items(): |
| 45 | + got = metadata.get(key) |
| 46 | + if got != want: |
| 47 | + return False |
| 48 | + return True |
| 49 | + |
| 50 | + |
| 51 | +def _aggregate_match( |
| 52 | + rule_when: dict[str, Any], |
| 53 | + metadata: dict[str, Any], |
| 54 | + aggregate_state: dict[str, Any] | None, |
| 55 | +) -> bool: |
| 56 | + agg = rule_when.get("aggregate") |
| 57 | + if not agg: |
| 58 | + return True |
| 59 | + if not isinstance(agg, dict): |
| 60 | + return False |
| 61 | + cost_gte = agg.get("cost_usd_gte") |
| 62 | + if cost_gte is not None: |
| 63 | + cumulative = aggregate_state.get("cumulative_cost_usd") if aggregate_state else None |
| 64 | + if cumulative is None: |
| 65 | + cumulative = metadata.get("cumulative_cost_usd") |
| 66 | + if cumulative is None: |
| 67 | + return False |
| 68 | + try: |
| 69 | + if float(cumulative) < float(cost_gte): |
| 70 | + return False |
| 71 | + except (TypeError, ValueError): |
| 72 | + return False |
| 73 | + turn_gte = agg.get("turn_count_gte") |
| 74 | + if turn_gte is not None: |
| 75 | + turns = aggregate_state.get("turn_count") if aggregate_state else None |
| 76 | + if turns is None: |
| 77 | + turns = metadata.get("turn_count") |
| 78 | + if turns is None: |
| 79 | + return False |
| 80 | + try: |
| 81 | + if float(turns) < float(turn_gte): |
| 82 | + return False |
| 83 | + except (TypeError, ValueError): |
| 84 | + return False |
| 85 | + return True |
| 86 | + |
| 87 | + |
| 88 | +def match_rules( |
| 89 | + rules: list[EventRule], |
| 90 | + *, |
| 91 | + event_type: str, |
| 92 | + metadata: dict[str, Any], |
| 93 | + evaluation: str | None = None, |
| 94 | + aggregate_state: dict[str, Any] | None = None, |
| 95 | +) -> list[EventRule]: |
| 96 | + """Return rules that match the given event.""" |
| 97 | + name = _event_name(event_type, metadata) |
| 98 | + matched: list[EventRule] = [] |
| 99 | + for rule in rules: |
| 100 | + if rule.on != name: |
| 101 | + continue |
| 102 | + if evaluation is not None and rule.evaluation != evaluation: |
| 103 | + continue |
| 104 | + when = rule.when or {} |
| 105 | + if not _fields_match(when, metadata): |
| 106 | + continue |
| 107 | + if not _aggregate_match(when, metadata, aggregate_state): |
| 108 | + continue |
| 109 | + matched.append(rule) |
| 110 | + return matched |
| 111 | + |
| 112 | + |
| 113 | +def parse_rules( |
| 114 | + raw: list[dict[str, Any]] | None, |
| 115 | + *, |
| 116 | + rule_pack_id: str | None = None, |
| 117 | +) -> list[EventRule]: |
| 118 | + """Parse blueprint/registry rule dicts into ``EventRule`` instances.""" |
| 119 | + if not raw: |
| 120 | + return [] |
| 121 | + out: list[EventRule] = [] |
| 122 | + for item in raw: |
| 123 | + if not isinstance(item, dict) or not item.get("id"): |
| 124 | + continue |
| 125 | + out.append( |
| 126 | + EventRule( |
| 127 | + id=str(item["id"]), |
| 128 | + on=str(item["on"]), |
| 129 | + action=str(item.get("action", "observe_only")), |
| 130 | + mode=str(item.get("mode", "observe_only")), |
| 131 | + evaluation=str(item.get("evaluation", "sync")), |
| 132 | + when=dict(item.get("when") or {}), |
| 133 | + reason=str(item.get("reason") or ""), |
| 134 | + severity=str(item.get("severity") or "medium"), |
| 135 | + timeout_s=item.get("timeout_s"), |
| 136 | + notify_channels=list(item.get("notify_channels") or []), |
| 137 | + rule_pack_id=rule_pack_id or item.get("rule_pack_id"), |
| 138 | + ) |
| 139 | + ) |
| 140 | + return out |
0 commit comments