Coverage for app / services / rules / scopes.py: 91%

322 statements  

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

1""" 

2Scopes — *what* a governance rule governs. 

3 

4One class per scope kind, registered with :func:`register_scope`, mirroring 

5how ``fields``, ``operators`` and ``actions`` already work. A scope owns four 

6things: where it sits in the containment hierarchy (its ``specificity``), the 

7resource it can be pinned to, how to name that resource for a human, and how 

8to narrow the usage ledger to it. 

9 

10────────────────────────────────────────────────────────────────────────────── 

11Why an invocation carries a *chain* rather than one scope 

12────────────────────────────────────────────────────────────────────────────── 

13 

14An agent turn is not one governed thing. It is an agent, running a model, in 

15a project, belonging to an organisation — and a rule written against any one 

16of those is a rule about that turn. Matching a single ``(scope_type, 

17scope_id)`` pair meant an agent invocation could not be governed by a 

18model-scoped rule, a project-wide spend cap had nowhere to live, and a 

19model-scoped policy silently did nothing the moment the model was reached 

20through an agent rather than directly. That is the difference between a 

21governance layer and a per-page setting. 

22 

23So an invocation declares a :class:`ScopeChain` — every governed resource it 

24touches — and a rule applies when it targets *any* link in that chain. The 

25chain is built at the call site, where the agent, model and owner are already 

26in hand; nothing here goes back to the database to discover it. 

27 

28Ordering within a chain is by ``specificity``: a rule pinned to one agent is 

29considered before one covering every agent, which is considered before the 

30project's, then the organisation's, then global. Priority still wins — it is 

31the knob the user turns — but two rules at the same priority resolve 

32narrowest-first rather than by insertion order, which is the behaviour a 

33person predicts when they write an exception to a broad rule. 

34""" 

35 

36from __future__ import annotations 

37 

38import logging 

39from abc import ABC 

40from collections.abc import Sequence 

41from dataclasses import dataclass 

42from typing import Any, ClassVar 

43from uuid import UUID 

44 

45from sqlalchemy import and_, case, or_ 

46from sqlalchemy.sql.elements import ColumnElement 

47 

48from app.db.postgres.enums import RuleEnum 

49 

50logger = logging.getLogger(__name__) 

51 

52 

53# ─── Scope ──────────────────────────────────────────────────────────────────── 

54 

55 

56class Scope(ABC): 

57 """One kind of thing a rule can be written about.""" 

58 

59 #: Stable key, stored on ``Rule.scope_type`` and sent over the API. 

60 key: ClassVar[RuleEnum.Scope] 

61 #: Human label for the scope picker. 

62 label: ClassVar[str] 

63 #: One line explaining what writing a rule here governs. 

64 description: ClassVar[str] = "" 

65 #: Containment rank. Higher is narrower; used to order rules at equal 

66 #: priority and to sort the picker from broad to specific. 

67 specificity: ClassVar[int] 

68 #: Whether the scope can be pinned to one resource. ``global`` cannot — 

69 #: there is exactly one of it. 

70 targets_resource: ClassVar[bool] = True 

71 #: Plural noun for "all of them", e.g. "All agents". 

72 plural: ClassVar[str] = "" 

73 

74 # -- usage ledger --------------------------------------------------- 

75 

76 def usage_filter(self, scope_id: UUID | None) -> list[Any]: 

77 """Filters narrowing the usage ledger to this scope. 

78 

79 A quota counts its *own* scope's traffic: a per-agent rate limit must 

80 not be consumed by another agent, and a project-wide cost cap must 

81 count every agent in the project. The ledger records both the invoked 

82 resource and its owning project/organisation, so each scope answers 

83 this for itself rather than the window guessing from a type it was 

84 handed. 

85 """ 

86 from app.db.postgres.models import GovernanceUsage 

87 

88 filters: list[Any] = [GovernanceUsage.scope_type == self.key] 

89 if scope_id is not None: 

90 filters.append(GovernanceUsage.scope_id == scope_id) 

91 return filters 

92 

93 # -- targets -------------------------------------------------------- 

94 # 

95 # What a rule at this scope can be pinned to, and whether a given id is 

96 # something this user may pin to. Both live here so adding a scope stays 

97 # one class: the builder's picker, the create/update validation and the 

