Coverage for app / services / rules / layers.py: 97%

66 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1""" 

2Rule layers — where in a request a rule acts, in the order a request meets them. 

3 

4A rule belongs to one layer, and the layer decides three things: what the 

5rule's conditions can see (the phase whose fields the builder offers), which 

6actions it may carry (``actions``, registered per layer), and when the engine 

7runs it. One class per layer, registered with :func:`register_layer`, and 

8served to the rule builder in the catalogue (``catalogue.build``) with its 

9label and the question it answers — so the Rules page's flow strip, its 

10sections and the builder's layer picker are this registry, not a list kept 

11beside it. 

12 

13Order is the enum's (``RuleEnum.Layer``), which is the order a request meets 

14them: whether it may run at all, what the model reads, where it may look 

15things up, then what people receive. Within a layer, rules run by priority, then by how narrowly each is 

16aimed (``rule_engine._get_applicable_rules``). 

17 

18These replaced the rule *types* (policy / routing / audit) in migration 105: 

19names for what a rule does to a request rather than for the engine's two 

20passes. Routing rules had already gone (migration 104). The Tools layer came 

21with migration 106. 

22""" 

23 

24from __future__ import annotations 

25 

26from abc import ABC 

27from typing import Any, ClassVar 

28 

29from app.db.postgres.enums import RuleEnum 

30from app.services.rules.fields import Phase 

31 

32 

33class Layer(ABC): 

34 """One layer of a request a rule can act in.""" 

35 

36 #: The stored value (``rules.layer``). 

37 key: ClassVar[RuleEnum.Layer] 

38 #: The name the Rules page and the builder show. 

39 label: ClassVar[str] 

40 #: The question the layer's rules answer, in a few words. 

41 summary: ClassVar[str] 

42 #: One sentence: when its rules run and what they can do. 

43 description: ClassVar[str] 

44 #: When its conditions are evaluated, and so which fields they can see. 

45 phase: ClassVar[Phase] 

46 

47 @property 

48 def position(self) -> int: 

49 """1-based place in the flow.""" 

50 return list(RuleEnum.Layer).index(self.key) + 1 

51 

52 def spec(self) -> dict[str, Any]: 

53 return { 

54 "layer": self.key.value, 

55 "label": self.label, 

56 "summary": self.summary, 

57 "description": self.description, 

58 "phase": self.phase.value, 

59 "position": self.position, 

60 } 

61 

62 

63_REGISTRY: dict[RuleEnum.Layer, Layer] = {} 

64 

65 

66def register_layer(cls: type[Layer]) -> type[Layer]: 

67 """Class decorator adding one layer to the registry.""" 

68 instance = cls() 

69 if instance.key in _REGISTRY: 

70 raise RuntimeError(f"Layer '{instance.key.value}' is already registered.") 

71 _REGISTRY[instance.key] = instance 

72 return cls 

73 

74 

75def get(layer: RuleEnum.Layer | str) -> Layer: 

76 """The registered layer for ``layer``. Raises ``ValueError`` for a value 

77 that is not a layer.""" 

78 return _REGISTRY[RuleEnum.Layer(layer)] 

79 

80 

81def ordered() -> list[Layer]: 

82 """Every layer, in the order a request meets them.""" 

83 return [_REGISTRY[member] for member in RuleEnum.Layer] 

84 

85 

86def before_model() -> list[RuleEnum.Layer]: 

87 """The layers evaluated before the model is called, in order.""" 

88 return [layer.key for layer in ordered() if layer.phase is Phase.input] 

89 

90 

91def after_model() -> list[RuleEnum.Layer]: 

92 """The layers evaluated after the model answers, in order.""" 

93 return [layer.key for layer in ordered() if layer.phase is Phase.output] 

94 

95 

96def catalogue() -> list[dict[str, Any]]: 

97 """Every layer's spec, in flow order.""" 

98 return [layer.spec() for layer in ordered()] 

99 

100 

101@register_layer 

102class AccessLayer(Layer): 

103 key = RuleEnum.Layer.access 

104 label = "Access" 

105 summary = "May it run?" 

106 description = ( 

107 "Before anything is read: budgets, rate limits and the evaluation " 

108 "gate decide whether the request runs at all." 

109 ) 

110 phase = Phase.input 

111 

112 

113@register_layer 

114class InputLayer(Layer): 

115 key = RuleEnum.Layer.input 

116 label = "Input" 

117 summary = "What may the model read?" 

118 description = ( 

119 "Before the model reads the request: refuse it, or replace personal " 

120 "data in the prompt, its history and its attachments." 

121 ) 

122 phase = Phase.input 

123 

124 

125@register_layer 

126class ToolsLayer(Layer): 

127 key = RuleEnum.Layer.tools 

128 label = "Tools" 

129 summary = "Where may it look things up?" 

130 description = ( 

131 "While the agent works: the web sources it puts first, the only ones " 

132 "it may use, or the ones it must never use when it searches the web, " 

133 "reads pages or fetches images." 

134 ) 

135 # Resolved with the request, before the model is asked, and handed to 

136 # svc-ai for the run's tools (``web_domains.WebPolicy``). 

137 phase = Phase.input 

138 

139 

140@register_layer 

141class OutputLayer(Layer): 

142 key = RuleEnum.Layer.output 

143 label = "Output" 

144 summary = "What may people receive?" 

145 description = ( 

146 "After the model answers: replace personal data in what it wrote, or " 

147 "send the answer to a person to review." 

148 ) 

149 phase = Phase.output 

150 

151 

152def _check_complete() -> None: 

153 """Every ``RuleEnum.Layer`` member has exactly one class — checked at 

154 import, so a layer added to the enum alone fails at startup rather than 

155 on the first request that reaches it.""" 

156 missing = [member.value for member in RuleEnum.Layer if member not in _REGISTRY] 

157 if missing: 

158 raise RuntimeError(f"Rule layers with no class: {', '.join(missing)}") 

159 

160 

161_check_complete()