Coverage for app / router / app / rules / setup.py: 91%

174 statements  

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

1""" 

2Generative governance setup. 

3 

4A sibling of skillsets/setup.py and knowledge/setup.py, scoped to the one 

5resource whose whole value is that it is enforced: a governance rule. 

6 

7POST /app/rules/generate — send svc-ai the rule vocabulary this 

8 service owns (``app.services.rules``: fields, operators, actions, scopes) 

9 together with what the user may pin a rule to, then **authoritatively 

10 re-validate** everything that comes back against those same registries 

11 before returning it for review. 

12 

13POST /app/rules/create-from-config — persist a reviewed proposal in one 

14 transaction: every rule, its version row, and the generation run marked 

15 applied. One commit, full rollback on any error. 

16 

17Why validation is stricter here than anywhere else in the codebase 

18────────────────────────────────────────────────────────────────── 

19 

20A generated agent with a hallucinated skill id is missing a capability, and 

21the user can see that. A rule with a hallucinated condition field is *worse 

22than nothing*: ``app.services.rules.conditions`` logs a warning and returns 

23False, so the rule is stored, listed as active on the governance page, and 

24never once fires. Somebody believes they are governed and they are not. 

25 

26So a proposed rule is dropped whole rather than repaired: 

27 

28 • an unknown condition field, operator, or a pairing the field does not 

29 support — dropping the *condition* instead would widen the rule, and a 

30 widened ``block`` rule refuses traffic nobody asked it to refuse; 

31 • an unknown scope, or a ``scope_id`` that does not resolve to something 

32 this user owns — falling back to the whole scope widens it the same way, 

33 and an unresolvable pin is exactly what ``POST /app/rules`` already 

34 refuses; 

35 • an action the registry does not carry for that layer, or a required 

36 action parameter left empty — a ``rate_limit`` with no limit is a rule 

37 that cannot be evaluated. 

38 

39Every drop carries a warning naming the rule and the reason, because a 

40proposal that quietly shrinks is its own kind of silence. On 

41``create-from-config`` the same check runs again and *refuses* (422) rather 

42than dropping: by then a human has reviewed and edited the blocks, and they 

43should be told what is wrong with what they approved. 

44""" 

45 

46import logging 

47from typing import Any 

48from uuid import UUID, uuid4 

49 

50from fastapi import APIRouter, Depends, HTTPException, status 

51from pydantic import BaseModel, Field 

52from sqlalchemy.orm import Session 

53 

54from app.db.postgres.crud_schemas import Schema 

55from app.db.postgres.enums import GenerationEnum, HistoryEnum, RuleEnum 

56from app.db.postgres.models import Rule, User 

57from app.dependency.base import get_db 

58from app.dependency.workspace import owner_for 

59from app.dependency.user.context import get_current_user 

60from app.router.app.agents.setup import ( 

61 MAX_CATALOG_ITEMS, 

62 GenerationModelInfo, 

63 _resolve_generation_model, 

64 _truncate, 

65) 

66from app.router.app.rules.router import _verify_scope 

67from app.services import ai_client 

68from app.services import generation as generation_service 

69from app.services import history as history_service 

70from app.services.ai_client import AIServiceError, GenerationFailedError 

71from app.services.rules import catalogue as rule_catalogue 

72from app.services.rules import proposals 

73from app.services.rules import references as rule_references 

74from app.services.rules import scopes as scope_registry 

75 

76logger = logging.getLogger(__name__) 

77 

78rule_setup_router = APIRouter(prefix="/rules", tags=["App - Rule Setup"]) 

79 

80#: Cap on rules accepted from one proposal. The prompt asks for 2-5; this is 

81#: the boundary's own limit rather than a trusted one. 

82MAX_PROPOSED_RULES = 12 

83 

84 

85# --------------------------------------------------------------------------- 

86# Request / response models 

87# --------------------------------------------------------------------------- 

88 

89 

90class GenerateRulesRequest(BaseModel): 

91 problem_description: str = Field(min_length=20) 

92 ai_model_id: UUID | None = None 

93 

94 

95class ProposedRuleInfo(BaseModel): 

96 """One validated rule, in the shape the review step edits and posts back.""" 

97 

98 name: str 

99 description: str = "" 

100 layer: RuleEnum.Layer 

101 scope_type: RuleEnum.Scope = RuleEnum.Scope.global_ 

102 scope_id: UUID | None = None 

103 #: What the scope resolves to, in words — a reviewer approving "applies 

104 #: to 7f3c…" has not been told anything. 

105 scope_label: str = "" 

106 conditions: list[dict] = [] 

107 actions: list[dict] = [] 