98 # list page's "applies to" label are all served from the same definition. 

99 

100 def target_model(self) -> Any: 

101 """The SQLAlchemy model backing this scope's targets, or None. 

102 

103 Imported inside the method rather than at module level: ``models`` 

104 imports ``enums``, and a top-level import here would close the loop. 

105 """ 

106 return None 

107 

108 def targets(self, db: Any, user: Any, ws: Any = None) -> list[dict[str, Any]]: 

109 """Resources of this kind the user may pin a rule to. 

110 

111 Ownership-filtered rather than access-checked row by row: the picker 

112 offers what the user owns, and :meth:`validate` is what refuses an id 

113 they do not. A scope that cannot be pinned returns nothing. 

114 

115 Given the workspace the rule is written in (``ws``), what that 

116 workspace lists — its own, what a project inherits, and the 

117 built-ins (CHAINR Bot: a rule pinned to it governs its use there) — 

118 since a rule governs only invocations in its own workspace, and an 

119 organisation's builder has no business naming a member's personal 

120 agents. Without one, everything the user can reach. 

121 """ 

122 model = self.target_model() 

123 if model is None or not self.targets_resource: 

124 return [] 

125 if ws is not None: 

126 from app.services.workspace import in_scope 

127 

128 clause = in_scope(model, ws) 

129 else: 

130 from app.dependency.resource_access import shared_with 

131 

132 clause = shared_with(model, user, include_system=True) 

133 rows = db.query(model).filter(clause).order_by(model.name.asc()).all() 

134 return [ 

135 {"id": str(row.id), "label": row.name, "scope_type": self.key.value} 

136 for row in rows 

137 ] 

138 

139 def validate(self, db: Any, user: Any, scope_id: UUID) -> bool: 

140 """Whether ``scope_id`` names a resource this user may scope a rule to. 

141 

142 A rule pinned to an id that does not resolve is not a narrow rule — 

143 it is a rule that silently never fires, which is the worst outcome a 

144 governance surface can produce. Creation refuses it instead. 

145 """ 

146 model = self.target_model() 

147 if model is None: 

148 return False 

149 row = db.get(model, scope_id) 

150 if row is None: 

151 return False 

152 if getattr(user, "is_superuser", False): 

153 return True 

154 if getattr(row, "is_system", False) is True: 

155 return True 

156 # Anything the user may read: their own, or a member's. 

157 from fastapi import HTTPException 

158 

159 from app.dependency.resource_access import verify_resource_read 

160 

161 try: 

162 verify_resource_read(row, user, db) 

163 except HTTPException: 

164 return False 

165 return True 

166 

167 # -- catalogue ------------------------------------------------------ 

168 

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

170 """Catalogue entry for this scope, for the rule builder's picker.""" 

171 return { 

172 "key": self.key.value, 

173 "label": self.label, 

174 "description": self.description, 

175 "specificity": self.specificity, 

176 "targets_resource": self.targets_resource, 

177 "plural": self.plural, 

178 } 

179 

180 

181# ─── Registry ───────────────────────────────────────────────────────────────── 

182 

183_REGISTRY: dict[RuleEnum.Scope, Scope] = {} 

184 

185 

186def register_scope(cls: type[Scope]) -> type[Scope]: 

187 """Class decorator adding one scope to the registry.""" 

188 instance = cls() 

189 if instance.key in _REGISTRY: 

190 raise RuntimeError(f"Rule scope '{instance.key}' is already registered.") 

191 _REGISTRY[instance.key] = instance 

192 return cls 

193 

194 

195def get_scope(key: RuleEnum.Scope | str | None) -> Scope | None: 

196 """The scope registered under ``key``, or None if there is none.""" 

197 resolved = coerce_scope(key, default=None) 

198 return _REGISTRY.get(resolved) if resolved is not None else None 

199 

200 

201def scope_keys() -> frozenset[RuleEnum.Scope]: 

202 """Every registered scope key.""" 

203 return frozenset(_REGISTRY) 

204 

205 

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

207 """Registered scopes, broadest first — the order the picker offers them.""" 

208 return [ 

209 scope.spec() 

210 for scope in sorted(_REGISTRY.values(), key=lambda s: s.specificity) 

211 ] 

212 

213 

