Coverage for app / router / app / rules / router.py: 93%

167 statements  

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

1import logging 

2from datetime import timedelta 

3from typing import Optional 

4from uuid import UUID 

5 

6from fastapi import APIRouter, Depends, HTTPException, Query, status 

7from sqlalchemy.orm import Session 

8 

9from app.db.postgres.crud_schemas import Schema 

10from app.db.postgres.enums import GovernanceEnum, HistoryEnum, RuleEnum 

11from app.db.postgres.models import Agent, Rule, User 

12from app.dependency.base import get_db 

13from app.dependency.workspace import owner_for 

14from app.dependency.resource_access import ( 

15 annotated, 

16 may_change_here, 

17 scoped, 

18 verify_change_here, 

19 verify_owner_scope, 

20 verify_resource_read, 

21) 

22from app.dependency.user.context import get_current_user 

23from app.router.app.history.router import register_history_routes 

24from app.services import governance_activity as activity_service 

25from app.services import history as history_service 

26from app.services import workspace as workspace_service 

27from app.services.rules import catalogue as rule_catalogue 

28from app.services.rules import proposals 

29from app.services.rules import references as rule_references 

30from app.services.rules import scopes as rule_scopes 

31from app.util.time import aware_utcnow 

32 

33logger = logging.getLogger(__name__) 

34 

35rules_router = APIRouter(prefix="/rules", tags=["App - Rules"]) 

36 

37 

38@rules_router.get("", response_model=list[Schema.Rule.Read]) 

39def list_rules( 

40 layer: RuleEnum.Layer | None = None, 

41 workspace: Optional[str] = None, 

42 owner_organisation_id: Optional[UUID] = None, 

43 owner_project_id: Optional[UUID] = None, 

44 include_system: bool = False, 

45 db: Session = Depends(get_db), 

46 current_user: User = Depends(get_current_user), 

47): 

48 """The caller's rules — and, with ``include_system``, the built-in rules 

49 after them, in the order they are declared. 

50 

51 Opt-in, as for agents and repositories: every count of "your rules" reads 

52 this listing, and a built-in governs nobody, so it must not be counted as 

53 a rule in force. Only the personal listing offers them; an organisation's 

54 or project's rules are that owner's alone. 

55 """ 

56 where, ws = scoped( 

57 Rule, 

58 current_user, 

59 db, 

60 workspace=workspace, 

61 owner_organisation_id=owner_organisation_id, 

62 owner_project_id=owner_project_id, 

63 ) 

64 query = db.query(Rule).filter(where) 

65 if layer: 

66 query = query.filter(Rule.layer == layer) 

67 rules = query.order_by(Rule.priority.desc(), Rule.created_at.desc()).all() 

68 # Built-ins follow the rules in force; every workspace offers them. 

69 if include_system and ( 

70 workspace or not (owner_organisation_id or owner_project_id) 

71 ): 

72 built_in = db.query(Rule).filter(Rule.is_system.is_(True)) 

73 if layer: 

74 built_in = built_in.filter(Rule.layer == layer) 

75 # Fixed ids, allocated in declaration order. 

76 rules = [*rules, *built_in.order_by(Rule.id).all()] 

77 return annotated(rules, ws) 

78 

79 

80# --------------------------------------------------------------------------- 

81# Vocabulary catalogue 

82# 

83# Declared before /{rule_id} so the literal path is not parsed as a rule id. 

84# --------------------------------------------------------------------------- 

85 

86 

87@rules_router.get("/catalogue", response_model=Schema.Rule.Catalogue) 

88def rule_catalogue_endpoint(): 

89 """The grammar a rule may be written in — fields, operators and actions. 

90 

91 Served from the backend registries so the visual rule builder offers 

92 exactly what the engine can evaluate. Adding a condition field or an 

93 action is a class in ``app.services.rules``; it appears here, and 

94 therefore in the builder, without a frontend release. 

95 

96 Unauthenticated callers never reach this — the whole ``/app`` surface is 

97 session-gated — but the catalogue itself is the same for every user: it 

98 describes the engine, not their data. 

99 """ 

100 return rule_catalogue.build() 

101 

102 

103@rules_router.get("/targets", response_model=Schema.Rule.ScopeTargets) 

