Coverage for app / services / rules / summary.py: 81%
27 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2What a rule does, in words — the lines a rule's card and page show.
4Each registered action says what its own block does (``Action.summarise``):
5"Caps spend at $100 a month", "Redacts email addresses from the prompt". A
6rule's summaries are its actions' in order, so the Rules page reads as what
7the rules do rather than as "1 condition · 2 actions".
9An action its layer does not carry is said to do nothing, because the engine
10skips it (``rule_engine._apply_text_actions``) — a card claiming it blocks
11would be the one place the rule looked enforced.
12"""
14from __future__ import annotations
16import logging
17from typing import Any
19from app.db.postgres.enums import RuleEnum
20from app.services.rules import actions as action_registry
21from app.services.rules import layers as layer_registry
23logger = logging.getLogger(__name__)
26def summaries(layer: RuleEnum.Layer | str | None, actions: Any) -> list[str]:
27 """One line per action block of a rule in ``layer``, in order."""
28 try:
29 registered_layer = layer_registry.get(layer).key if layer else None
30 except (ValueError, KeyError):
31 registered_layer = None
32 lines: list[str] = []
33 for block in actions if isinstance(actions, list) else []:
34 if not isinstance(block, dict):
35 continue
36 action_type = str(block.get("type", ""))
37 action = (
38 action_registry.get_action(registered_layer, action_type)
39 if registered_layer is not None
40 else None
41 )
42 if action is None:
43 lines.append(f"Does nothing: '{action_type}' is not an action here")
44 continue
45 try:
46 lines.append(action.summarise(block))
47 except Exception: # a card must not fail on one block
48 logger.exception("Could not summarise a %s action", action_type)
49 lines.append(action.label)
50 return lines