214def coerce_scope( 

215 value: RuleEnum.Scope | str | None, 

216 default: RuleEnum.Scope | None = RuleEnum.Scope.global_, 

217) -> RuleEnum.Scope | None: 

218 """``value`` as a scope enum member, or ``default`` when it is not one. 

219 

220 Accepts both spellings, because both are in circulation: SQLAlchemy 

221 persists an enum's *name* (``global_``) while the API and svc-ai speak its 

222 *value* (``global``). A string that is neither is not silently promoted to 

223 something narrower or broader — it falls back to ``default``, and the 

224 caller decides what that means. 

225 """ 

226 if value is None: 

227 return default 

228 if isinstance(value, RuleEnum.Scope): 

229 return value 

230 text = str(value) 

231 try: 

232 return RuleEnum.Scope[text] 

233 except KeyError: 

234 pass 

235 try: 

236 return RuleEnum.Scope(text) 

237 except ValueError: 

238 return default 

239 

240 

241# ─── Scope references and chains ────────────────────────────────────────────── 

242 

243 

244@dataclass(frozen=True, order=False) 

245class ScopeRef: 

246 """One governed resource an invocation touches. 

247 

248 ``scope_id`` of None means the *kind* is in play but no particular 

249 instance — used by callers that know a model was involved but not which 

250 record it was. A rule pinned to a specific resource will not match such a 

251 reference, which is the safe direction: a targeted rule must never fire on 

252 a resource it was not written for. 

253 """ 

254 

255 scope_type: RuleEnum.Scope 

256 scope_id: UUID | None = None 

257 

258 @property 

259 def specificity(self) -> int: 

260 scope = _REGISTRY.get(self.scope_type) 

261 base = scope.specificity if scope else 0 

262 return base * 2 + (1 if self.scope_id else 0) 

263 

264 def as_dict(self) -> dict[str, str | None]: 

265 return { 

266 "scope_type": self.scope_type.value, 

267 "scope_id": str(self.scope_id) if self.scope_id else None, 

268 } 

269 

270 

271#: An invocation's full set of governed references, narrowest first. 

272ScopeChain = tuple[ScopeRef, ...] 

273 

274 

275def _uuid(value: str | UUID | None) -> UUID | None: 

276 """UUID form of ``value``, or None when absent or malformed.""" 

277 if value is None: 

278 return None 

279 if isinstance(value, UUID): 

280 return value 

281 try: 

282 return UUID(str(value)) 

283 except (ValueError, AttributeError, TypeError): 

284 return None 

285 

286 

287def ref( 

288 scope_type: RuleEnum.Scope | str | None, 

289 scope_id: str | UUID | None = None, 

290) -> ScopeRef | None: 

291 """One reference, or None when ``scope_type`` names no registered scope. 

292 

293 Returning None rather than defaulting to global is deliberate here: a 

294 chain built from an unrecognised type would silently widen to *everything* 

295 at exactly the moment the caller believed it had narrowed. 

296 """ 

297 resolved = coerce_scope(scope_type, default=None) 

298 if resolved is None or resolved not in _REGISTRY: 

299 if scope_type is not None: 

300 logger.warning( 

301 "Ignoring unknown rule scope %r in invocation chain", scope_type 

302 ) 

303 return None 

304 scope = _REGISTRY[resolved] 

305 if not scope.targets_resource: 

306 return ScopeRef(resolved, None) 

307 resource_id = _uuid(scope_id) 

308 if scope_id is not None and resource_id is None: 

309 # Silently dropping it would widen the reference from "this agent" to 

310 # "every agent" — more rules would then apply, which is the safe 

311 # direction, but it would apply them for a reason nobody could see. 

312 logger.warning( 

313 "Rule scope %s was given an unparseable id %r; treating it as every %s", 

314 resolved.value, 

315 scope_id, 

316 resolved.value, 

317 ) 

318 return ScopeRef(resolved, resource_id) 

319 

320 

321def chain(*refs: ScopeRef | None) -> ScopeChain: 

322 """A de-duplicated chain, narrowest first. 

323 

324 ``global`` is dropped: every rule query includes global rules 

325 unconditionally, so carrying the reference would only invite a caller to 

326 believe a chain without it excludes them. 

327 """ 

328 seen: dict[tuple[RuleEnum.Scope, UUID | None], ScopeRef] = {} 

329 for item in refs: 