104def rule_scope_targets( 

105 db: Session = Depends(get_db), 

106 current_user: User = Depends(get_current_user), 

107): 

108 """Every resource the current user may pin a rule to, grouped by scope. 

109 

110 One call instead of the builder fanning out to the agent, model, skill, 

111 worker, project and organisation routers — and one place for the rules 

112 list to resolve a stored ``scope_id`` into the name of the thing it 

113 governs, so a scoped rule reads as "Support Agent" rather than a UUID. 

114 

115 Unlike ``/catalogue`` this *is* per-user and per-workspace: it lists 

116 what the request's workspace holds (``Scope.targets``), since a rule 

117 governs only invocations made there. 

118 """ 

119 from app.dependency.workspace import request_workspace 

120 

121 ws = request_workspace(db, current_user) 

122 return { 

123 "targets": { 

124 scope.key.value: scope.targets(db, current_user, ws) 

125 for scope in ( 

126 rule_scopes.get_scope(spec["key"]) for spec in rule_scopes.catalogue() 

127 ) 

128 if scope is not None and scope.targets_resource 

129 } 

130 } 

131 

132 

133# --------------------------------------------------------------------------- 

134# Activity 

135# 

136# Declared before /{rule_id} for the same reason /catalogue and /targets are. 

137# --------------------------------------------------------------------------- 

138 

139#: Hard ceiling on a single page, so a client cannot ask for the whole log. 

140MAX_ACTIVITY_LIMIT = 200 

141 

142 

143def _activity_subjects(db: Session, groups: list[dict]) -> dict[UUID, str]: 

144 """Agent names for a page of turns — what each card is about. 

145 

146 One query for the whole page rather than a lookup per card, and resolved 

147 rather than denormalised onto the row: the event has to outlive the agent, 

148 but while the agent exists its *current* name is the one a reader 

149 recognises. A deleted agent resolves to nothing and the card says so, the 

150 same way a deleted rule does. 

151 

152 Models are deliberately not resolved. They are svc-ai's records, not this 

153 service's, so naming one would put a cross-service call on a log page — 

154 and a direct model prompt is already legible from its execution type. 

155 """ 

156 agent_ids = {entry["agent_id"] for entry in groups if entry.get("agent_id")} 

157 if not agent_ids: 

158 return {} 

159 return { 

160 agent.id: agent.name 

161 for agent in db.query(Agent).filter(Agent.id.in_(agent_ids)).all() 

162 } 

163 

164 

165@rules_router.get("/activity", response_model=Schema.GovernanceActivity.List) 

166def rule_activity( 

167 rule_id: UUID | None = None, 

168 layer: RuleEnum.Layer | None = None, 

169 phase: GovernanceEnum.Phase | None = None, 

170 outcome: GovernanceEnum.Outcome | None = None, 

171 execution_type: str | None = None, 

172 conversation_id: UUID | None = None, 

173 days: int | None = Query(default=None, ge=1, le=365), 

174 limit: int = Query(default=50, ge=1, le=MAX_ACTIVITY_LIMIT), 

175 offset: int = Query(default=0, ge=0), 

176 workspace: str | None = None, 

177 db: Session = Depends(get_db), 

178 current_user: User = Depends(get_current_user), 

179): 

180 """What the rules have actually done, grouped into the message they ran on. 

181 

182 ``workspace`` narrows it to the work done in one workspace — everyone's, 

183 for its reviewers (``governance_activity.scoped_query``). 

184 

185 The log's reason for existing is the rules that did *nothing*: an action 

186 with nothing to do emits no event, so before this a redaction rule over a 

187 clean prompt was indistinguishable from a rule that had never been 

188 evaluated. ``outcome`` separates blocked / applied / ran-and-changed- 

189 nothing / conditions-did-not-hold, and the summary counts all four over 

190 the filtered set rather than over the page — a header that only counted 

191 the rows on screen would answer a different question from the one it 

192 appears to. 

193 

194 Returned grouped, and paged by *invocation* rather than by event. One turn 

195 is routinely governed by half a dozen rules across both phases; flat, they 

196 interleave with every other agent's traffic, and "what happened to this 

197 message?" — the question somebody monitoring a fleet is actually asking — 

198 stops being answerable. Paging by row would also cut a turn in half at the 

199 page boundary and show a reader half its governance. 

200 

201 Scoped by owner, like the reviewer queue: the row records whose invocation 

202 was governed, which is the only scope it can answer on its own. 

203 """ 