108 priority: int = 0 

109 is_active: bool = True 

110 

111 

112class RulesGenerationProposal(BaseModel): 

113 reasoning: str = "" 

114 proposed_rules: list[ProposedRuleInfo] = [] 

115 warnings: list[str] = [] 

116 model: GenerationModelInfo 

117 # Echoed back on create-from-config; see app.services.generation. 

118 generation_id: UUID 

119 

120 

121class CreateRulesFromConfigRequest(BaseModel): 

122 rules: list[ProposedRuleInfo] = Field(min_length=1) 

123 generation_id: UUID | None = None 

124 

125 

126class CreateRulesFromConfigResponse(BaseModel): 

127 rules: list[Schema.Rule.Read] 

128 

129 

130# --------------------------------------------------------------------------- 

131# Vocabulary → svc-ai payload 

132# --------------------------------------------------------------------------- 

133 

134 

135def _targets_payload(db: Session, user: User) -> tuple[list[dict], dict[str, str]]: 

136 """What this user may pin a rule to in the request's workspace, and a 

137 lookup from id to label. Only that workspace's: the list goes into a 

138 model's prompt, and an organisation's rule setup has no business sending 

139 it the names of a member's personal agents.""" 

140 from app.dependency.workspace import request_workspace 

141 

142 ws = request_workspace(db, user) 

143 targets: list[dict] = [] 

144 labels: dict[str, str] = {} 

145 for spec in scope_registry.catalogue(): 

146 scope = scope_registry.get_scope(spec["key"]) 

147 if scope is None or not scope.targets_resource: 

148 continue 

149 for row in scope.targets(db, user, ws)[:MAX_CATALOG_ITEMS]: 

150 targets.append( 

151 { 

152 "scope": row["scope_type"], 

153 "id": row["id"], 

154 "name": _truncate(row["label"]), 

155 } 

156 ) 

157 labels[row["id"]] = row["label"] 

158 return targets, labels 

159 

160 

161# --------------------------------------------------------------------------- 

162# Authoritative validation 

163# --------------------------------------------------------------------------- 

164 

165 

166def _enum_value(value: Any) -> str: 

167 """The stored key of an enum column, tolerant of a plain string.""" 

168 return str(getattr(value, "value", value) or "") 

169 

170 

171def _validate_scope( 

172 raw: dict, 

173 db: Session, 

174 user: User, 

175 labels: dict[str, str], 

176) -> tuple[RuleEnum.Scope, UUID | None, str, str | None]: 

177 """Scope type, pinned id and its label — or the reason to drop the rule.""" 

178 scope_key = str(raw.get("scope_type", "") or "global").strip() 

179 scope = scope_registry.get_scope(scope_key) 

180 if scope is None: 

181 return ( 

182 RuleEnum.Scope.global_, 

183 None, 

184 "", 

185 f"scope '{scope_key}' is not one the engine resolves", 

186 ) 

187 raw_id = str(raw.get("scope_id", "") or "").strip() 

188 if not raw_id: 

189 return scope.key, None, "", None 

190 if not scope.targets_resource: 

191 return ( 

192 scope.key, 

193 None, 

194 "", 

195 f"a {scope.label.lower()} rule cannot be aimed at a single resource", 

196 ) 

197 try: 

198 scope_id = UUID(raw_id) 

199 except ValueError: 

200 return scope.key, None, "", f"'{raw_id}' is not a resource id" 

201 if not scope.validate(db, user, scope_id): 

202 return ( 

203 scope.key, 

204 None, 

205 "", 

206 f"no {scope.label.lower()} of yours matches '{raw_id}'", 

207 ) 

208 return scope.key, scope_id, labels.get(raw_id, ""), None 

209 

210 

211def validate_proposed_rule( 

212 raw: dict, 

213 db: Session, 

214 user: User, 

215 labels: dict[str, str] | None = None, 

216) -> tuple[ProposedRuleInfo | None, str | None]: 

217 """One proposed rule, validated against the registries — or why it fails. 

218 

219 The single implementation behind both endpoints: ``/generate`` drops what 

220 this rejects and says so in a warning, ``/create-from-config`` refuses. 

221 """ 

222 labels = labels or {} 

223 name = str(raw.get("name", "") or "").strip() or "Generated Rule" 

224 

225 layer_key = str(raw.get("layer", "") or "").strip() 

226 try: 

227 layer = RuleEnum.Layer(layer_key) 

228 except ValueError: 

229 return None, f"Dropped '{name}': '{layer_key}' is not a layer." 

230 

231 scope_type, scope_id, scope_label, scope_error = _validate_scope( 

232 raw, db, user, labels 

233 ) 

