Coverage for app / services / rule_engine.py: 98%
510 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2Rule evaluation engine.
4Evaluates active governance rules against LLM invocations at two points, in
5the order a request meets its layers (``app.services.rules.layers``):
6 1. Before the prompt reaches svc-ai — Access rules (may it run at all?),
7 then Input rules (what may the model read?).
8 2. After the response returns from svc-ai — Output rules (what may people
9 receive?).
10Priority orders the rules within a layer, never across layers.
12──────────────────────────────────────────────────────────────────────────────
13Where the vocabulary lives
14──────────────────────────────────────────────────────────────────────────────
16This module owns *when* rules are evaluated, which rules apply, and how their
17effects are recorded. It deliberately owns none of the grammar: the fields a
18condition may reference, the operators it may use and the actions a rule may
19carry are each a registry in ``app.services.rules``, served to the frontend by
20``GET /app/rules/catalogue``.
22That split is what makes widening the vocabulary additive. A new condition
23field is one class in ``app.services.rules.fields``; a new action is one class
24in ``app.services.rules.actions``. Neither requires an edit here, and neither
25requires a frontend release for the rule builder to offer it.
27Unknown fields, operators and actions never match and never fire — they log a
28warning instead. A rule the engine cannot understand must not be treated as
29satisfied, or one malformed block rule refuses every invocation on the
30platform.
31"""
33import logging
34from collections.abc import Sequence
35from dataclasses import dataclass, replace
36from decimal import Decimal
37from typing import Any, NamedTuple, Protocol
38from uuid import uuid4
40from sqlalchemy import case
41from sqlalchemy.orm import Session
43from app.db.postgres.enums import GovernanceEnum, HistoryEnum, RuleEnum
44from app.db.postgres.models import Rule
45from app.services import governance_activity as activity_service
46from app.services import history as history_service
47from app.services.rules import actions as action_registry
48from app.services.rules import conditions as condition_registry
49from app.services.rules import fields as field_registry
50from app.services.rules import layers as layer_registry
51from app.services.rules import operators as operator_registry
52from app.services.rules import scopes as scope_registry
53from app.services.rules.actions import (
54 EVIDENCE_CONTEXT_KEY,
55 RESERVE_CONTEXT_KEY,
56 USAGE_CONTEXT_KEY,
57 Enforcement,
58 TextAction,
59 WithholdDecision,
60)
61from app.services.rules import pii
62from app.services.rules.pii import (
63 filter_pii, # noqa: F401 — re-exported; callers import it from here
64)
65from app.services.rules.redaction import OWNER_CONTEXT_KEY
66from app.services.rules.scopes import ScopeChain
67from app.services.usage import TurnReserveLookup, UsageWindow, UsageWindows
68from app.util import web_domains
70logger = logging.getLogger(__name__)
72# ─── Vocabulary ───────────────────────────────────────────────────────────────
73#
74# Kept as module-level names because callers and tests reference them, but
75# each is now a *view* of the registry rather than a second list to maintain.
76# They are computed at import time: registration happens on module import, and
77# nothing registers an operator or field after startup.
80def _valid_context_fields() -> frozenset[str]:
81 """Every condition field the engine understands."""
82 return field_registry.field_keys()
85def _valid_operators() -> frozenset[str]:
86 """Every comparison operator the engine understands."""
87 return operator_registry.operator_keys()
90def _valid_actions(layer: RuleEnum.Layer) -> frozenset[str]:
91 """Every action type valid on a rule in ``layer``."""
92 return action_registry.action_types(layer)
95# ─── Exception ────────────────────────────────────────────────────────────────
98class BlockLike(Protocol):
99 """The identity every block carries, wherever it was enforced.
101 ``RuleBlock`` (enforced in svc-core) and ``ai_client.RuleBlockedError``
102 (enforced inside svc-ai and reported back) both satisfy this, so one
103 trace builder serves both and a blocked turn looks the same in History
104 regardless of which service made the decision.
105 """
107 rule_name: str
108 message: str
109 rule_id: str | None
110 rule_version: int | None
111 scope_type: str | None
112 scope_id: str | None
115class RuleBlock(Exception):
116 """Raised when an Access or Input rule refuses the invocation.
118 Carries the firing rule's full identity, not just its name. ``Rule.name``
119 is mutable and not unique, so a trace recording only a name cannot be
120 resolved back to the policy that produced it — rename or delete the rule
121 and every historical block points at nothing. ``rule_id`` plus
122 ``rule_version`` are what make a block defensible after the fact.
124 The identity fields are optional so the exception stays constructible in
125 tests and from callers that only have a name to hand.
126 """
128 def __init__(
129 self,
130 rule_name: str,
131 message: str,
132 *,
133 rule_id: str | None = None,
134 rule_version: int | None = None,
135 scope_type: str | None = None,
136 scope_id: str | None = None,
137 evaluations: list[dict[str, Any]] | None = None,
138 ) -> None:
139 self.rule_name = rule_name
140 self.message = message
141 self.rule_id = rule_id
142 self.rule_version = rule_version
143 self.scope_type = scope_type
144 self.scope_id = scope_id
145 # Every rule evaluated before (and including) the one that refused, so
146 # a blocked turn's trace can show what else ran on the prompt rather
147 # than the refusal alone.
148 self.evaluations = list(evaluations or [])
149 super().__init__(message)
152#: ``SpendLimit.kind`` of a swarm task's share of its run's budget.
153SWARM_LIMIT = "swarm"
156@dataclass(frozen=True)
157class SpendLimit:
158 """The most one turn may spend: what is left of the tightest cost cap
159 (or platform allowance) that let it through.
161 svc-core sends ``usd`` to svc-ai on every call the turn makes
162 (``X-Spend-Limit``, ``ai_client.in_spend_limit``), and svc-ai refuses the
163 turn's next model call once it has spent that. The rest names what set
164 it, so a turn stopped there can say which budget stopped it and when it
165 starts again (``SpendLimitReached``).
166 """
168 usd: Decimal
169 #: The cap's rule — None for the platform allowance, which no one wrote.
170 rule_id: str | None
171 rule_name: str
172 rule_version: int | None
173 #: The cap itself; for a swarm limit, what the task's share had left when
174 #: the call started (``swarms.budget.limit``).
175 cap_usd: Decimal | None
176 #: When its period starts again (ISO 8601), or None for a trailing window.
177 resets_at: str | None
178 #: ``rule``, ``platform``, or :data:`SWARM_LIMIT` — a swarm task's share
179 #: of its run's budget (``swarms.budget``), which no rule wrote.
180 kind: str = "rule"
181 scope_type: str | None = None
182 scope_id: str | None = None
184 def after(self, spent: Decimal | None) -> "SpendLimit":
185 """This limit for a later part of the same turn (a resume after a
186 pause), less what the turn has spent so far — spend the ledger does
187 not hold until the turn ends."""
188 if not spent:
189 return self
190 cap = self.cap_usd
191 if self.kind == SWARM_LIMIT and cap is not None:
192 # A swarm task's cap is its share's remainder: spent too.
193 cap = max(cap - spent, Decimal(0))
194 return replace(self, usd=max(self.usd - spent, Decimal(0)), cap_usd=cap)
196 def ref(self) -> dict[str, Any]:
197 """The identity block an activity row about it carries."""
198 return {
199 "rule": self.rule_name,
200 "rule_id": self.rule_id,
201 "rule_version": self.rule_version,
202 "scope_type": self.scope_type,
203 "scope_id": self.scope_id,
204 }
206 def stop_message(self) -> str:
207 """What a person is told when a turn is stopped at this limit."""
208 figures = {"resets_at": self.resets_at} if self.resets_at else {}
209 if self.kind == SWARM_LIMIT:
210 spent = action_registry.usd_text(self.usd)
211 share = (
212 action_registry.usd_text(self.cap_usd)
213 if self.cap_usd is not None
214 else None
215 )
216 if share is not None and self.usd < self.cap_usd and spent != share:
217 # The run, not the share, ran short.
218 return (
219 f"This task was stopped: the swarm had only {spent} left "
220 f"for it, less than its share ({share})."
221 )
222 return (
223 f"This task was stopped: it reached its share of the swarm's "
224 f"budget ({spent})."
225 )
226 what = (
227 "this workspace's monthly platform allowance"
228 if self.kind == "platform"
229 else f"the budget “{self.rule_name}”"
230 )
231 return (
232 f"This answer was stopped: it reached what was left of {what} "
233 f"({action_registry.usd_text(self.usd)}). "
234 f"{action_registry.resets_phrase(figures)}"
235 )
238def _tighter(limit: SpendLimit | None, other: SpendLimit | None) -> SpendLimit | None:
239 if limit is None:
240 return other
241 if other is None:
242 return limit
243 return other if other.usd < limit.usd else limit
246#: The tighter of two limits, for a caller that adds its own to the rules'
247#: (a swarm task's share of its run, ``targets.spend_ceiling``).
248tighter = _tighter
251@dataclass(frozen=True)
252class Withheld:
253 """An answer an Output rule withheld (the ``withhold`` action).
255 People receive ``message`` in its place. ``original`` is the answer
256 after every other Output rule ran on it — so redacted as they redacted
257 it — and goes to one place only: a review item, when the rule sends it
258 there (``review.record_withheld``). It is never stored where the person
259 it was withheld from can read it.
260 """
262 message: str
263 original: str
264 review: bool
265 #: The rule that withheld it (``_rule_ref``).
266 ref: dict[str, Any]
267 #: The workspace the answer was given in (its key), whose reviewers see it.
268 workspace: str | None = None
270 def meta(self) -> dict[str, Any]:
271 """What the stored answer says of it (``meta.withheld``)."""
272 return {
273 "rule": self.ref.get("rule"),
274 "rule_id": self.ref.get("rule_id"),
275 "rule_version": self.ref.get("rule_version"),
276 "review": self.review,
277 }
280class RulePass(tuple):
281 """What one evaluation pass returns: ``(text, events)``, plus every rule.
283 Unpacks exactly as the bare pair always has, so the many call sites that
284 only want the rewritten text and the fired events are untouched. The
285 extra is ``evaluations``: one entry per *applicable* rule with its
286 outcome, including the rules whose conditions did not hold and the ones
287 that ran and found nothing to do. ``events`` records only what acted, and
288 a trace built from events alone shows one rule where five were checked.
289 """
291 evaluations: list[dict[str, Any]]
292 #: The PII redaction the pass applied, when a ``filter_pii`` or
293 #: ``redact_pii`` action ran — its kinds and its placeholder key, merged
294 #: across rules. Whatever travels with the text (the conversation history
295 #: sent with a prompt, the answers to a paused run, a run's outputs) is
296 #: redacted with exactly this, so a value hidden in the prompt is hidden
297 #: everywhere else it appears, behind the same placeholder.
298 redactor: "pii.Redactor | None"
299 #: The most the turn may spend (passes before the model only): what is left of the
300 #: tightest cost cap or allowance that let it through. None when nothing
301 #: caps it.
302 spend_limit: SpendLimit | None
303 #: The web sources the turn may use (passes before the model only): every
304 #: Tools rule's, merged (``WebPolicy.merge``). svc-ai's web tools hold to
305 #: it (``X-Web-Policy``). None when no Tools rule applied.
306 web_policy: web_domains.WebPolicy | None
307 #: The answer an Output rule withheld (passes after the model only):
308 #: ``text`` is then the rule's message. None when none withheld it.
309 withheld: Withheld | None
311 def __new__(
312 cls,
313 text: str,
314 events: list[dict],
315 evaluations: list[dict[str, Any]] | None = None,
316 redactor: "pii.Redactor | None" = None,
317 spend_limit: SpendLimit | None = None,
318 web_policy: web_domains.WebPolicy | None = None,
319 withheld: Withheld | None = None,
320 ) -> "RulePass":
321 instance = super().__new__(cls, (text, events))
322 instance.evaluations = list(evaluations or [])
323 instance.redactor = redactor
324 instance.spend_limit = spend_limit
325 instance.web_policy = web_policy
326 instance.withheld = withheld
327 return instance
329 def redact(self, value: Any) -> Any:
330 """``value`` through this pass's redaction — every string in it — or
331 unchanged when no redaction action ran."""
332 return value if self.redactor is None else self.redactor.redact_values(value)
334 def redact_history(self, history: list[dict]) -> list[dict]:
335 """Conversation history with each message's content redacted.
337 A rule written after a conversation began, or a value the model said
338 back, would otherwise reach the model again on every later turn: the
339 stored history is sent as it was stored.
340 """
341 if self.redactor is None:
342 return history
343 return [
344 {**message, "content": self.redactor.redact(str(message["content"]))[0]}
345 if isinstance(message, dict) and message.get("content")
346 else message
347 for message in history
348 ]
350 @property
351 def text(self) -> str:
352 return self[0]
354 @property
355 def events(self) -> list[dict]:
356 return self[1]
359# ─── PII ──────────────────────────────────────────────────────────────────────
360#
361# ``filter_pii`` is imported from ``app.services.rules.pii`` and re-exported
362# here, where it has always lived from a caller's point of view. The patterns
363# moved so the ``pii_detected`` condition field can ask "is there PII here?"
364# using exactly the patterns the redaction actions would apply — a detector
365# and a redactor that disagree make the detector useless.
368# ─── Query ────────────────────────────────────────────────────────────────────
371def _scope_filter(links: ScopeChain):
372 """
373 Build the SQLAlchemy filter selecting rules applicable to an invocation.
375 Delegates to :func:`app.services.rules.scopes.chain_filter`, which owns
376 the matching semantics: global rules always apply, a rule covering a whole
377 resource kind applies when the invocation touches that kind, and a rule
378 pinned to one resource applies when that exact resource is involved.
380 The chain is the change that made governance exhaustive. An agent turn
381 touches an agent, a model, a project and an organisation; matching one
382 scope at a time meant a model-scoped rule quietly stopped applying the
383 moment its model was reached through an agent.
384 """
385 return scope_registry.chain_filter(links)
388def _get_applicable_rules(
389 db: Session,
390 layers: RuleEnum.Layer | Sequence[RuleEnum.Layer],
391 owner_user_id: str,
392 links: ScopeChain = (),
393 workspace: Any = None,
394) -> list[Rule]:
395 """Active rules in ``layers`` that govern an invocation in ``workspace``
396 touching ``links``: the workspace's own rules, and — for a project — the rules it
397 inherits from its parent (Required, pinned to it, or declared;
398 ``app/services/inheritance.py``).
400 Governance belongs to where the work happens, not to who does it. A
401 caller that names no workspace gets the one its chain reaches — the
402 project, else the organisation, else the invoker's personal workspace
403 (``workspace.from_chain``) — so an organisation's agent is governed by
404 the organisation's rules, and the invoker's personal rules no longer
405 follow them into it. The workspace's own references (a project and its
406 organisation) join the chain, so a Required rule scoped to the
407 organisation matches inside its projects.
409 Never a built-in rule: a built-in is a definition users create rules
410 from, and governs nobody itself. It has no owner, so the owner filter
411 already leaves it out; ``is_system`` says so outright, so widening which
412 owners' rules apply (organisation membership, say) cannot pull one in.
414 Ordered by layer, in the order a request meets them — an Access rule
415 before any Input rule, whatever their priorities — then by priority, then
416 by how narrowly each rule is aimed. Priority is the knob the user turns,
417 so it wins within a layer; below it, a rule pinned to one agent
418 is considered before one covering every agent, which is considered before
419 the project's and then the organisation's. That is what makes "block
420 everything, except this agent" express what a person means by it, rather
421 than depending on which row was inserted first.
422 """
423 from app.services import workspace as workspace_service
425 ws = workspace or workspace_service.from_chain(db, links, owner_user_id)
426 links = scope_registry.chain(*links, *ws.refs())
427 wanted = [layers] if isinstance(layers, RuleEnum.Layer) else list(layers)
428 flow = case(
429 *((Rule.layer == layer, place) for place, layer in enumerate(RuleEnum.Layer))
430 )
432 return (
433 db.query(Rule)
434 .filter(
435 Rule.layer.in_(wanted),
436 Rule.is_active.is_(True),
437 Rule.is_system.is_(False),
438 workspace_service.governing_rules(ws),
439 _scope_filter(links),
440 )
441 .order_by(
442 flow,
443 Rule.priority.desc(),
444 scope_registry.specificity_expression().desc(),
445 Rule.created_at.asc(),
446 )
447 .all()
448 )
451# ─── Rule identity ────────────────────────────────────────────────────────────
454def _current_rule_versions(db: Session, rules: list[Rule]) -> dict[str, int]:
455 """Map rule id → the version number currently in force for that rule.
457 A thin call into ``history.current_versions``, which every provenance
458 stamp now shares: the same question ("which revision of this is in force
459 right now?") is asked of agents when a turn is recorded, and asking it two
460 different ways invites the two answers to drift.
461 """
462 return history_service.current_versions(
463 db, HistoryEnum.ResourceType.rule, [rule.id for rule in rules]
464 )
467def _rule_ref(rule: Rule, versions: dict[str, int]) -> dict[str, Any]:
468 """Identity block stamped onto every event a rule produces.
470 ``rule`` (the name) is retained for display and for readers that predate
471 this field set; ``rule_id`` and ``rule_version`` are what make the event
472 resolvable back to the exact policy revision that fired.
473 """
474 rule_id = str(rule.id)
475 return {
476 "rule": rule.name,
477 "rule_id": rule_id,
478 "rule_version": versions.get(rule_id),
479 "scope_type": rule.scope_type.value if rule.scope_type else None,
480 "scope_id": str(rule.scope_id) if rule.scope_id else None,
481 }
484def _evaluation(
485 rule: Rule,
486 ref: dict[str, Any],
487 outcome: GovernanceEnum.Outcome,
488 events: list[dict[str, Any]] | None = None,
489) -> dict[str, Any]:
490 """One rule's evaluation, in the shape the activity log stores.
492 Built for **every applicable rule**, including the ones whose conditions
493 did not hold. That is the whole point of the log: an action with nothing
494 to do emits no event, so recording only events would make a redaction rule
495 over a clean prompt indistinguishable from a rule that never ran. See
496 ``app.services.governance_activity``.
497 """
498 events = events or []
499 return {
500 **ref,
501 "layer": rule.layer,
502 "outcome": outcome,
503 "actions": [
504 str(event.get("action", "")) for event in events if event.get("action")
505 ],
506 "detail": activity_service.detail_of(events),
507 }
510# ─── Serialization for svc-ai ─────────────────────────────────────────────────
513def _chain(
514 scope_type: str | RuleEnum.Scope | None = None,
515 scope_id: str | None = None,
516 scopes: Any = None,
517) -> ScopeChain:
518 """A scope chain from either form a caller may pass.
520 ``scopes`` is the full chain and the one to prefer; ``scope_type`` /
521 ``scope_id`` name a single resource and remain accepted because several
522 call sites legitimately govern exactly one thing (a standalone skill run,
523 a direct model prompt). Given both, the single pair is folded in rather
524 than overriding — a caller that names its primary resource *and* its
525 chain means both.
526 """
527 links = list(scope_registry.parse_chain(scopes))
528 single = scope_registry.ref(scope_type, scope_id) if scope_type else None
529 if single is not None:
530 links.append(single)
531 return scope_registry.chain(*links)
534def serialize_rules(
535 db: Session,
536 owner_user_id: str,
537 scope_type: str | None = None,
538 scope_id: str | None = None,
539 scopes: Any = None,
540 workspace: str | None = None,
541) -> list[dict[str, Any]]:
542 """
543 Resolve the user's applicable rules and serialise them
544 into the RuleSpec shape svc-ai expects in ``ExecuteRequest.rules``.
546 This lets svc-ai enforce governance inside its own execution engines
547 (LangGraph skills, workers, graphs, streaming) without a cross-service
548 DB round-trip.
550 ``scopes`` carries the invocation's full chain — agent, model, project,
551 organisation — so svc-ai enforces exactly the set svc-core resolved. A
552 single ``scope_type``/``scope_id`` pair is still accepted for callers
553 whose invocation genuinely governs one resource.
554 """
555 specs: list[dict[str, Any]] = []
556 links = _chain(scope_type, scope_id, scopes)
557 ws = _invocation_workspace(
558 db, {WORKSPACE_CONTEXT_KEY: workspace}, owner_user_id, links
559 )
560 applicable = _get_applicable_rules(
561 db, list(RuleEnum.Layer), owner_user_id, links, ws
562 )
563 # One version lookup for every layer, so svc-ai's own enforcement can
564 # attribute its events to the same revision svc-core evaluated.
565 versions = _current_rule_versions(db, applicable)
566 for rule in applicable:
567 forwarded = _forwardable_actions(rule)
568 if not forwarded:
569 # Every action on this rule is enforced here. Forwarding it would
570 # make svc-ai warn about an unsupported action on every single
571 # invocation, for a rule that is being enforced correctly.
572 continue
573 specs.append(
574 {
575 "rule_id": str(rule.id),
576 "rule_version": versions.get(str(rule.id)),
577 "name": rule.name,
578 "layer": rule.layer.value,
579 "scope_type": rule.scope_type.value,
580 "scope_id": str(rule.scope_id) if rule.scope_id else None,
581 "conditions": rule.conditions or [],
582 "actions": forwarded,
583 "priority": rule.priority,
584 }
585 )
586 return specs
589def _forwardable_actions(rule: Rule) -> list[dict[str, Any]]:
590 """The subset of ``rule``'s actions svc-ai is able to carry out.
592 ``rate_limit`` and ``cost_cap`` read svc-core's usage ledger, which svc-ai
593 has no access to — deliberately, since keeping the counter local is what
594 lets a cap be judged without a cross-service hop on the inference path.
595 They are enforced here before the request is sent, so sending them too
596 would be asking svc-ai to do something it cannot and does not need to.
598 An action the registry does not recognise is forwarded unchanged rather
599 than dropped: svc-ai owns its own vocabulary, and a newer svc-ai may
600 understand something this svc-core does not.
601 """
602 forwarded: list[dict[str, Any]] = []
603 for action in rule.actions or []:
604 registered = action_registry.get_action(rule.layer, action.get("type", ""))
605 if registered is not None and registered.enforced_in is Enforcement.core_only:
606 continue
607 forwarded.append(action)
608 return forwarded
611# ─── Condition evaluation ─────────────────────────────────────────────────────
612#
613# Thin wrappers over ``app.services.rules.conditions``. They stay because the
614# call sites and tests here name them, and because keeping one seam between
615# "the engine" and "the grammar" makes the grammar swappable.
618def _condition_matches(condition: dict[str, Any], context: dict[str, Any]) -> bool:
619 """Return True if a single condition is satisfied by the context."""
620 return condition_registry.condition_matches(condition, context)
623def _all_conditions_match(conditions: list[dict], context: dict[str, Any]) -> bool:
624 """All conditions must match (AND semantics). Empty list → always matches."""
625 return condition_registry.all_conditions_match(conditions, context)
628class _Applied(NamedTuple):
629 """What one matched rule's actions did (:func:`_apply_text_actions`)."""
631 #: The text, rewritten by any action that rewrites it.
632 text: str
633 events: list[dict]
634 #: The refusal, when an action refused the invocation.
635 block: "BlockDecisionWithRef | None" = None
636 #: The PII redaction the actions applied, merged.
637 redactor: "pii.Redactor | None" = None
638 #: The least of the spend limits its cost caps set.
639 limit: Decimal | None = None
640 #: The web sources its Tools actions set, merged.
641 web: web_domains.WebPolicy | None = None
642 #: Its Output action's decision to withhold the answer.
643 withhold: WithholdDecision | None = None
646def _apply_text_actions(
647 rule: Rule,
648 text: str,
649 context: dict[str, Any],
650 ref: dict[str, Any],
651) -> _Applied:
652 """Run every action on one matched rule against ``text``.
654 Returns what they did (:class:`_Applied`): the text, the events, a
655 refusal, the redaction, a spend limit (``ActionOutcome.spend_limit``),
656 web sources (``ActionOutcome.web_policy``) and a decision to withhold the
657 answer (``ActionOutcome.withhold``). Actions after a block are not run:
658 the invocation is over, and an action that rewrote text nobody will ever
659 see would only add a misleading event to the trail.
660 """
661 events: list[dict] = []
662 redactor: pii.Redactor | None = None
663 limit: Decimal | None = None
664 web: web_domains.WebPolicy | None = None
665 withhold: WithholdDecision | None = None
666 for action in rule.actions or []:
667 action_type: str = action.get("type", "")
668 registered = action_registry.get_action(rule.layer, action_type)
670 if registered is None or not isinstance(registered, TextAction):
671 logger.warning(
672 "%s rule %r has unsupported action %r — skipped. Valid: %s",
673 layer_registry.get(rule.layer).label,
674 rule.name,
675 action_type,
676 ", ".join(sorted(_valid_actions(rule.layer))),
677 )
678 continue
680 outcome = registered.apply(action, text, context)
681 text = outcome.text
682 events.extend({**ref, **event} for event in outcome.events)
683 if outcome.redactor is not None:
684 redactor = outcome.redactor.merged(redactor)
685 if outcome.spend_limit is not None:
686 limit = (
687 outcome.spend_limit
688 if limit is None
689 else min(limit, outcome.spend_limit)
690 )
691 if outcome.web_policy is not None:
692 web = outcome.web_policy.merge(web)
693 if outcome.withhold is not None and withhold is None:
694 withhold = outcome.withhold
696 if outcome.block is not None:
697 # A refusal has to name the action that made it and say what the
698 # caller was told. ``block`` itself emits no event of its own —
699 # raising the exception was the point — while ``rate_limit``
700 # describes the figures it judged, so the message is folded into
701 # that event rather than added beside it. Either way the activity
702 # log ends up with one row naming one action.
703 if outcome.events:
704 events[-1] = {**events[-1], "message": outcome.block.message}
705 else:
706 events.append(
707 {**ref, "action": action_type, "message": outcome.block.message}
708 )
709 return _Applied(
710 text, events, BlockDecisionWithRef(outcome.block.message, ref), redactor
711 )
713 return _Applied(text, events, None, redactor, limit, web, withhold)
716class BlockDecisionWithRef:
717 """A block decision paired with the identity of the rule that made it."""
719 def __init__(self, message: str, ref: dict[str, Any]) -> None:
720 self.message = message
721 self.ref = ref
724# ─── Before the model: Access and Input rules ────────────────────────────────
727#: Context key carrying an invocation's full scope chain — every governed
728#: resource the call touches. Call sites that know more than one (an agent
729#: turn knows its agent, its model and its owners) set this; the older
730#: ``scope_type``/``scope_id`` pair still works and is folded in.
731SCOPES_CONTEXT_KEY = "scopes"
733#: Context key carrying the key of the workspace the invocation happens in
734#: (``app/services/workspace.py``) — whose rules govern it, whose quotas it
735#: counts against, whose review queue and activity it lands in. A caller
736#: that knows (a chat in a project, using an agent the project inherits) sets
737#: it; one that doesn't gets the workspace its chain reaches.
738WORKSPACE_CONTEXT_KEY = "workspace"
741def _invocation_workspace(
742 db: Session, context: dict[str, Any], owner_user_id: str, links: ScopeChain
743):
744 """The workspace an evaluation context names, or its chain's."""
745 from app.services import workspace as workspace_service
747 key = context.get(WORKSPACE_CONTEXT_KEY)
748 if key:
749 try:
750 return workspace_service.from_key(db, str(key))
751 except Exception:
752 logger.warning(
753 "Rule context named workspace %r, which can't be read; "
754 "governing by the invocation's own resources instead",
755 key,
756 )
757 return workspace_service.from_chain(db, links, owner_user_id)
760#: Context key carrying the id of the turn being governed. Minted once per
761#: request by the caller and put on *both* phases' contexts, so the rules
762#: that ran on a prompt and those that ran on its response group together in
763#: the activity log — which is how somebody monitoring governance across
764#: several agents reads it. A caller that does not set
765#: one still records; those evaluations simply stand alone.
766INVOCATION_CONTEXT_KEY = "invocation_id"
769def new_invocation_id() -> str:
770 """An id for one turn, to put on both phases' evaluation contexts."""
771 return str(uuid4())
774def model_fields(model_info: dict[str, Any] | None) -> dict[str, Any]:
775 """The rule context's fields for the model a turn runs on: what a
776 condition on the model reads (``model_name``, ``provider``)."""
777 info = model_info or {}
778 provider = info.get("provider")
779 if isinstance(provider, dict):
780 provider = provider.get("name")
781 return {
782 "model_id": str(info.get("id") or ""),
783 "model_name": info.get("model_name"),
784 "provider": provider,
785 }
788def _chain_from_context(context: dict[str, Any]) -> ScopeChain:
789 """The scope chain an evaluation context describes.
791 Reads ``scopes`` first and falls back to the single ``scope_type`` /
792 ``scope_id`` pair, so every existing call site keeps the behaviour it
793 had while the ones that can say more get the wider matching.
794 """
795 return _chain(
796 context.get("scope_type"),
797 context.get("scope_id"),
798 context.get(SCOPES_CONTEXT_KEY),
799 )
802_PHASE_INPUT = GovernanceEnum.Phase.input
803_PHASE_OUTPUT = GovernanceEnum.Phase.output
806def _record_activity(
807 db: Session,
808 evaluations: list[dict[str, Any]],
809 context: dict[str, Any],
810 owner_user_id: str,
811 phase: GovernanceEnum.Phase,
812 workspace: Any = None,
813) -> None:
814 """Append the activity rows for one evaluation pass.
816 The identity of what was governed comes off the evaluation context, which
817 every call site already builds for the rules themselves — so a new caller
818 gets a usable log entry without having to know this exists.
820 Not committed here: the rows belong to the same transaction as the turn
821 they describe, exactly as the usage ledger does (see
822 ``app.services.governance_activity``). A caller that evaluates rules in a
823 short-lived session of its own commits it.
824 """
825 activity_service.record(
826 db,
827 evaluations,
828 owner_user_id=owner_user_id,
829 phase=phase,
830 invocation_id=context.get(INVOCATION_CONTEXT_KEY),
831 execution_type=context.get("execution_type"),
832 conversation_id=context.get("conversation_id"),
833 agent_id=context.get("agent_id"),
834 ai_model_id=context.get("model_id"),
835 workspace=workspace,
836 )
839def evaluate_input(
840 db: Session,
841 prompt: str,
842 context: dict[str, Any],
843 owner_user_id: str,
844) -> RulePass:
845 """
846 Evaluate the Access, Input and Tools rules against a prompt before it
847 reaches svc-ai — every Access rule first, then every Input rule, then
848 every Tools rule, each layer in priority order. An Access rule
849 conditioned on the prompt sees it as written, before any Input rule
850 redacts it. The Tools rules set the web sources the turn may use
851 (``RulePass.web_policy``).
853 ``context`` should include: execution_type, user_id, and optionally
854 scope_type and scope_id for non-global rule matching.
856 Returns:
857 (filtered_prompt, events) — prompt may be modified by redact_pii —
858 as a :class:`RulePass` also carrying every applicable rule's outcome.
860 Raises:
861 RuleBlock if a block action fires; it carries the evaluations so far.
862 """
863 links = _chain_from_context(context)
864 ws = _invocation_workspace(db, context, owner_user_id, links)
866 rules = _get_applicable_rules(
867 db, layer_registry.before_model(), owner_user_id, links, ws
868 )
870 versions = _current_rule_versions(db, rules)
872 # One cache for the whole evaluation, but a window *per rule scope*.
873 # Several rules capping the same scope cost one set of queries rather than
874 # three, and two actions in one request cannot see different totals — but
875 # a rule capping one agent still counts that agent while a project-wide
876 # cap beside it counts the project. Handing every rule the invocation's
877 # own scope would have judged one against the other's population. The
878 # queries inside are lazy: a request governed by no quota rule never
879 # touches the ledger.
880 usage = UsageWindows(db, owner_user_id)
881 # The evidence gate's reading of the caller's evaluation runs — lazy and
882 # cached like the usage windows. Imported here, not at module scope: the
883 # evaluation package's targets import this engine.
884 from app.services.evaluation.evidence import EvidenceLookup
886 evidence = EvidenceLookup(db, owner_user_id, ws)
887 # What a turn like this one usually costs — read only if a cost cap with
888 # little left asks (its ``reserve``), and once for every cap that does.
889 reserve = _turn_reserve(db, context, ws)
891 events: list[dict] = []
892 evaluations: list[dict] = []
893 filtered = prompt
894 redactor: pii.Redactor | None = None
895 limit: SpendLimit | None = None
896 web: web_domains.WebPolicy | None = None
898 # The platform's own cap on the workspace comes before any of its rules:
899 # no budget a workspace writes can spend past it.
900 allowance_pass = _check_allowance(
901 db, filtered, context, owner_user_id, ws, reserve, evaluations
902 )
903 if allowance_pass is not None:
904 allowance_events, limit = allowance_pass
905 events.extend(allowance_events)
907 for rule in rules:
908 eval_ctx = {
909 **context,
910 "prompt": filtered,
911 USAGE_CONTEXT_KEY: usage.for_rule(rule),
912 EVIDENCE_CONTEXT_KEY: evidence,
913 RESERVE_CONTEXT_KEY: reserve,
914 OWNER_CONTEXT_KEY: owner_user_id,
915 }
916 ref = _rule_ref(rule, versions)
917 if not _all_conditions_match(rule.conditions, eval_ctx):
918 # Recorded, not skipped: "this policy was evaluated against this
919 # prompt and stood aside" is the answer to a question the log is
920 # kept to answer.
921 evaluations.append(
922 _evaluation(rule, ref, GovernanceEnum.Outcome.not_matched)
923 )
924 continue
926 applied = _apply_text_actions(rule, filtered, eval_ctx, ref)
927 filtered, rule_events, block = applied.text, applied.events, applied.block
928 if applied.redactor is not None:
929 redactor = applied.redactor.merged(redactor)
930 if applied.web is not None:
931 web = applied.web.merge(web)
932 if applied.limit is not None:
933 limit = _tighter(limit, _rule_limit(rule, ref, applied.limit, rule_events))
934 events.extend(rule_events)
935 evaluations.append(
936 _evaluation(
937 rule,
938 ref,
939 activity_service.outcome_of(rule_events, blocked=block is not None),
940 rule_events,
941 )
942 )
944 if block is not None:
945 logger.info(
946 "Rule %r (id=%s v%s, governing %s) blocked invocation: %s",
947 rule.name,
948 ref["rule_id"],
949 ref["rule_version"],
950 # What the rule covers, in words. A block is the event most
951 # likely to be challenged, and "which of my things did this
952 # apply to?" is the first question asked of one — a log line
953 # carrying only a name and a uuid cannot answer it.
954 scope_registry.describe(rule.scope_type, rule.scope_id),
955 block.message,
956 )
957 # Written before the exception leaves: a refusal is the event
958 # this log least tolerates losing, and the caller that catches
959 # this commits the blocked turn with it.
960 _record_activity(db, evaluations, context, owner_user_id, _PHASE_INPUT, ws)
961 raise RuleBlock(
962 rule_name=rule.name,
963 message=block.message,
964 rule_id=ref["rule_id"],
965 rule_version=ref["rule_version"],
966 scope_type=ref["scope_type"],
967 scope_id=ref["scope_id"],
968 evaluations=evaluations,
969 )
971 _record_activity(db, evaluations, context, owner_user_id, _PHASE_INPUT, ws)
972 return RulePass(filtered, events, evaluations, redactor, limit, web)
975class BudgetBlock(RuleBlock):
976 """A budget refusing work that is not a turn (:func:`evaluate_budgets`),
977 with when it starts again: ``resets_at``, an ISO timestamp, or None for
978 a trailing window, which frees up as earlier spend leaves it."""
980 def __init__(self, *args: Any, resets_at: str | None = None, **kwargs: Any) -> None:
981 super().__init__(*args, **kwargs)
982 self.resets_at = resets_at
985def evaluate_budgets(
986 db: Session,
987 context: dict[str, Any],
988 owner_user_id: str | None,
989) -> SpendLimit | None:
990 """The budgets alone, for work that is not a turn (cost-control plan A1.5).
992 A generation flow, a search of a knowledge base, indexing, a crawl and a
993 simulation reach a model too, and every budget counted what they spent
994 without ever refusing them (Known gap 20). This is their check: the same
995 cost caps and the same platform allowance a turn meets, judged by the
996 same action (``CostCapAction.apply``) with each cap's conditions and
997 ``execution_types`` as written — and nothing else, since a content rule is
998 a prompt's and a crawl has none. No reserve: "room to finish" is what a
999 turn usually costs, and this work is not a turn.
1001 Returns the tightest amount left — the call's ``X-Spend-Limit`` — or None
1002 when no budget governs the work. Raises :class:`BudgetBlock` when one is
1003 used up, recorded in the activity log for the person whose work it was.
1004 Work no person started (``owner_user_id`` None, a scheduled crawl) is
1005 refused without a row: the activity log is a person's, and the caller
1006 records the refusal on its own record. Passes are not recorded either —
1007 a search or an indexed document is not a governed turn, and a row per
1008 budget per page indexed would bury the turns the log is read for.
1009 """
1010 links = _chain_from_context(context)
1011 ws = _invocation_workspace(db, context, owner_user_id, links)
1012 record = owner_user_id is not None
1013 evaluations: list[dict] = []
1014 limit: SpendLimit | None = None
1016 allowance_pass = _check_allowance(
1017 db,
1018 "",
1019 context,
1020 owner_user_id,
1021 ws,
1022 None,
1023 evaluations,
1024 record=record,
1025 budget=True,
1026 )
1027 if allowance_pass is not None:
1028 limit = allowance_pass[1]
1030 cap = action_registry.CostCapAction()
1031 rules = [
1032 rule
1033 for rule in _get_applicable_rules(
1034 db, RuleEnum.Layer.access, owner_user_id, links, ws
1035 )
1036 if any((a or {}).get("type") == cap.type for a in rule.actions or [])
1037 ]
1038 if not rules:
1039 return limit
1040 versions = _current_rule_versions(db, rules)
1041 usage = UsageWindows(db, owner_user_id)
1042 for rule in rules:
1043 eval_ctx = {
1044 **context,
1045 "prompt": "",
1046 USAGE_CONTEXT_KEY: usage.for_rule(rule),
1047 OWNER_CONTEXT_KEY: owner_user_id,
1048 }
1049 if not _all_conditions_match(rule.conditions, eval_ctx):
1050 continue
1051 ref = _rule_ref(rule, versions)
1052 for action in rule.actions or []:
1053 if (action or {}).get("type") != cap.type:
1054 continue
1055 if (
1056 owner_user_id is None
1057 and str((action or {}).get("share") or "")
1058 == action_registry.QuotaShare.per_member
1059 ):
1060 # Each member's own allowance: work no person started is no
1061 # member's, so it is counted by the workspace's budgets alone.
1062 continue
1063 outcome = cap.apply(action, "", eval_ctx)
1064 events = [{**ref, **event} for event in outcome.events]
1065 if outcome.block is not None:
1066 figures = _cap_figures(events)
1067 message = budget_refusal(rule.name, action, figures)
1068 if events:
1069 events[-1] = {**events[-1], "message": message}
1070 else:
1071 events.append({**ref, "action": cap.type, "message": message})
1072 evaluations.append(
1073 _evaluation(rule, ref, GovernanceEnum.Outcome.blocked, events)
1074 )
1075 if record:
1076 _record_activity(
1077 db, evaluations, context, owner_user_id, _PHASE_INPUT, ws
1078 )
1079 raise BudgetBlock(
1080 rule_name=rule.name,
1081 message=message,
1082 rule_id=ref["rule_id"],
1083 rule_version=ref["rule_version"],
1084 scope_type=ref["scope_type"],
1085 scope_id=ref["scope_id"],
1086 evaluations=evaluations,
1087 resets_at=figures.get("resets_at"),
1088 )
1089 if outcome.spend_limit is not None:
1090 limit = _tighter(
1091 limit, _rule_limit(rule, ref, outcome.spend_limit, events)
1092 )
1093 return limit
1096def budget_refusal(name: str, config: dict[str, Any], figures: dict[str, Any]) -> str:
1097 """What a used-up budget tells work it refuses: the rule's own message
1098 when it wrote one, else the budget's name and when it starts again."""
1099 custom = (config or {}).get("message")
1100 if custom and custom != action_registry.DEFAULT_CAP_MESSAGE:
1101 return str(custom)
1102 return f"{name} is used up. {action_registry.resets_phrase(figures)}"
1105def _turn_reserve(db: Session, context: dict[str, Any], ws: Any) -> TurnReserveLookup:
1106 """What a turn like the one being governed usually costs: the same
1107 resource's recent turns of the same kind, in the same workspace."""
1108 from app.db.postgres.models import GovernanceUsage
1110 return TurnReserveLookup(
1111 db,
1112 scope_type=context.get("scope_type"),
1113 scope_id=context.get("scope_id"),
1114 execution_type=context.get("execution_type"),
1115 where=ws.stamped(GovernanceUsage, projects=False) if ws is not None else None,
1116 )
1119def _cap_figures(events: list[dict[str, Any]]) -> dict[str, Any]:
1120 """The cost cap event among a rule's events: its cap and reset."""
1121 for event in events:
1122 if event.get("action") == action_registry.CostCapAction.type:
1123 return event
1124 return {}
1127def _rule_limit(
1128 rule: Rule, ref: dict[str, Any], usd: Decimal, events: list[dict[str, Any]]
1129) -> SpendLimit:
1130 figures = _cap_figures(events)
1131 cap = figures.get("cap_usd")
1132 return SpendLimit(
1133 usd=usd,
1134 rule_id=ref.get("rule_id"),
1135 rule_name=rule.name,
1136 rule_version=ref.get("rule_version"),
1137 cap_usd=Decimal(str(cap)) if cap is not None else None,
1138 resets_at=figures.get("resets_at"),
1139 scope_type=ref.get("scope_type"),
1140 scope_id=ref.get("scope_id"),
1141 )
1144class _PlatformEntry:
1145 """What the activity log needs of a rule, for an Access entry that is not
1146 one rule's evaluation: the platform allowance, or a budget stopping a
1147 turn part-way through."""
1149 layer = RuleEnum.Layer.access
1152def _check_allowance(
1153 db: Session,
1154 text: str,
1155 context: dict[str, Any],
1156 owner_user_id: str | None,
1157 ws: Any,
1158 reserve: TurnReserveLookup | None,
1159 evaluations: list[dict[str, Any]],
1160 *,
1161 record: bool = True,
1162 budget: bool = False,
1163) -> tuple[list[dict[str, Any]], SpendLimit | None] | None:
1164 """Judge the workspace's platform allowance, as a cost cap is judged.
1166 Appends its evaluation to ``evaluations``; returns its events and the
1167 limit it sets, or None when the deployment sets no allowance here.
1168 Raises ``RuleBlock`` — recorded first, like a rule's — when it refuses;
1169 ``BudgetBlock`` for work that is not a turn (``budget``), recorded only
1170 when ``record``.
1171 """
1172 from app.services.budgets import allowance as allowance_service
1174 allowance = allowance_service.for_workspace(ws)
1175 if allowance is None:
1176 return None
1177 window = UsageWindow(db, owner_user_id, population=allowance.population)
1178 cap = action_registry.CostCapAction()
1179 config = allowance.config()
1180 ref = allowance.ref()
1181 outcome = cap.apply(
1182 config,
1183 text,
1184 {**context, USAGE_CONTEXT_KEY: window, RESERVE_CONTEXT_KEY: reserve},
1185 )
1186 events = [{**ref, **event} for event in outcome.events]
1187 if outcome.block is not None:
1188 figures = _cap_figures(events)
1189 message = allowance_service.refusal(figures)
1190 if events:
1191 events[-1] = {**events[-1], "message": message}
1192 evaluations.append(
1193 _evaluation(_PlatformEntry(), ref, GovernanceEnum.Outcome.blocked, events)
1194 )
1195 if record:
1196 _record_activity(db, evaluations, context, owner_user_id, _PHASE_INPUT, ws)
1197 if budget:
1198 raise BudgetBlock(
1199 rule_name=allowance_service.NAME,
1200 message=message,
1201 scope_type=ref["scope_type"],
1202 scope_id=ref["scope_id"],
1203 evaluations=evaluations,
1204 resets_at=figures.get("resets_at"),
1205 )
1206 raise RuleBlock(
1207 rule_name=allowance_service.NAME,
1208 message=message,
1209 scope_type=ref["scope_type"],
1210 scope_id=ref["scope_id"],
1211 evaluations=evaluations,
1212 )
1213 evaluations.append(
1214 _evaluation(_PlatformEntry(), ref, activity_service.outcome_of(events), events)
1215 )
1216 limit = None
1217 if outcome.spend_limit is not None:
1218 figures = _cap_figures(events)
1219 limit = SpendLimit(
1220 usd=outcome.spend_limit,
1221 rule_id=None,
1222 rule_name=allowance_service.NAME,
1223 rule_version=None,
1224 cap_usd=allowance.amount,
1225 resets_at=figures.get("resets_at"),
1226 kind="platform",
1227 scope_type=ref["scope_type"],
1228 scope_id=ref["scope_id"],
1229 )
1230 return events, limit
1233def record_turn_stop(
1234 db: Session,
1235 limit: SpendLimit,
1236 context: dict[str, Any],
1237 owner_user_id: str,
1238 *,
1239 spent_usd: Decimal | None = None,
1240) -> None:
1241 """Record that ``limit`` stopped a turn part-way through: one output-phase
1242 activity row for the cap (or allowance) that set it, outcome ``blocked``,
1243 with the limit and what the turn spent. Beside the input row that let the
1244 turn start, it is the whole story of the budget and the turn. Not
1245 committed; never raises."""
1246 try:
1247 links = _chain_from_context(context)
1248 ws = _invocation_workspace(db, context, owner_user_id, links)
1249 detail_event = {
1250 "action": action_registry.CostCapAction.type,
1251 "stopped_mid_turn": True,
1252 "limit_usd": str(limit.usd),
1253 "cap_usd": str(limit.cap_usd) if limit.cap_usd is not None else None,
1254 "spent_usd": str(spent_usd) if spent_usd is not None else None,
1255 "resets_at": limit.resets_at,
1256 "message": limit.stop_message(),
1257 }
1258 evaluation = _evaluation(
1259 _PlatformEntry(),
1260 limit.ref(),
1261 GovernanceEnum.Outcome.blocked,
1262 [detail_event],
1263 )
1264 _record_activity(db, [evaluation], context, owner_user_id, _PHASE_OUTPUT, ws)
1265 except Exception:
1266 logger.exception("Could not record a turn stopped at its spend limit")
1269# ─── After the model: Output rules ────────────────────────────────────────────
1272def evaluate_output(
1273 db: Session,
1274 response: str,
1275 context: dict[str, Any],
1276 owner_user_id: str,
1277) -> RulePass:
1278 """
1279 Evaluate the Output rules against an LLM response after it returns from
1280 svc-ai.
1282 ``context`` may include scope_type and scope_id (like ``evaluate_input``)
1283 so resource-scoped Output rules are honoured, not just global ones.
1285 A ``withhold`` action is applied last, whatever its rule's priority:
1286 every Output rule runs on the answer as written — a flag still sees a
1287 leaked key, a redaction still redacts — and then, if one withheld it,
1288 the result is its rule's message and the answer goes on the pass as
1289 ``withheld`` (the first such rule's, in priority order).
1291 Returns:
1292 (filtered_response, events) — response may be modified by redact_pii,
1293 or replaced by a withhold rule's message — as a :class:`RulePass`
1294 also carrying every applicable rule's outcome.
1295 """
1296 links = _chain_from_context(context)
1297 ws = _invocation_workspace(db, context, owner_user_id, links)
1299 rules = _get_applicable_rules(
1300 db, layer_registry.after_model(), owner_user_id, links, ws
1301 )
1303 versions = _current_rule_versions(db, rules)
1305 events: list[dict] = []
1306 evaluations: list[dict] = []
1307 filtered = response
1308 redactor: pii.Redactor | None = None
1309 withhold: tuple[WithholdDecision, dict[str, Any]] | None = None
1311 for rule in rules:
1312 eval_ctx = {
1313 **context,
1314 "response": filtered,
1315 OWNER_CONTEXT_KEY: owner_user_id,
1316 }
1317 ref = _rule_ref(rule, versions)
1318 if not _all_conditions_match(rule.conditions, eval_ctx):
1319 evaluations.append(
1320 _evaluation(rule, ref, GovernanceEnum.Outcome.not_matched)
1321 )
1322 continue
1324 # Output actions cannot block — none registers a block decision — but
1325 # the same helper is used so both phases record their events
1326 # identically and a future blocking Output action is not a special
1327 # case here.
1328 applied = _apply_text_actions(rule, filtered, eval_ctx, ref)
1329 filtered, rule_events = applied.text, applied.events
1330 if applied.redactor is not None:
1331 redactor = applied.redactor.merged(redactor)
1332 if applied.withhold is not None and withhold is None:
1333 withhold = (applied.withhold, ref)
1334 events.extend(rule_events)
1335 evaluations.append(
1336 _evaluation(
1337 rule, ref, activity_service.outcome_of(rule_events), rule_events
1338 )
1339 )
1340 for event in rule_events:
1341 if event.get("action") == "flag_for_review":
1342 # Where it happened, so the flag lands in that workspace's
1343 # review queue (``review.record_flags``) whoever's rule it was.
1344 event.setdefault(WORKSPACE_CONTEXT_KEY, ws.key)
1345 logger.warning(
1346 "Audit rule %r: flagging invocation for review by %r",
1347 rule.name,
1348 event.get("reviewer"),
1349 )
1351 withheld: Withheld | None = None
1352 if withhold is not None:
1353 decision, ref = withhold
1354 withheld = Withheld(
1355 message=decision.message,
1356 original=filtered,
1357 review=decision.review,
1358 ref=ref,
1359 workspace=ws.key,
1360 )
1361 logger.info(
1362 "Output rule %r (id=%s v%s) withheld an answer%s",
1363 ref["rule"],
1364 ref["rule_id"],
1365 ref["rule_version"],
1366 " and sent it to review" if decision.review else "",
1367 )
1368 filtered = decision.message
1370 _record_activity(db, evaluations, context, owner_user_id, _PHASE_OUTPUT, ws)
1371 return RulePass(filtered, events, evaluations, redactor, withheld=withheld)
1374def may_withhold(db: Session, context: dict[str, Any], owner_user_id: str) -> bool:
1375 """Whether an Output rule that can withhold the answer governs this
1376 invocation — whatever its conditions, which only the finished answer can
1377 answer. While one does, nothing of the answer is shown or kept before
1378 the Output rules have run on it (``app/services/withholding.py``)."""
1379 links = _chain_from_context(context)
1380 ws = _invocation_workspace(db, context, owner_user_id, links)
1381 rules = _get_applicable_rules(
1382 db, layer_registry.after_model(), owner_user_id, links, ws
1383 )
1384 return any(_withholds(rule) for rule in rules)
1387def _withholds(rule: Rule) -> bool:
1388 """Whether ``rule`` carries the ``withhold`` action."""
1389 return any(
1390 isinstance(action, dict) and action.get("type") == WITHHOLD_ACTION
1391 for action in rule.actions or []
1392 )
1395#: The Output action that withholds an answer.
1396WITHHOLD_ACTION = "withhold"
1399# ─── Trace serialisation ─────────────────────────────────────────────────────
1400#
1401# A turn's governance renders as two system nodes in its execution trace: one
1402# for the Access and Input rules run against the prompt, one for the Output
1403# rules run against the response. Each node's result carries two lists:
1404#
1405# ``evaluations`` every applicable rule and its outcome — blocked, applied,
1406# no_change or not_matched, the same four answers the
1407# governance activity log records. This is what the trace
1408# reads from: a rule that stood aside is an answer too.
1409# ``events`` the raw action events, kept for readers that tally them
1410# (the Activity page's rule-hit charts) and for traces
1411# persisted before ``evaluations`` existed.
1412#
1413# svc-ai re-enforces the forwardable rules inside its run and reports what it
1414# did. Those are merged into the same node rather than given one of their own:
1415# it is the same rule on the same turn, and two nodes read as two rules — or,
1416# where svc-ai redacted the response before svc-core looked, as one rule that
1417# acted and one that found nothing, with no way to tell they were the same.
1419#: node_id used for the rules run before the model (Access, Input) in traces
1420POLICY_TRACE_NODE = "__policy__"
1421#: node_id used for the rules run after it (Output) in traces
1422AUDIT_TRACE_NODE = "__audit__"
1424#: Each phase's trace node, and the layer of a rule svc-ai reports from it
1425#: (svc-ai enforces Input and Output rules only). The node ids predate layers
1426#: and stay: stored traces carry them.
1427_PHASES: dict[str, tuple[str, RuleEnum.Layer]] = {
1428 "input": (POLICY_TRACE_NODE, RuleEnum.Layer.input),
1429 "output": (AUDIT_TRACE_NODE, RuleEnum.Layer.output),
1430}
1432#: How much an outcome says, weakest first. Merging two reports of one rule
1433#: keeps the stronger: a redaction svc-ai made is not undone by svc-core
1434#: finding nothing left to redact afterwards.
1435_OUTCOME_STRENGTH: dict[str, int] = {
1436 GovernanceEnum.Outcome.not_matched.value: 0,
1437 GovernanceEnum.Outcome.no_change.value: 1,
1438 GovernanceEnum.Outcome.applied.value: 2,
1439 GovernanceEnum.Outcome.blocked.value: 3,
1440}
1442#: Where a traced evaluation was enforced. ``both`` is a rule svc-core
1443#: evaluated that svc-ai also enforced inside the run.
1444_ENFORCED_CORE = GovernanceEnum.EnforcedIn.core.value
1445_ENFORCED_AI = GovernanceEnum.EnforcedIn.ai.value
1446_ENFORCED_BOTH = "both"
1449def _phase_of(phase: str) -> str:
1450 """``input`` or ``output``; anything else is output, the later phase."""
1451 return "input" if phase == "input" else "output"
1454def _rule_key(item: dict[str, Any]) -> str:
1455 """Identity for merging: the rule id, or its name when there is none."""
1456 return str(item.get("rule_id") or item.get("rule") or "")
1459def _value(value: Any) -> Any:
1460 """An enum's value, so a trace frame survives ``json.dumps`` unchanged."""
1461 return getattr(value, "value", value)
1464def _trace_evaluation(
1465 evaluation: dict[str, Any], enforced_in: str = _ENFORCED_CORE
1466) -> dict[str, Any]:
1467 """One evaluation in the JSON shape a trace frame carries."""
1468 return {
1469 "rule": evaluation.get("rule"),
1470 "rule_id": evaluation.get("rule_id"),
1471 "rule_version": evaluation.get("rule_version"),
1472 "layer": _value(evaluation.get("layer")),
1473 "scope_type": _value(evaluation.get("scope_type")),
1474 "scope_id": evaluation.get("scope_id"),
1475 "outcome": _value(evaluation.get("outcome")),
1476 "actions": list(evaluation.get("actions") or []),
1477 "detail": dict(evaluation.get("detail") or {}),
1478 "enforced_in": evaluation.get("enforced_in") or enforced_in,
1479 }
1482def _evaluations_from_events(
1483 events: list[dict], phase: str, enforced_in: str
1484) -> list[dict[str, Any]]:
1485 """Evaluations reconstructed from action events, one per rule.
1487 Used for svc-ai's trail, and for a caller with only events in hand (a
1488 block svc-ai reported). Events exist only for rules that matched, so every
1489 entry is ``applied``, ``no_change`` or ``blocked`` — never
1490 ``not_matched``. For svc-ai that is fine: svc-core evaluated the full set,
1491 and these are merged into it.
1492 """
1493 _, layer = _PHASES[_phase_of(phase)]
1494 grouped: dict[str, list[dict]] = {}
1495 for event in events:
1496 grouped.setdefault(_rule_key(event), []).append(event)
1497 evaluations = []
1498 for rule_events in grouped.values():
1499 first = rule_events[0]
1500 outcome = activity_service.outcome_of(
1501 rule_events,
1502 blocked=any(event.get("action") == "block" for event in rule_events),
1503 )
1504 evaluations.append(
1505 _trace_evaluation(
1506 {
1507 **first,
1508 "layer": layer,
1509 "outcome": outcome,
1510 "actions": [e["action"] for e in rule_events if e.get("action")],
1511 "detail": activity_service.detail_of(rule_events),
1512 },
1513 enforced_in,
1514 )
1515 )
1516 return evaluations
1519def _merge_evaluations(
1520 local: list[dict[str, Any]], remote: list[dict[str, Any]]
1521) -> list[dict[str, Any]]:
1522 """svc-core's evaluations with svc-ai's folded in, one entry per rule."""
1523 merged = [_trace_evaluation(evaluation) for evaluation in local]
1524 index = {_rule_key(item): i for i, item in enumerate(merged)}
1525 for item in remote:
1526 at = index.get(_rule_key(item))
1527 if at is None:
1528 index[_rule_key(item)] = len(merged)
1529 merged.append(item)
1530 continue
1531 existing = merged[at]
1532 stronger = _OUTCOME_STRENGTH.get(item["outcome"], 0) > _OUTCOME_STRENGTH.get(
1533 existing["outcome"], 0
1534 )
1535 actions = list(existing["actions"])
1536 actions += [action for action in item["actions"] if action not in actions]
1537 merged[at] = {
1538 **existing,
1539 "outcome": item["outcome"] if stronger else existing["outcome"],
1540 "actions": actions,
1541 "detail": (
1542 {**existing["detail"], **item["detail"]}
1543 if stronger
1544 else {**item["detail"], **existing["detail"]}
1545 ),
1546 "enforced_in": _ENFORCED_BOTH,
1547 }
1548 return merged
1551def _merge_events(local: list[dict], remote: list[dict]) -> list[dict]:
1552 """Action events, one per rule and action, the one that did something kept.
1554 Without this a ``flag_for_review`` rule enforced in both services counts
1555 twice per turn in anything that tallies events.
1556 """
1557 merged = list(local)
1558 index = {(_rule_key(e), e.get("action")): i for i, e in enumerate(merged)}
1559 for event in remote:
1560 key = (_rule_key(event), event.get("action"))
1561 at = index.get(key)
1562 if at is None:
1563 index[key] = len(merged)
1564 merged.append(event)
1565 elif not merged[at].get("changed", True) and event.get("changed", True):
1566 merged[at] = event
1567 return merged
1570def rule_trace_result(
1571 events: list[dict] | None,
1572 phase: str,
1573 evaluations: list[dict[str, Any]] | None = None,
1574 remote_events: list[dict] | None = None,
1575) -> dict[str, Any] | None:
1576 """The result payload of one phase's rule node, or None when nothing ran."""
1577 phase = _phase_of(phase)
1578 remote = [e for e in remote_events or [] if _phase_of(e.get("phase", "")) == phase]
1579 local = evaluations or _evaluations_from_events(
1580 list(events or []), phase, _ENFORCED_CORE
1581 )
1582 merged_evaluations = _merge_evaluations(
1583 local, _evaluations_from_events(remote, phase, _ENFORCED_AI)
1584 )
1585 merged_events = _merge_events(list(events or []), remote)
1586 if not merged_evaluations and not merged_events:
1587 return None
1588 return {
1589 "phase": phase,
1590 "evaluations": merged_evaluations,
1591 "events": [{**event, "phase": phase} for event in merged_events],
1592 }
1595def build_rule_trace(
1596 events: list[dict] | None,
1597 phase: str,
1598 evaluations: list[dict[str, Any]] | None = None,
1599 remote_events: list[dict] | None = None,
1600) -> list[dict]:
1601 """
1602 Serialise one phase's rule enforcement into trace frames, so it renders
1603 as a system node in the chat execution trace and the Activity page.
1605 ``phase`` is "input" (Access and Input rules) or "output" (Output rules).
1606 ``evaluations`` is every applicable rule's outcome (``RulePass
1607 .evaluations``); ``remote_events`` is svc-ai's enforcement trail, of which
1608 only this phase's events are used.
1610 Returns an empty list when no rule applied, so callers can concatenate
1611 unconditionally.
1612 """
1613 result = rule_trace_result(events, phase, evaluations, remote_events)
1614 if result is None:
1615 return []
1616 node_id = _PHASES[result["phase"]][0]
1617 return [
1618 {"type": "node_start", "node_id": node_id, "is_system_node": True},
1619 {"type": "system_node_result", "node_id": node_id, "result": result},
1620 {"type": "node_end", "node_id": node_id, "is_system_node": True},
1621 ]
1624def build_rule_trace_update(
1625 events: list[dict] | None,
1626 phase: str,
1627 evaluations: list[dict[str, Any]] | None = None,
1628 remote_events: list[dict] | None = None,
1629) -> list[dict]:
1630 """A replacement result for a rule node already sent, as one frame.
1632 A stream sends the policy node before svc-ai runs — that is when the
1633 rules ran — but svc-ai's own enforcement of the same rules is known only
1634 when it finishes. A second ``system_node_result`` for the same node
1635 replaces the first in every trace reader, so the node is corrected in
1636 place instead of a second policy node appearing after the answer.
1638 Only for a node that was sent: when none was, use ``build_rule_trace``.
1639 """
1640 result = rule_trace_result(events, phase, evaluations, remote_events)
1641 if result is None:
1642 return []
1643 return [
1644 {
1645 "type": "system_node_result",
1646 "node_id": _PHASES[result["phase"]][0],
1647 "result": result,
1648 }
1649 ]
1652def build_turn_rule_trace(
1653 input_rules: tuple | None,
1654 output_rules: tuple | None,
1655 remote_events: list[dict] | None = None,
1656) -> list[dict]:
1657 """Both phases of one turn: the policy node, then the audit node.
1659 ``input_rules`` / ``output_rules`` are what ``evaluate_input`` and
1660 ``evaluate_output`` returned. A bare ``(text, events)`` pair is accepted
1661 too and simply has no evaluations to show.
1662 """
1664 def _parts(rules: tuple | None) -> tuple[list[dict], list[dict]]:
1665 if not rules:
1666 return [], []
1667 return list(rules[1] or []), list(getattr(rules, "evaluations", []) or [])
1669 input_events, input_evaluations = _parts(input_rules)
1670 output_events, output_evaluations = _parts(output_rules)
1671 return build_rule_trace(
1672 input_events, "input", input_evaluations, remote_events
1673 ) + build_rule_trace(output_events, "output", output_evaluations, remote_events)
1676def build_remote_rule_trace(events: list[dict] | None) -> list[dict]:
1677 """Trace frames for rules enforced inside svc-ai, when svc-core ran none.
1679 svc-ai returns its enforcement trail on ``ExecuteResponse.rule_events``
1680 (batch) or the terminal ``done`` frame (streaming). Each event carries a
1681 ``phase`` of input/output; events with an unrecognised phase are treated
1682 as output, the later of the two, so an unknown event is never rendered as
1683 having preceded the call.
1685 Where svc-core evaluated rules on the same turn, pass these as
1686 ``remote_events`` to ``build_rule_trace`` / ``build_turn_rule_trace``
1687 instead, so each rule is one entry in one node.
1688 """
1689 if not events:
1690 return []
1691 return build_turn_rule_trace(None, None, events)
1694def build_block_trace(
1695 rule_name: str,
1696 message: str,
1697 *,
1698 rule_id: str | None = None,
1699 rule_version: int | None = None,
1700 scope_type: str | None = None,
1701 scope_id: str | None = None,
1702 evaluations: list[dict[str, Any]] | None = None,
1703) -> list[dict]:
1704 """
1705 Serialise a caught ``RuleBlock``/``RuleBlockedError`` into a trace frame.
1707 ``evaluate_input`` raises before it can append a "block" event to the
1708 ``events`` list it would otherwise return, so callers that catch the
1709 block exception synthesize the event here instead — this is what lets a
1710 blocked turn's persisted trace surface as "Blocked" on the Activity page.
1711 ``evaluations`` are the rules evaluated up to and including the refusal.
1713 Prefer ``build_block_trace_from_exc`` where a ``RuleBlock`` is in hand:
1714 it carries the identity fields across without the caller restating them.
1715 """
1716 return build_rule_trace(
1717 [
1718 {
1719 "rule": rule_name,
1720 "rule_id": rule_id,
1721 "rule_version": rule_version,
1722 "scope_type": scope_type,
1723 "scope_id": scope_id,
1724 "action": "block",
1725 "message": message,
1726 }
1727 ],
1728 "input",
1729 evaluations,
1730 )
1733def build_block_trace_from_exc(exc: "BlockLike") -> list[dict]:
1734 """Trace frames for a caught block, preserving rule identity.
1736 Accepts a block enforced here (``RuleBlock``) or one reported by svc-ai
1737 (``ai_client.RuleBlockedError``) — both expose the same identity — so a
1738 blocked turn is recorded identically wherever the decision was made.
1739 Only a ``RuleBlock`` knows which other rules ran before it.
1741 Blocks are the events most likely to be challenged later, so they are the
1742 ones that least tolerate a trace recording only a mutable name.
1743 """
1744 return build_block_trace(
1745 exc.rule_name,
1746 exc.message,
1747 rule_id=exc.rule_id,
1748 rule_version=exc.rule_version,
1749 scope_type=exc.scope_type,
1750 scope_id=exc.scope_id,
1751 evaluations=getattr(exc, "evaluations", None),
1752 )