204 from app.services import workspace as workspace_service 

205 

206 ws = workspace_service.resolve(db, workspace, current_user) if workspace else None 

207 query = activity_service.filtered( 

208 activity_service.scoped_query(db, current_user, ws), 

209 rule_id=rule_id, 

210 layer=layer, 

211 phase=phase, 

212 outcome=outcome, 

213 execution_type=execution_type, 

214 conversation_id=conversation_id, 

215 since=(aware_utcnow() - timedelta(days=days)) if days else None, 

216 ) 

217 # Two queries rather than one: page over invocations, then fetch every 

218 # event of the invocations on that page. Paging over events instead would 

219 # split a turn across the page boundary and show half its governance. 

220 invocation_ids, total = activity_service.invocation_page( 

221 query, limit=limit, offset=offset 

222 ) 

223 groups = activity_service.group(activity_service.events_for(query, invocation_ids)) 

224 subjects = _activity_subjects(db, groups) 

225 return Schema.GovernanceActivity.List( 

226 groups=[ 

227 Schema.GovernanceActivity.Group( 

228 **{ 

229 **entry, 

230 "subject": subjects.get(entry["agent_id"]), 

231 "events": [ 

232 Schema.GovernanceActivity.Read.model_validate( 

233 event, from_attributes=True 

234 ) 

235 for event in entry["events"] 

236 ], 

237 } 

238 ) 

239 for entry in groups 

240 ], 

241 total=total, 

242 summary=Schema.GovernanceActivity.Summary(**activity_service.summarise(query)), 

243 ) 

244 

245 

246@rules_router.get("/{rule_id}", response_model=Schema.Rule.Detail) 

247def get_rule( 

248 rule_id: UUID, 

249 db: Session = Depends(get_db), 

250 current_user: User = Depends(get_current_user), 

251): 

252 """A rule, whether the caller may change it here, and whose it is. 

253 

254 ``can_change`` is what a page asks before it offers Edit — the rule's 

255 own page, and the note under an answer a Tools rule narrowed, which 

256 links straight to a pre-filled edit. A reader who may not is told 

257 whose rule it is (``home_workspace_name``), so they know where to ask. 

258 """ 

259 rule = db.get(Rule, rule_id) 

260 if not rule: 

261 raise HTTPException( 

262 status_code=status.HTTP_404_NOT_FOUND, detail="Rule not found" 

263 ) 

264 # A built-in is readable by everyone: it is what the builder opens with 

265 # when a user creates a rule from it. 

266 verify_resource_read(rule, current_user, db) 

267 home = workspace_service.home_of(db, rule, named=True) 

268 detail = Schema.Rule.Detail.model_validate(rule) 

269 detail.can_change = may_change_here(rule, current_user, db) 

270 if home is not None: 

271 detail.home_workspace = detail.home_workspace or home.key 

272 detail.home_workspace_name = home.name 

273 return detail 

274 

275 

276def _based_on(based_on_rule_id: UUID | None, current_user: User, db: Session) -> dict: 

277 """The provenance columns for a rule created from a built-in. 

278 

279 Only a built-in may be named: the column answers "which of CHAIN-R's 

280 definitions did this start from, and which release of it?", and a 

281 user's own rule has no release to record. The version is read here, not 

282 taken from the client, so it is the one actually in force. 

283 """ 

284 if based_on_rule_id is None: 

285 return {} 

286 source = db.get(Rule, based_on_rule_id) 

287 if source is None: 

288 raise HTTPException( 

289 status_code=status.HTTP_404_NOT_FOUND, 

290 detail="No rule found for based_on_rule_id", 

291 ) 

292 if source.is_system is not True: 

293 raise HTTPException( 

294 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

295 detail="based_on_rule_id must name a built-in rule", 

296 ) 

297 verify_resource_read(source, current_user, db) 

298 return { 

299 "based_on_rule_id": source.id, 

300 "based_on_version": history_service.current_version( 

301 db, HistoryEnum.ResourceType.rule, source.id 

302 ), 

303 } 

304 

305 

306def _verify_required(required: bool | None, owner_project_id) -> None: 