330 if item is None or item.scope_type == RuleEnum.Scope.global_: 

331 continue 

332 seen.setdefault((item.scope_type, item.scope_id), item) 

333 return tuple(sorted(seen.values(), key=lambda r: -r.specificity)) 

334 

335 

336def owner_refs(resource: Any) -> list[ScopeRef]: 

337 """The project/organisation references implied by an ownable resource. 

338 

339 Every governed resource carries the three-column ownership of 

340 ``OwnableMixin.Resource``, so "which project is this agent in?" is already 

341 answered on the row the call site is holding. A user-owned resource yields 

342 nothing — a user is not a governance scope; their rules are already 

343 filtered by owner. 

344 """ 

345 refs: list[ScopeRef] = [] 

346 if resource is None: 

347 return refs 

348 project_id = getattr(resource, "owner_project_id", None) 

349 organisation_id = getattr(resource, "owner_organisation_id", None) 

350 if project_id: 

351 refs.append(ScopeRef(RuleEnum.Scope.project, _uuid(project_id))) 

352 if organisation_id: 

353 refs.append(ScopeRef(RuleEnum.Scope.organisation, _uuid(organisation_id))) 

354 return refs 

355 

356 

357def invocation_chain( 

358 *, 

359 agent: Any = None, 

360 skill: Any = None, 

361 worker: Any = None, 

362 model_id: str | UUID | None = None, 

363 owner: Any = None, 

364 extra: Sequence[ScopeRef] = (), 

365) -> ScopeChain: 

366 """The chain for one invocation, built from the rows the caller has. 

367 

368 This is the call sites' single entry point, and it exists so that "what 

369 does this turn touch?" is answered once rather than assembled by hand in 

370 five routers that would drift. Pass the ORM rows already loaded for the 

371 request — each contributes its own reference *and* the project or 

372 organisation that owns it, which is where an ownership-scoped rule lives. 

373 

374 ``owner`` covers the case where the governed resource is not itself 

375 ownable but runs on behalf of something that is. 

376 """ 

377 links: list[ScopeRef | None] = list(extra) 

378 for resource, scope_type in ( 

379 (agent, RuleEnum.Scope.agent), 

380 (skill, RuleEnum.Scope.skill), 

381 (worker, RuleEnum.Scope.worker), 

382 ): 

383 if resource is None: 

384 continue 

385 links.append(ref(scope_type, getattr(resource, "id", None))) 

386 links.extend(owner_refs(resource)) 

387 if model_id: 

388 links.append(ref(RuleEnum.Scope.model, model_id)) 

389 links.extend(owner_refs(owner)) 

390 return chain(*links) 

391 

392 

393def parse_chain(raw: Any) -> ScopeChain: 

394 """A chain from the loosely-typed form an evaluation context carries. 

395 

396 Accepts a list of ``{"scope_type": ..., "scope_id": ...}`` dicts, of 

397 ``ScopeRef`` objects, or of ``(type, id)`` pairs. Entries that name no 

398 registered scope are dropped with a warning rather than widening the 

399 chain. 

400 """ 

401 if not raw: 

402 return () 

403 items: list[ScopeRef | None] = [] 

404 for entry in raw if isinstance(raw, (list, tuple)) else [raw]: 

405 if isinstance(entry, ScopeRef): 

406 items.append(entry) 

407 elif isinstance(entry, dict): 

408 items.append(ref(entry.get("scope_type"), entry.get("scope_id"))) 

409 elif isinstance(entry, (list, tuple)) and len(entry) == 2: 

410 items.append(ref(entry[0], entry[1])) 

411 else: 

412 logger.warning("Ignoring malformed scope reference %r", entry) 

413 return chain(*items) 

414 

415 

416def serialize(links: Sequence[ScopeRef]) -> list[dict[str, str | None]]: 

417 """A chain in the wire form an evaluation context and svc-ai use.""" 

418 return [link.as_dict() for link in links] 

419 

420 

421# ─── Matching ───────────────────────────────────────────────────────────────── 

422 

423 

424def chain_filter(links: Sequence[ScopeRef]) -> ColumnElement[bool]: 

425 """The SQLAlchemy filter selecting rules applicable to ``links``. 

426 

427 A rule matches when: 

428 • its scope is global — those govern everything, always; or 

429 • its scope_type is a kind the invocation touches and its scope_id is 

430 NULL (the rule covers every resource of that kind); or 

431 • its scope_type and scope_id name one of the exact resources involved. 

432 """ 