234 if scope_error: 

235 return None, f"Dropped '{name}': {scope_error}." 

236 

237 conditions, condition_error = proposals.validate_conditions( 

238 list(raw.get("conditions", []) or []), layer 

239 ) 

240 if condition_error: 

241 return None, f"Dropped '{name}': {condition_error}." 

242 

243 actions, action_error = proposals.validate_actions( 

244 list(raw.get("actions", []) or []), layer 

245 ) 

246 if action_error: 

247 return None, f"Dropped '{name}': {action_error}." 

248 # An id in an action is model output at a boundary: one that does not 

249 # resolve drops the rule rather than being cleared, because clearing the 

250 # evidence gate's dataset changes which evidence it demands. 

251 unresolved = rule_references.unresolved(db, user, layer, actions) 

252 if unresolved: 

253 return None, f"Dropped '{name}': {'; '.join(unresolved)}." 

254 

255 return ( 

256 ProposedRuleInfo( 

257 name=name[:255], 

258 description=str(raw.get("description", "") or ""), 

259 layer=layer, 

260 scope_type=scope_type, 

261 scope_id=scope_id, 

262 scope_label=scope_label, 

263 conditions=conditions, 

264 actions=actions, 

265 priority=int(raw.get("priority", 0) or 0), 

266 is_active=bool(raw.get("is_active", True)), 

267 ), 

268 None, 

269 ) 

270 

271 

272# --------------------------------------------------------------------------- 

273# Endpoints 

274# --------------------------------------------------------------------------- 

275 

276 

277@rule_setup_router.post("/generate", response_model=RulesGenerationProposal) 

278def generate_rules( 

279 body: GenerateRulesRequest, 

280 db: Session = Depends(get_db), 

281 current_user: User = Depends(get_current_user), 

282): 

283 """Propose governance rules for review (creates nothing). 

284 

285 Records the invocation even so — see ``generate_agent`` for why. 

286 """ 

287 try: 

288 model_info = _resolve_generation_model(body.ai_model_id) 

289 except AIServiceError as exc: 

290 run = generation_service.start( 

291 db, 

292 flow=GenerationEnum.Flow.rule_setup, 

293 actor=current_user, 

294 arguments=body.model_dump(), 

295 ) 

296 generation_service.fail(db, run, error=str(exc)) 

297 db.commit() 

298 raise HTTPException( 

299 status_code=status.HTTP_502_BAD_GATEWAY, 

300 detail=f"Could not resolve a generation model: {exc}", 

301 ) 

302 provider = model_info["provider"]["name"] 

303 model_name = model_info["model_name"] 

304 

305 run = generation_service.start( 

306 db, 

307 flow=GenerationEnum.Flow.rule_setup, 

308 actor=current_user, 

309 arguments=body.model_dump(), 

310 model_info=model_info, 

311 ) 

312 

313 warnings: list[str] = [] 

314 targets, labels = _targets_payload(db, current_user) 

315 

316 existing_rules = ( 

317 db.query(Rule) 

318 .filter(Rule.owner_user_id == current_user.id) 

319 .limit(MAX_CATALOG_ITEMS) 

320 .all() 

321 ) 

322 

323 payload = { 

324 "problem_description": body.problem_description, 

325 "provider": provider, 

326 "model": model_name, 

327 "model_id": str(model_info["id"]) if model_info.get("id") else None, 

328 "targets": targets, 

329 "existing_rules": [ 

330 { 

331 "name": rule.name, 

332 "description": _truncate(rule.description), 

333 "layer": _enum_value(rule.layer), 

334 "scope_type": _enum_value(rule.scope_type), 

335 } 

336 for rule in existing_rules 

337 ], 

338 "user_id": str(current_user.id), 

339 **rule_catalogue.generation_vocabulary(), 

340 } 

341 

342 try: 

343 with generation_service.metered(db, run): 

344 result = ai_client.generate_rules_config(payload) 

345 except GenerationFailedError as exc: 

346 generation_service.fail(db, run, error=str(exc)) 

347 db.commit() 

348 raise HTTPException( 

349 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc) 

350 ) 

351 except AIServiceError as exc: 

352 logger.error("Rule generation failed: %s", exc) 

353 generation_service.fail(db, run, error=str(exc)) 

354 db.commit() 

355 raise HTTPException( 

356 status_code=status.HTTP_502_BAD_GATEWAY, 

357 detail="Could not reach svc-ai to generate the rules.", 

358 ) 

359 

360 config: dict = result.get("config", {}) 

361 warnings.extend(result.get("warnings", [])) 

362 