307 """422 for a project's rule marked required: a project has no projects 

308 to require it of (``ck_rules_required_parent``).""" 

309 if required and owner_project_id is not None: 

310 raise HTTPException( 

311 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

312 detail="Only a person's or an organisation's rule can be required " 

313 "for its projects.", 

314 ) 

315 

316 

317def _verify_scope( 

318 scope_type: RuleEnum.Scope | None, 

319 scope_id: UUID | None, 

320 current_user: User, 

321 db: Session, 

322) -> None: 

323 """Refuse a rule whose scope names something that cannot govern anything. 

324 

325 Two failures are worth catching before the row is written, because both 

326 produce a rule that *looks* active on the list page and silently never 

327 fires — the worst thing a governance surface can do: 

328 

329 • a scope type the engine has no definition for, and 

330 • a ``scope_id`` that resolves to nothing, or to a resource belonging to 

331 somebody else. 

332 

333 A pinned id is checked against the same ownership the resource's own 

334 routes enforce, so a rule cannot be used to probe whether an id exists in 

335 another account. 

336 """ 

337 scope = rule_scopes.get_scope(scope_type) 

338 if scope is None: 

339 raise HTTPException( 

340 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

341 detail=f"Unknown rule scope '{scope_type}'", 

342 ) 

343 if scope_id is None: 

344 return 

345 if not scope.targets_resource: 

346 raise HTTPException( 

347 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

348 detail=f"A {scope.label.lower()} rule cannot target a single resource", 

349 ) 

350 if not scope.validate(db, current_user, scope_id): 

351 raise HTTPException( 

352 status_code=status.HTTP_404_NOT_FOUND, 

353 detail=f"No {scope.label.lower()} found for that scope", 

354 ) 

355 

356 

357def _verify_terms( 

358 layer: RuleEnum.Layer | str | None, 

359 conditions: list[dict] | None, 

360 actions: list[dict] | None, 

361) -> None: 

362 """Refuse a rule naming a value its registry does not hold — a PII kind no 

363 detector knows. Stored, it would be a rule that looks configured and 

364 quietly redacts the default set instead.""" 

365 problems = proposals.unknown_terms(layer, conditions, actions) 

366 if problems: 

367 raise HTTPException( 

368 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

369 detail="; ".join(problems), 

370 ) 

371 

372 

373def _verify_references( 

374 layer: RuleEnum.Layer | str | None, 

375 blocks: list[dict] | None, 

376 current_user: User, 

377 db: Session, 

378) -> None: 

379 """Refuse a rule whose actions name a resource that is not there — the 

380 evidence gate's dataset, say. The same reasoning, and the same 404, as a 

381 scope pinned to nothing (:func:`_verify_scope`).""" 

382 problems = rule_references.unresolved(db, current_user, layer, blocks) 

383 if problems: 

384 raise HTTPException( 

385 status_code=status.HTTP_404_NOT_FOUND, detail="; ".join(problems) 

386 ) 

387 

388 

389@rules_router.post( 

390 "", response_model=Schema.Rule.Read, status_code=status.HTTP_201_CREATED 

391) 

392def create_rule( 

393 body: Schema.Rule.Create, 

394 db: Session = Depends(get_db), 

395 current_user: User = Depends(get_current_user), 

396): 

397 data = body.model_dump() 

398 if not data.get("owner_organisation_id") and not data.get("owner_project_id"): 

399 # The workspace the request was made in (app/dependency/workspace.py). 

400 data.update(owner_for(db, current_user, model=Rule)) 

401 verify_owner_scope(data, current_user, db, model=Rule) 

402 _verify_required(data.get("required_for_projects"), data.get("owner_project_id")) 

403 _verify_scope(data.get("scope_type"), data.get("scope_id"), current_user, db) 

404 _verify_terms(data.get("layer"), data.get("conditions"), data.get("actions")) 

405 _verify_references(data.get("layer"), data.get("actions"), current_user, db) 

406 data["actions"] = proposals.normalise_actions( 

407 data.get("layer"), data.get("actions") 

408 ) 

409 data.update(_based_on(data.pop("based_on_rule_id", None), current_user, db)) 

410 

411 rule = Rule(**data) 

412 try: 

413 db.add(rule) 

414 db.commit() 

415 db.refresh(rule) 