433 from app.db.postgres.models import Rule 

434 

435 clauses: list[ColumnElement[bool]] = [ 

436 Rule.scope_type == RuleEnum.Scope.global_, 

437 ] 

438 grouped: dict[RuleEnum.Scope, set[UUID]] = {} 

439 for link in links: 

440 if link.scope_type == RuleEnum.Scope.global_: 

441 continue 

442 ids = grouped.setdefault(link.scope_type, set()) 

443 if link.scope_id: 

444 ids.add(link.scope_id) 

445 

446 for scope_type, ids in grouped.items(): 

447 id_clause: ColumnElement[bool] = Rule.scope_id.is_(None) 

448 if ids: 

449 id_clause = or_(id_clause, Rule.scope_id.in_(sorted(ids))) 

450 clauses.append(and_(Rule.scope_type == scope_type, id_clause)) 

451 

452 return or_(*clauses) 

453 

454 

455def specificity_expression(): 

456 """SQL ordering key: how narrowly a rule is aimed. 

457 

458 Computed in the database rather than in Python because the ordering has to 

459 hold across the whole result set, not just the page a caller happens to 

460 have loaded. Doubling the scope rank leaves room for the pinned-resource 

461 bit underneath it, so ``agent:X`` outranks ``agent:*`` which outranks 

462 ``project:*`` — the same arithmetic as :attr:`ScopeRef.specificity`. 

463 """ 

464 from app.db.postgres.models import Rule 

465 

466 ranks = [ 

467 (Rule.scope_type == scope.key, scope.specificity * 2) 

468 for scope in _REGISTRY.values() 

469 ] 

470 scope_rank = case(*ranks, else_=0) if ranks else case((True, 0), else_=0) 

471 pinned = case((Rule.scope_id.isnot(None), 1), else_=0) 

472 return scope_rank + pinned 

473 

474 

475def describe( 

476 scope_type: RuleEnum.Scope | str | None, 

477 scope_id: str | UUID | None = None, 

478) -> str: 

479 """A human phrase for one rule's scope, used in logs and audit trails.""" 

480 scope = get_scope(scope_type) 

481 if scope is None: 

482 return "unknown scope" 

483 if not scope.targets_resource: 

484 return scope.label 

485 if scope_id: 

486 return f"{scope.label} {scope_id}" 

487 return scope.plural or f"all {scope.label.lower()}s" 

488 

489 

490# ─── The scopes ─────────────────────────────────────────────────────────────── 

491# 

492# Specificity is "how precisely is this aimed at one invocation", which is 

493# containment down the execution path: an organisation contains projects, 

494# which contain agents, which run skills, which are graphs of workers. A model 

495# sits between project and agent — a model-scoped rule reaches every agent 

496# using that model, so it is broader than an agent's own rule, but it names a 

497# concrete participant in the call where a project only names where it lives. 

498# 

499# The ordering decides nothing about whether a rule applies — every matching 

500# rule applies. It decides the order they are *considered* in at equal 

501# priority, so a narrow exception is evaluated before the broad rule it 

502# qualifies. 

503 

504 

505@register_scope 

506class GlobalScope(Scope): 

507 key = RuleEnum.Scope.global_ 

508 label = "Everything" 

509 description = "Applies to every invocation you make, whatever it runs through." 

510 specificity = 0 

511 targets_resource = False 

512 plural = "Everything" 

513 

514 def usage_filter(self, scope_id: UUID | None) -> list[Any]: 

515 """No narrowing — counting everything is what makes it global.""" 

516 return [] 

517 

518 

519@register_scope 

520class OrganisationScope(Scope): 

521 key = RuleEnum.Scope.organisation 

522 label = "Organisation" 

523 description = ( 

524 "Applies to every invocation by resources this organisation owns, " 

525 "across all of its projects." 

526 ) 

527 specificity = 1 

528 plural = "All organisations" 

529 

530 def usage_filter(self, scope_id: UUID | None) -> list[Any]: 

