Coverage for app / routers / rules_setup.py: 100%

72 statements  

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

1""" 

2One-shot generative governance-rule setup. 

3 

4A sibling of skillset_setup.py / toolkit_setup.py / knowledge_setup.py, 

5scoped to proposing **governance rules** — the conditions and actions that 

6decide what an invocation may ask, which model answers it, and what is 

7recorded afterwards. 

8 

9One thing makes this flow different from its siblings: the vocabulary is not 

10written down here. A rule's condition fields, operators and actions are 

11registries in svc-core (``app.services.rules``), served to the rule builder 

12by ``GET /app/rules/catalogue`` — so svc-core sends the same catalogue on 

13this request and the prompt quotes it verbatim. Hard-coding a field list here 

14would produce rules referencing fields the engine has never heard of, and the 

15failure is silent: the rule is stored, shown as active on the governance 

16page, and never once matches (see ``app.services.rules.conditions``, which 

17logs and returns False for exactly that). 

18 

19For the same reason there is no validation here beyond the schema. svc-core 

20owns the registries and re-validates the whole proposal against them before 

21anything is persisted — a single authoritative check, rather than two 

22implementations of one grammar drifting apart across two images. The 

23enforcement-side mirror in ``app/inference/rule_vocabulary.py`` is the 

24narrower thing: what svc-ai can *evaluate* at inference time, which excludes 

25the actions only svc-core can resolve (quotas, the evidence gate). 

26""" 

27 

28from fastapi import APIRouter, Depends, HTTPException 

29from langchain_core.messages import HumanMessage, SystemMessage 

30from pydantic import BaseModel, Field 

31from sqlalchemy.orm import Session 

32 

33from app import prompts 

34from app.services.structured_output import ModelOutput 

35from app.db.postgres.enums import InvocationEnum 

36from app.dependency.base import get_db 

37from app.models.spec import ModelConfig 

38from app.services.conversation import persist_llm_invocation 

39from app.services import rule_catalogue 

40from app.services.llm import build_langchain_llm 

41from app.services.rule_catalogue import ( 

42 CatalogLayer, 

43 CatalogOperator, 

44 CatalogPiiKind, 

45 CatalogScope, 

46 ProposedAction, 

47 ProposedCondition, 

48) 

49from app.services.structured_generation import ( 

50 generate, 

51) 

52from app.util.logger import get_logger 

53 

54logger = get_logger(__name__) 

55 

56router = APIRouter(prefix="/rules", tags=["rule-setup"]) 

57 

58# Same budget as the other setup flows — must undercut svc-core's client 

59# timeout. 

60GENERATION_BUDGET_S = 100.0 

61 

62 

63# --------------------------------------------------------------------------- 

64# Request models — the catalogue svc-core sends, not a vocabulary of our own 

65# (its models and rendering are shared with agent setup; see 

66# app/services/rule_catalogue.py) 

67# --------------------------------------------------------------------------- 

68 

69 

70class CatalogTarget(BaseModel): 

71 """A resource a rule may be pinned to, from svc-core's /rules/targets.""" 

72 

73 scope: str 

74 id: str 

75 name: str = "" 

76 

77 

78class CatalogRule(BaseModel): 

79 """A rule the user already has — context, so the model does not restate 

80 governance that is already in force.""" 

81 

82 name: str 

83 description: str = "" 

84 layer: str = "" 

85 scope_type: str = "" 

86 

87 

88class RulesConfigGenerationRequest(BaseModel): 

89 problem_description: str = Field(min_length=1) 

90 provider: str 

91 model: str 

92 # llm_models.id of the generation model, for the invocation trace 

93 model_id: str | None = None 

94 layers: list[CatalogLayer] = [] 

95 operators: list[CatalogOperator] = [] 

96 #: What a field or parameter with ``vocabulary: "pii_kinds"`` holds — sent 

97 #: all along, and dropped here until this field was declared. 

98 pii_kinds: list[CatalogPiiKind] = [] 

99 scopes: list[CatalogScope] = [] 

100 targets: list[CatalogTarget] = [] 

101 existing_rules: list[CatalogRule] = [] 

102 user_id: str = "system" 

103 

104 

105# --------------------------------------------------------------------------- 

106# Structured-output schema 

107# 

108# Plain strings, not Literals: the vocabulary arrives on the request, so 

109# pinning it in the schema would freeze svc-core's registries into this 

110# image. svc-core drops anything outside the catalogue it sent. 

111# --------------------------------------------------------------------------- 

112 

113 