363 proposed: list[ProposedRuleInfo] = [] 

364 for raw in list(config.get("proposed_rules", []) or [])[:MAX_PROPOSED_RULES]: 

365 rule_info, warning = validate_proposed_rule(raw, db, current_user, labels) 

366 if rule_info is None: 

367 warnings.append(warning or "Dropped a proposed rule.") 

368 continue 

369 proposed.append(rule_info) 

370 

371 if not proposed: 

372 warnings.append( 

373 "No rule in this proposal could be written against the engine's " 

374 "vocabulary. Try describing what you want governed in more " 

375 "concrete terms." 

376 ) 

377 

378 generation_service.record_warnings(run, warnings) 

379 db.commit() 

380 

381 return RulesGenerationProposal( 

382 reasoning=config.get("reasoning", ""), 

383 proposed_rules=proposed, 

384 warnings=warnings, 

385 model=GenerationModelInfo( 

386 provider=provider, 

387 model_name=model_name, 

388 ai_model_id=model_info.get("id"), 

389 ), 

390 generation_id=run.id, 

391 ) 

392 

393 

394@rule_setup_router.post( 

395 "/create-from-config", 

396 response_model=CreateRulesFromConfigResponse, 

397 status_code=status.HTTP_201_CREATED, 

398) 

399def create_rules_from_config( 

400 body: CreateRulesFromConfigRequest, 

401 db: Session = Depends(get_db), 

402 current_user: User = Depends(get_current_user), 

403): 

404 """Persist a reviewed rule proposal atomically. 

405 

406 Re-validated rather than trusted: the blocks arriving here have been 

407 through a human's edits *and* a model's invention, and this endpoint is 

408 as reachable as any other. A rule that fails is refused with the reason 

409 (422) instead of being silently narrowed or dropped — by this point the 

410 user has approved it and deserves to know what is wrong with it. 

411 """ 

412 prepared: list[ProposedRuleInfo] = [] 

413 for candidate in body.rules: 

414 rule_info, reason = validate_proposed_rule( 

415 candidate.model_dump(mode="json"), db, current_user 

416 ) 

417 if rule_info is None: 

418 raise HTTPException( 

419 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

420 detail=(reason or "A rule could not be validated.").replace( 

421 "Dropped", "Refused" 

422 ), 

423 ) 

424 # The same scope check ``POST /app/rules`` performs, so the two 

425 # creation paths cannot disagree about what a valid pin is. 

426 _verify_scope(rule_info.scope_type, rule_info.scope_id, current_user, db) 

427 prepared.append(rule_info) 

428 

429 run = generation_service.resolve(db, body.generation_id, current_user) 

430 

431 try: 

432 rows = [ 

433 Rule( 

434 id=uuid4(), 

435 name=rule.name, 

436 description=rule.description or None, 

437 layer=rule.layer, 

438 scope_type=rule.scope_type, 

439 scope_id=rule.scope_id, 

440 conditions=rule.conditions, 

441 actions=rule.actions, 

442 is_active=rule.is_active, 

443 priority=rule.priority, 

444 **owner_for(db, current_user, model=Rule), 

445 ) 

446 for rule in prepared 

447 ] 

448 generation_service.stamp(rows, run) 

449 # stamp() only sets the flag when there is a run to point at; this 

450 # endpoint only ever persists generated output, so the flag holds 

451 # even for a client that did not echo an id back. 

452 for row in rows: 

453 row.is_ai_generated = True 

454 db.add_all(rows) 

455 db.flush() 

456 

457 db.add_all( 

458 [ 

459 history_service.build_version( 

460 db, 

461 resource_type=HistoryEnum.ResourceType.rule, 

462 model=Rule, 

463 resource=row, 

464 action=HistoryEnum.Action.created, 

465 actor=current_user, 

466 ) 

467 for row in rows 

468 ] 

469 ) 

470 

471 generation_service.apply( 

472 db, 

473 run, 

474 target_resource_type=HistoryEnum.ResourceType.rule, 

475 # A proposal creates several peers with no parent between them, 

476 # so the first rule stands for the run's target the way the 

477 # skillset does in its own flow. 

478 target_resource_id=rows[0].id if rows else None, 

479 ) 

480 

481 db.commit() 

482 except HTTPException: 

483 raise 

484 except Exception: 

485 db.rollback() 

486 logger.exception("Failed to create rules from generated config") 

487 raise 

488 

489 for row in rows: 

490 db.refresh(row) 

491 return CreateRulesFromConfigResponse( 

492 rules=[ 

493 Schema.Rule.Read.model_validate(row, from_attributes=True) for row in rows 

494 ] 

495 )