531 """Counts by *owner*, not by invoked resource. 

532 

533 An organisation never appears as ``scope_type`` on a ledger row — the 

534 row records the agent or model that ran. What makes the row the 

535 organisation's is the owning organisation stamped beside it, which is 

536 exactly what a cap covering "everything this organisation spends" 

537 has to add up. 

538 """ 

539 from app.db.postgres.models import GovernanceUsage 

540 

541 if scope_id is not None: 

542 return [GovernanceUsage.owner_organisation_id == scope_id] 

543 return [GovernanceUsage.owner_organisation_id.isnot(None)] 

544 

545 def target_model(self) -> Any: 

546 from app.db.postgres.models import Organisation 

547 

548 return Organisation 

549 

550 def targets(self, db: Any, user: Any, ws: Any = None) -> list[dict[str, Any]]: 

551 """Organisations the user belongs to — membership is the filter, 

552 since an organisation has members rather than an owner. 

553 

554 In a workspace, the one organisation a rule there can concern: the 

555 organisation itself, or an organisation project's parent. A personal 

556 workspace's rules govern nothing an organisation owns, so none. 

557 """ 

558 from app.db.postgres.models import Organisation, UserOrganisation 

559 from app.services.workspace import WorkspaceKind 

560 

561 if ws is not None: 

562 org = ws if ws.kind is WorkspaceKind.organisation else ws.parent 

563 if org is None or org.kind is not WorkspaceKind.organisation: 

564 return [] 

565 return [ 

566 { 

567 "id": str(org.id), 

568 "label": org.name or "", 

569 "scope_type": self.key.value, 

570 } 

571 ] 

572 

573 query = db.query(Organisation) 

574 if not getattr(user, "is_superuser", False): 

575 query = query.join( 

576 UserOrganisation, 

577 UserOrganisation.organisation_id == Organisation.id, 

578 ).filter(UserOrganisation.user_id == user.id) 

579 return [ 

580 {"id": str(row.id), "label": row.name, "scope_type": self.key.value} 

581 for row in query.order_by(Organisation.name.asc()).all() 

582 ] 

583 

584 def validate(self, db: Any, user: Any, scope_id: UUID) -> bool: 

585 from app.db.postgres.models import Organisation, UserOrganisation 

586 

587 if db.get(Organisation, scope_id) is None: 

588 return False 

589 if getattr(user, "is_superuser", False): 

590 return True 

591 return ( 

592 db.query(UserOrganisation) 

593 .filter( 

594 UserOrganisation.user_id == user.id, 

595 UserOrganisation.organisation_id == scope_id, 

596 ) 

597 .first() 

598 is not None 

599 ) 

600 

601 

602@register_scope 

603class ProjectScope(Scope): 

604 key = RuleEnum.Scope.project 

605 label = "Project" 

606 description = ( 

607 "Applies to every invocation by agents, skills and workers belonging " 

608 "to this project." 

609 ) 

610 specificity = 2 

611 plural = "All projects" 

612 

613 def usage_filter(self, scope_id: UUID | None) -> list[Any]: 

614 """Counts by owning project — see :class:`OrganisationScope`.""" 

615 from app.db.postgres.models import GovernanceUsage 

616 

617 if scope_id is not None: 

618 return [GovernanceUsage.owner_project_id == scope_id] 

619 return [GovernanceUsage.owner_project_id.isnot(None)] 

620 

621 def target_model(self) -> Any: 

622 from app.db.postgres.models import Project 

623 

624 return Project 

625 

626 def targets(self, db: Any, user: Any, ws: Any = None) -> list[dict[str, Any]]: 

627 """Projects — in a workspace, the ones a rule there can concern: 

628 Personal's or an organisation's own projects, or a project itself. 

629 Projects are not inheritable, so the generic filter does not fit.""" 

630 from app.db.postgres.models import Project 

631 from app.services.workspace import WorkspaceKind 

632 

633 if ws is None: 

634 return super().targets(db, user) 

635 if ws.kind is WorkspaceKind.project: 

636 clause = Project.id == ws.id 

637 elif ws.kind is WorkspaceKind.organisation: 

638 clause = Project.owner_organisation_id == ws.id 

639 else: 

640 clause = Project.owner_user_id == ws.id 

641 rows = db.query(Project).filter(clause).order_by(Project.name.asc()).all() 

642 return [ 

643 {"id": str(row.id), "label": row.name, "scope_type": self.key.value} 

644 for row in rows 

645 ] 