114class ProposedRule(BaseModel): 

115 name: str 

116 description: str = "" 

117 layer: str 

118 scope_type: str = "global" 

119 #: Empty unless the rule is pinned to one resource from the catalog. 

120 scope_id: str = "" 

121 conditions: list[ProposedCondition] = [] 

122 actions: list[ProposedAction] = Field(min_length=1) 

123 priority: int = 0 

124 

125 

126class GeneratedRulesConfig(ModelOutput): 

127 """The complete proposal the LLM must produce.""" 

128 

129 explanation: str = Field( 

130 default="", 

131 description="Why this proposal — written to the user.", 

132 # The model fills "explanation" (a field named for its reasoning can 

133 # be refused by Claude 5.x); svc-core reads it as "reasoning". 

134 serialization_alias="reasoning", 

135 ) 

136 proposed_rules: list[ProposedRule] = [] 

137 

138 

139class GenerateRulesConfigResponse(BaseModel): 

140 config: GeneratedRulesConfig 

141 warnings: list[str] = [] 

142 

143 

144# --------------------------------------------------------------------------- 

145# Prompt assembly 

146# --------------------------------------------------------------------------- 

147 

148 

149def _build_user_content(req: RulesConfigGenerationRequest) -> str: 

150 def section(title: str, items: list[BaseModel]) -> str: 

151 if not items: 

152 return f"{title}: (none)" 

153 lines = "\n".join(f" - {item.model_dump_json()}" for item in items) 

154 return f"{title}:\n{lines}" 

155 

156 return ( 

157 f"What the user wants governed:\n{req.problem_description}\n\n" 

158 + section("Governed resources catalog (for scope_id)", req.targets) 

159 + "\n\n" 

160 + section("Rules already in force", req.existing_rules) 

161 ) 

162 

163 

164# --------------------------------------------------------------------------- 

165# Endpoint 

166# --------------------------------------------------------------------------- 

167 

168 

169@router.post("/generate-config", response_model=GenerateRulesConfigResponse) 

170async def generate_rules_config( 

171 req: RulesConfigGenerationRequest, db: Session = Depends(get_db) 

172) -> GenerateRulesConfigResponse: 

173 """Propose governance rules in one structured call, over svc-core's vocabulary.""" 

174 system_prompt = prompts.build_rules_config_generator_prompt( 

175 vocabulary=rule_catalogue.render_vocabulary( 

176 rule_catalogue.RuleVocabulary( 

177 layers=req.layers, operators=req.operators, pii_kinds=req.pii_kinds 

178 ) 

179 ), 

180 scopes=rule_catalogue.render_scopes(req.scopes), 

181 has_targets=bool(req.targets), 

182 ) 

183 llm = build_langchain_llm( 

184 ModelConfig( 

185 provider=req.provider, 

186 model=req.model, 

187 temperature=0.2, 

188 max_tokens=4096, 

189 ) 

190 ) 

191 # include_raw surfaces the raw AIMessage so token usage can be recorded 

192 # in the LLM invocation trace alongside ordinary executions. 

193 messages = [ 

194 SystemMessage(content=system_prompt), 

195 HumanMessage(content=_build_user_content(req)), 

196 ] 

197 

198 outcome = await generate( 

199 llm, 

200 GeneratedRulesConfig, 

201 messages, 

202 purpose="rule-setup", 

203 budget_s=GENERATION_BUDGET_S, 

204 ) 

205 config = outcome.config 

206 

207 # The generation call is a real LLM invocation — trace it (success or 

208 # failure) so it appears in the activity view like any execution. 

209 persist_llm_invocation( 

210 db, 

211 purpose="rule_generation", 

212 provider=req.provider, 

213 model=req.model, 

214 user_id=req.user_id, 

215 latency_ms=outcome.latency_ms, 

216 status=InvocationEnum.Status.success 

217 if config is not None 

218 else InvocationEnum.Status.error, 

219 error_detail=outcome.failure if config is None else None, 

220 request_config={ 

221 "provider": req.provider, 

222 "model": req.model, 

223 "temperature": 0.2, 

224 "max_tokens": 4096, 

225 "flow": "rules_setup.generate_config", 

226 }, 

227 output_preview=config.model_dump_json(indent=2) if config else None, 

228 ) 

229 

230 if config is None: 

231 raise HTTPException( 

232 status_code=422, 

233 detail=f"Rule generation failed: {outcome.user_message}", 

234 ) 

235 

236 return GenerateRulesConfigResponse(config=config, warnings=[])