416 history_service.record_version( 

417 db, 

418 resource_type=HistoryEnum.ResourceType.rule, 

419 model=Rule, 

420 resource=rule, 

421 action=HistoryEnum.Action.created, 

422 actor=current_user, 

423 ) 

424 db.commit() 

425 return rule 

426 except Exception: 

427 db.rollback() 

428 logger.exception("Failed to create rule") 

429 raise 

430 

431 

432@rules_router.patch("/{rule_id}", response_model=Schema.Rule.Read) 

433def update_rule( 

434 rule_id: UUID, 

435 body: Schema.Rule.Update, 

436 db: Session = Depends(get_db), 

437 current_user: User = Depends(get_current_user), 

438): 

439 rule = db.get(Rule, rule_id) 

440 if not rule: 

441 raise HTTPException( 

442 status_code=status.HTTP_404_NOT_FOUND, detail="Rule not found" 

443 ) 

444 # Changed in its own workspace only: what a project inherits from its 

445 # parent, or is required to apply, is read-only there. 

446 verify_change_here(rule, current_user, db) 

447 changes = body.model_dump(exclude_unset=True) 

448 if changes.get("required_for_projects") is None: 

449 changes.pop("required_for_projects", None) 

450 _verify_required(changes.get("required_for_projects"), rule.owner_project_id) 

451 # Checked against the *resulting* pair, not the submitted one: moving a 

452 # rule from "all agents" to one agent sends only ``scope_id``, and 

453 # validating that against the stored scope type would be validating half 

454 # an edit. ``exclude_unset`` is what makes clearing scope_id to None — 

455 # widening a pinned rule back to its whole kind — distinguishable from 

456 # not mentioning it. 

457 if "scope_type" in changes or "scope_id" in changes: 

458 _verify_scope( 

459 changes.get("scope_type", rule.scope_type), 

460 changes.get("scope_id", rule.scope_id), 

461 current_user, 

462 db, 

463 ) 

464 if {"actions", "conditions", "layer"} & changes.keys(): 

465 _verify_terms( 

466 changes.get("layer", rule.layer), 

467 changes.get("conditions", rule.conditions), 

468 changes.get("actions", rule.actions), 

469 ) 

470 if "actions" in changes or "layer" in changes: 

471 _verify_references( 

472 changes.get("layer", rule.layer), 

473 changes.get("actions", rule.actions), 

474 current_user, 

475 db, 

476 ) 

477 if "actions" in changes: 

478 changes["actions"] = proposals.normalise_actions( 

479 changes.get("layer", rule.layer), changes["actions"] 

480 ) 

481 for field, value in changes.items(): 

482 setattr(rule, field, value) 

483 history_service.record_version( 

484 db, 

485 resource_type=HistoryEnum.ResourceType.rule, 

486 model=Rule, 

487 resource=rule, 

488 action=HistoryEnum.Action.updated, 

489 actor=current_user, 

490 ) 

491 try: 

492 db.commit() 

493 db.refresh(rule) 

494 return rule 

495 except Exception: 

496 db.rollback() 

497 logger.exception("Failed to update rule") 

498 raise 

499 

500 

501@rules_router.delete("/{rule_id}", status_code=status.HTTP_204_NO_CONTENT) 

502def delete_rule( 

503 rule_id: UUID, 

504 db: Session = Depends(get_db), 

505 current_user: User = Depends(get_current_user), 

506): 

507 rule = db.get(Rule, rule_id) 

508 if not rule: 

509 raise HTTPException( 

510 status_code=status.HTTP_404_NOT_FOUND, detail="Rule not found" 

511 ) 

512 verify_change_here(rule, current_user, db) 

513 history_service.record_version( 

514 db, 

515 resource_type=HistoryEnum.ResourceType.rule, 

516 model=Rule, 

517 resource=rule, 

518 action=HistoryEnum.Action.deleted, 

519 actor=current_user, 

520 ) 

521 db.delete(rule) 

522 db.commit() 

523 

524 

525register_history_routes( 

526 rules_router, 

527 resource_type=HistoryEnum.ResourceType.rule, 

528 model=Rule, 

529 not_found_detail="Rule not found", 

530 # A built-in's history is its release history, readable by everyone. 

531 access_check=verify_resource_read, 

532)