646 

647 

648@register_scope 

649class AgentScope(Scope): 

650 key = RuleEnum.Scope.agent 

651 label = "Agent" 

652 description = "Applies whenever this agent runs, including its skills and workers." 

653 specificity = 4 

654 plural = "All agents" 

655 

656 def target_model(self) -> Any: 

657 from app.db.postgres.models import Agent 

658 

659 return Agent 

660 

661 

662@register_scope 

663class SkillScope(Scope): 

664 key = RuleEnum.Scope.skill 

665 label = "Skill" 

666 description = "Applies whenever this skill executes, standalone or inside an agent." 

667 specificity = 5 

668 plural = "All skills" 

669 

670 def target_model(self) -> Any: 

671 from app.db.postgres.models import Skill 

672 

673 return Skill 

674 

675 

676@register_scope 

677class WorkerScope(Scope): 

678 key = RuleEnum.Scope.worker 

679 label = "Worker" 

680 description = "Applies whenever this worker runs as a node in a skill graph." 

681 specificity = 6 

682 plural = "All workers" 

683 

684 def target_model(self) -> Any: 

685 from app.db.postgres.models import CustomWorker 

686 

687 return CustomWorker 

688 

689 

690@register_scope 

691class ModelScope(Scope): 

692 key = RuleEnum.Scope.model 

693 label = "Model" 

694 description = ( 

695 "Applies whenever this model answers — whether prompted directly or " 

696 "reached through an agent." 

697 ) 

698 specificity = 3 

699 plural = "All models" 

700 

701 def usage_filter(self, scope_id: UUID | None) -> list[Any]: 

702 """A model's quota counts every turn the model answered — prompted 

703 directly, or reached through an agent, a skill, an evaluation or a 

704 dashboard tile — as the rule applies to all of them. 

705 

706 Counted on ``ai_model_id``, the model that ran, 

707 which every ledger row records. The base filter counted rows 

708 *recorded at* model scope, which only a direct prompt is: an agent 

709 turn on the model is recorded at agent scope, so a model's cap 

710 governed agent turns without ever counting them. 

711 """ 

712 from app.db.postgres.models import GovernanceUsage 

713 

714 if scope_id is None: 

715 return [GovernanceUsage.ai_model_id.isnot(None)] 

716 return [GovernanceUsage.ai_model_id == scope_id] 

717 

718 def targets(self, db: Any, user: Any, ws: Any = None) -> list[dict[str, Any]]: 

719 """Models come from svc-ai's catalogue, not a table in this service. 

720 

721 svc-core mirrors nothing about models, so the picker is served by the 

722 same call the model list page makes. A svc-ai outage yields an empty 

723 list rather than an error: a user should still be able to write a 

724 global or agent-scoped rule when the model catalogue is unreachable. 

725 """ 

726 from app.services.ai_client import list_models 

727 

728 try: 

729 models = list_models(is_available=True) or [] 

730 except Exception: # noqa: BLE001 — any transport fault means "no list" 

731 logger.warning("Model catalogue unavailable; rule scope picker is empty") 

732 return [] 

733 return [ 

734 { 

735 "id": str(model.get("id")), 

736 "label": model.get("display_name") 

737 or model.get("model_name") 

738 or str(model.get("id")), 

739 "scope_type": self.key.value, 

740 } 

741 for model in models 

742 # A rule governs an invocation; an embedding model answers none. 

743 if model.get("id") and model.get("is_chat", True) 

744 ] 

745 

746 def validate(self, db: Any, user: Any, scope_id: UUID) -> bool: 

747 """Accepted whenever svc-ai confirms the model, and also when it 

748 cannot be asked. 

749 

750 The fail-open direction is deliberate and bounded: refusing to *save* 

751 a rule because a downstream service is unreachable would make the 

752 governance surface unavailable whenever svc-ai is, and a rule pinned 

753 to a model id that turns out not to exist simply never matches — it 

754 cannot mis-govern anything. 

755 """ 

756 from app.services.ai_client import get_model 

757 

758 try: 

759 return get_model(scope_id) is not None 

760 except Exception: # noqa: BLE001 — see the fail-open note above 

761 logger.warning( 

762 "Could not confirm model %s with svc-ai; accepting the rule scope", 

763 scope_id, 

764 ) 

765 return True