chain-rdeveloper portal
build

Governance Rules

How a rule is written, where it is evaluated, and how to widen what rules can express.

Rules are one of Governance's two tabs, beside Evaluation, and Activity and Reviews open from the top of it. Governance is the map of how they fit together and what evidence each leaves.

A rule is a stored Rule row with a layer, a scope, a list of conditions and a list of actions. Conditions are ANDed; if they all match, every action runs. Rules are versioned like any other resource (see the history rules in CLAUDE.md), so a block can be resolved back to the exact revision that produced it.

Layers: where in a request a rule acts

A rule acts in one layer of a request, and the layers run in the order a request meets them. Each is one class in app/services/rules/layers.py (label, the question it answers, the phase its conditions see), served in the catalogue, so the Rules page's sections and the builder's picker are the registry.

LayerAsksActionsRuns
inputWhat may the model read?block, redact_piiBefore the model, after Access — svc-core and svc-ai
toolsWhere may it look things up?trusted_sources, blocked_sourcesBefore the model, after Input — resolved in svc-core, held by svc-ai's web tools
outputWhat may people receive?redact_pii, flag_for_review, withholdAfter the model answers — svc-core and svc-ai

Order follows the flow. Every Access rule runs before any Input rule, and every Input rule before any Tools rule, whatever their priorities; priority, then how narrowly a rule is aimed, orders the rules within a layer (rule_engine._get_applicable_rules, one query ordered by layer, then priority, then specificity). So an Access rule conditioned on the prompt sees it as written, before any Input rule redacts it.

Layers replaced the rule types in migration 105: policy rules became Access rules when every action they carried was a quota or the evaluation gate, and Input rules otherwise; a policy rule carrying both was split, keeping its id on the Access half (budget alerts, a turn's spend limit and closed statements name a cap by its rule's id) and moving its other actions to a new "‹name› · Input" rule with the same owner, scope, conditions, priority, flags and project declarations; audit rules became Output rules. Input's redaction was filter_pii; both layers' are redact_pii now, one key registered in two layers. Every surviving rule got a version marked as a CHAIN-R release. Activity rows took the layer their actions said; breakdown tiles sliced by rule_type were rewritten to layer.

Where rules are evaluated

TypeEvaluatedWhereActs on
inputBefore the prompt reaches the modelsvc-core and svc-aiThe prompt
toolsBefore the prompt reaches the modelsvc-core, sent as a web policyThe web sources the run's tools may use
outputAfter the response returnssvc-core and svc-aiThe response

svc-core resolves the user's applicable rules and forwards the Input and Output rules to svc-ai on the execute request (serialize_rules, each with its layer), so svc-ai can enforce them inside its own engines — LangGraph runs, workers, streaming — without a cross-service DB round-trip. An Access rule's actions read svc-core's ledger and evaluations, so it is never forwarded; a Tools rule reaches svc-ai as the web policy it sets, not as a rule (see below). svc-ai reads a rule sent by an svc-core from before migration 105 (rule_type, filter_pii) as the layer it became, for the release the two may differ by.

Both services must understand the same grammar. svc-core evaluates a rule on the direct path and svc-ai evaluates it once execution moves inside a graph. A condition one service understands and the other does not is a rule that fires on some invocations and silently not on others.

The vocabulary is a registry

Condition fields, operators and actions are each one class, registered with a decorator — the same pattern as widget types, scorers and tools.

svc-core  app/services/rules/       ← authoritative
            operators.py    how two values are compared
            fields.py       what a condition can ask about, and how to resolve it
            actions.py      what a matched rule does, and its parameters
            scopes.py       what a rule governs, and how it matches an invocation
            layers.py       where in a request a rule acts, in flow order
            conditions.py   the single matcher every layer goes through
            catalogue.py    the registries, served over the API
            pii.py          the PII detectors — one class per kind of personal data
            redaction.py    the redaction a rule asks for, keyed for this deployment

svc-ai    app/inference/rule_vocabulary.py   ← enforcement-side mirror
          app/inference/pii.py               ← svc-core's pii.py, byte for byte

app/services/rule_engine.py (svc-core) and app/inference/rules.py (svc-ai) own when rules run and how effects are recorded. They own none of the grammar.

GET /app/rules/catalogue serves the registries to the fe-core rule builder, so the builder can only ever offer something the engine can evaluate. Before this existed, the field/operator/action lists were hard-coded in NewRule.tsx and drifted from the backend — and the failure mode was the bad one: the UI offered a condition the engine skipped with a warning, so a user believed a rule was governing them when it was not.

GET /app/rules/targets serves the resources the current user may pin a rule to, grouped by scope. The catalogue describes the engine and is the same for everybody; targets describe your data. One call rather than the builder asking six routers in turn — and the same payload is what lets a rule list say "applies to Support Agent" instead of showing a UUID.

Adding a condition field

One class in svc-core/app/services/rules/fields.py:

@register_field
class MyField(Field):
    key = "my_field"
    label = "My field"
    description = "What it is — shown in the builder."
    group = "invocation"          # groups the builder's field picker
    value_type = ValueType.number # decides which operators may be paired
    phases = frozenset({Phase.output})

    def resolve(self, context: dict[str, Any]) -> Any:
        return context.get("my_field")

Then mirror it in svc-ai/app/inference/rule_vocabulary.py and add the key to both manifests (see Keeping the two in sync). Nothing else changes: the builder picks it up from the catalogue, and the generative-setup validator (agents/setup.py) starts accepting it in AI-proposed rules at the same moment the engine starts enforcing it.

resolve is why widening the vocabulary needed no change to any invocation path — a field derives its value from what the context already carries, and prefers an exact figure if the caller supplies one. prompt_tokens counts the prompt; pii_detected runs the shared PII patterns over whichever text the phase is about.

Adding an action

One class in actions.py, subclassing TextAction, with the layer whose rules may carry it. One key may be registered in two layers, one class each (redact_pii, in Input and Output). Actions never raise to signal a block — they return a BlockDecision, and the caller turns it into an exception, an HTTP 403 or a stream refusal frame. That is what lets one class serve svc-core and svc-ai without either knowing the other's control flow.

Parameters are declared as ActionParams and rendered generically by the builder, so a new action's inputs appear with no frontend work. A parameter that names a resource by id declares it (resource="dataset"): the builder offers a picker for that kind (RESOURCE_PARAM_INPUTS in NewRule.tsx), and the id is checked when the rule is saved (services/rules/references.py, one entry per kind in RESOURCE_MODELS).

Scope: what a rule governs

A rule carries a scope_type and an optional scope_id. Three shapes, and they mean different things:

Covers
<kind>, no scope_idEvery resource of that kind — every agent, every project.
<kind> + scope_idExactly that resource.

Scopes are one class each, in app/services/rules/scopes.py, registered the same way fields and actions are. A scope owns where it sits in the containment hierarchy, the resource it can be pinned to, how to validate a pin, and how to narrow the usage ledger to itself. Adding a scope is one class and a migration for the enum label; the builder's picker, the list page's filter, the create/update validation and the quota window all follow from it.

global  ⊃  organisation  ⊃  project  ⊃  model  ⊃  agent  ⊃  skill  ⊃  worker

organisation and project are ownership scopes: no invocation names one directly, but every governed resource belongs to one, so a rule written there reaches everything inside it. model sits between project and agent because a model-scoped rule reaches every agent using that model — broader than one agent's own rule, but it names a concrete participant in the call.

Whose rules apply

A rule has an owner — a person, an organisation or a project, each a workspace (app/services/workspace.py) — as well as a scope. An invocation happens in one workspace, and is governed by:

  • that workspace's own rules, and

  • for a project, its parent's rules that it inherits: those the parent marked Required for all projects (rules.required_for_projects), those pinned to this project, and those the project declared it inherits (a single rule, or all of them) — see docs/system/security/authorization.md#workspaces.

The workspace is the one the request names (fe-core sends it with every chat, skill run and request — rule_engine.WORKSPACE_CONTEXT_KEY), or, for a caller that names none, the one its chain reaches: the project, else the organisation, else the invoker's personal workspace (workspace.from_chain). So an organisation's agent is governed by the organisation's rules, and a person's own rules no longer follow them into an organisation's agent. Inside a project, the project and its organisation join the chain (Workspace.refs), so a required rule scoped to the organisation matches there.

Before workspaces (migration 85), the invoker's personal rules applied to everything they invoked, and an organisation's rules never reached its projects' agents: the chain carried only each resource's direct owner. Before migration 81, rules were selected by the invoker alone, so a rule an organisation owned governed nobody.

Only governance editors write an organisation's rules, or mark one required. Every member can see them on the Rules tab, but creating, changing, deactivating or deleting one, or moving a rule into the organisation, needs editor access to the Governance area (admins are editors everywhere). A writer is not enough, even for a rule they wrote: otherwise a member could switch off the organisation's PII rule. A project's rules work the same way with the project's access. A project can add stricter rules of its own, never leave out a required one. See docs/system/security/authorization.md#access-per-area.

What a rule's effects reach follows the workspace that owns it:

Personal ruleOrganisation's ruleProject's rule
Quota counts (rate_limit, cost_cap)the person's workspace and personal projects, whoever invokes (workspace_user_id)one budget: the organisation and all its projectsthe project
Flags go tothe queue of the workspace it fired in — a project's for its reviewers (an organisation's admins are its admins by position)same; one fired in a project also names the organisation (rule_organisation_id), whose governance editors see itthe project's queue
ActivityGET /rules/activity?workspace= lists one workspace's: everyone's for its reviewers, your own otherwise; an organisation's also shows what its rules did in its projects

An invocation declares a chain, not a scope

This is the part that makes governance a layer rather than a per-page setting. An agent turn is not one governed thing: it is an agent, running a model, in a project, belonging to an organisation. A rule written against any one of those is a rule about that turn.

Call sites build the chain with scopes.invocation_chain(...), passing the ORM rows they already hold — each contributes its own reference and the project/organisation that owns it. _get_applicable_rules then selects every rule targeting any link in the chain, in one query.

Before this, matching was one (scope_type, scope_id) pair at a time, and the consequences were real:

  • a model-scoped policy silently stopped applying the moment its model was reached through an agent rather than prompted directly;

  • a skill- or worker-scoped rule never applied to an agent run that used that skill;

  • routing rules were only ever queried unscoped, so a routing rule scoped to anything never fired at all;

  • and there was nowhere for "everything this project spends" to live.

Ordering is by priority, then by how narrowly a rule is aimed — computed in SQL by scopes.specificity_expression() so it holds across the whole set. Priority is the knob the user turns, so it wins; below it, agent:X is considered before agent:*, then project:*, then the organisation's, then global. That is what makes "block everything, except this agent" express what a person means by it rather than depending on insertion order.

A pin that resolves to nothing is refused

POST/PATCH /app/rules validate scope_id against the scope's own resource, with the same ownership the resource's own routes enforce. A rule pinned to an id that does not resolve is not a narrow rule — it is a rule that looks active on the list page and never fires, which is the worst thing a governance surface can produce. Model pins are the one fail-open case: svc-ai owns the model catalogue, and refusing to save a rule because a downstream service is unreachable would make governance unavailable whenever svc-ai is.

Ids inside an action are held to the same standard. The evidence gate's dataset_id must name a dataset the author may read (their own, or a gold dataset), or the save is a 404. A generated rule naming one that does not resolve is dropped whole, not cleared: clearing it would change which evidence the gate demands.

Current vocabulary

Operators. eq neq contains not_contains starts_with ends_with matches not_matches gt gte lt lte in not_in has_any has_all has_none

Text comparisons are case-insensitive. Numeric operators coerce both sides, so a value typed into the builder compares as a number rather than lexically. Regex operators cap the pattern at 512 characters and the scanned text at 100,000 — re has no match timeout, and rules can be model-authored, so bounding both is the ReDoS defence.

Fields, by group:

GroupFields
contentprompt, response
classifierpii_detected, pii_types
invocationexecution_type, user_id, agent_id, agent_name, tags
modelmodel_name, provider
costprompt_tokens, response_tokens, total_tokens, estimated_cost_usd, latency_ms
qualityquality_check, quality_score

response, the cost fields and the quality fields are output-phase only — an Access or Input rule runs before the model is called, so conditioning one on the response or the latency would be writing a condition that can never match. The catalogue enforces this by only offering a field for layers whose phase it belongs to.

Actions. Access: rate_limit, cost_cap, require_evaluation. Input: block, redact_pii. Tools: trusted_sources, blocked_sources. Output: redact_pii, flag_for_review, withhold.

There is no log action any more. It wrote the rule's name, and nothing else, to container output, and turned the rule's activity outcome from no_change into applied. The activity log already records every applicable rule against every invocation, matched or not, so a rule's matches are visible with no action at all. Migration 79 removed it from stored rules, writing a version for each rule it changed (no actor). A rule left with no actions keeps running and keeps being recorded. Events recorded before the migration still carry log, and fe-core still labels them.

The quality check reaches the Output rules. Every agent turn ends in svc-ai's evaluator node, which now reports what became of the answer: passed, revised (it failed, the agent revised it, and the revision passed), failed (no revision passed, and the agent's latest answer went out) or unavailable (no evaluator model, or it errored). The evaluator no longer writes answers (agent-graph-review.md). The streamed agent turn adds quality_check and, when a check scored the draft, quality_score to the audit context (services/quality_check.audit_figures). A turn that never reached a check has neither, so a condition on them does not match. The score is the evaluator model's judgement, not a calibrated confidence. Before this, a broken evaluator reported a pass scored 80, and svc-core read the verdict from the wrong level of the stream event, so nothing it said was stored. svc-ai's forwarded copies of these rules never match, because inside a graph run no check has finished yet.

Latency and cost reach the Output rules. latency_ms and estimated_cost_usd were offered for Output rules and passed by no call site, so a condition on either never matched. Every path that runs Output rules — the agent stream and HTTP turn, a direct model prompt, a skill run segment and an evaluation cell — now adds usage.audit_figures(...) to the audit context: the model's time, timed around the svc-ai call (never the time a person took to answer a pause), and the turn's cost, computed by usage.turn_cost — the same function the ledger row uses, so "flag answers over $0.50" and the spend dashboard never disagree about one invocation. An unpriced model leaves the cost out, and a condition on it does not match: unknown is not free. svc-ai judges its forwarded copies the same way, from the done frame's metered usage and the run's start time (rules.output_figures). A pause is audited without either figure: it is not a finished call.

Personal data (PII)

redact_pii — in an Input rule and in an Output rule (Input's was filter_pii before migration 105) — replaces personal data with placeholders. The detectors are app/services/rules/pii.py, and svc-ai carries the same file byte for byte (app/inference/pii.py) — tools/test_shared_modules.py fails the build when the two differ, or when their tests differ by more than the import line. Svc-core redacts prompts, history, answers and stored responses; svc-ai redacts what it streams. A value one service caught and the other let through would be a rule that held or failed depending on where the text happened to be.

One class per kind. A Recogniser declares its formats, the checks a match must pass, its keywords, how it is described, and examples it must catch and near misses it must not — which tests/test_pii.py runs, in both services. The kinds, grouped by region:

  • International: email addresses, phone numbers (international, UK, US and European national formats), names (after a title or a form label), dates of birth (after a keyword), passport numbers (after the word, in eight languages), IP addresses (opt-in), payment card numbers (Luhn, every major scheme, spaced or not), IBANs (mod 97, every IBAN country).

  • United Kingdom: National Insurance numbers (HMRC's allocation rules), NHS numbers (mod 11), driving licence numbers, Unique Taxpayer References and sort codes / account numbers (after a keyword), postcodes (opt-in).

  • European Union: French NIR, German Steuer-ID, Spanish DNI / NIE, Italian codice fiscale, Dutch BSN, Belgian national register number, Polish PESEL, Swedish personnummer, Danish CPR, Finnish HETU, Irish PPSN, Portuguese NIF — each with its own checksum or encoded date verified, and the ones whose shape is just digits (BSN, PESEL, NIF…) only after their keyword.

  • United States: social security numbers (area, group and serial rules).

Precision is part of the job. A redaction that eats order numbers, dates, hashes and version strings ruins the prompts it is applied to, and gets switched off. So an identifier with a checksum is verified; a shape too common to redact on sight (nine bare digits) counts only with its keyword in the 48 characters before it; the North American phone format holds its area code to NANP's rule; and where two kinds claim overlapping text the longer match wins, then the one with its keyword nearby, then the one whose checksum held — so an IBAN beats the card-shaped run inside it, and "call 943 476 5919" is a phone number while "ref 943 476 5919" is an NHS number. A grouped value is searched for its longest valid run of whole groups, because a checksum cannot steer a regular expression's backtracking. Every pattern is linear: bounded repetition, possessive groups where a checksum follows, and a test feeding 100 KB of pathological input to each.

A rule chooses kinds. Both actions take kinds (the builder's What to redact): a list of kind keys, served as the parameter's options, with vocabulary: "pii_kinds" naming the catalogue section that describes them (GET /app/rules/catalogue → pii_kinds). Empty means the default set — every kind except IP addresses and UK postcodes, which identify a person only some of the time. A rule naming only kinds that no longer exist redacts the default set rather than nothing. A kind no detector knows is refused at save (422, proposals.unknown_terms) and drops a generated rule whole. The pii_types condition field lists every kind in the text, default or not, so a rule can block a prompt holding an NHS number (pii_types has_any nhs_number) and let one with an email address through; pii_detected stays the yes/no over the default set.

Placeholders are keyed. A value becomes [KIND_XXXX]: four Crockford base32 characters of an HMAC over the value's canonical form (spacing and case removed, so AB 12 34 56 C and ab123456c are one person), keyed with a key both services derive from INTERNAL_JWT_SECRET under a label of its own (pii.placeholder_key), and scoped to the owner. The same value gets the same placeholder for the same owner across turns and in both services — a model can tell two people apart and follow one through a conversation without either reaching it — and a different one for another owner. The suffix holds 20 bits, so it cannot be reversed even with the key. Rotating the secret changes every placeholder from then on.

What travels with the text meets the same redaction. A pass that ran a redaction action carries it (RulePass.redactor, merged across rules), and every caller applies it to whatever goes to the model beside the prompt or reaches a person beside the answer:

Input (redact_pii)Output (redact_pii)
the stored conversation history sent with it — stored as typed for any turn before the rule existed (RulePass.redact_history)the token stream, a buffer per node (StreamGuard in svc-ai)
a chat's attached documents, their names and text (never their ids): the rules read this message's with the words, then each copy is redacted apart (attachments.redacted; Attachments)node results, citations and pauses in the trace
answers to a paused run's questionsa skill run's outputs, state and steps
a skill run's inputsa pause's questions and draft
an evaluation case's conversation

The stream guard holds back 96 characters per stream and cuts only at whitespace outside every value it found, so a value cannot straddle released and held text; the text already released stays visible as context, so "passport number" in one token still marks the digits in the next. It is conservative: an Output rule's conditions are judged on the finished answer, which does not exist while the answer streams, so any Output rule carrying redact_pii guards the stream, and the final answer — judged by the rule's real conditions — replaces the streamed text.

Never the values. Redaction events carry kinds and counts. The direct model path no longer logs the prompt (it logged it in full at INFO, in front of every rule that redacted it everywhere else); it logs sizes.

Limits. Names are caught only after a title (Mr, Dr, Frau, Mme…) or a capitalised form label (Name:, Patient:) — not in free prose — and street addresses not at all (postcodes are, when chosen). Knowledge passages and tool results reach the model as they are; redact_pii still removes what the model writes back. Kinds outside the listed countries are not detected. Detecting names in prose needs a named-entity model in both images, which is a decision of its own.

The Tools layer: where an agent may look things up

A Tools rule (migration 106, October 2026) names web sources for the agents it covers:

  • trusted_sources — domains, and only. Off, the sources are put first wherever results are ranked, and the agent is told to read and cite them first. On, the agent may search and read nothing else.

  • blocked_sources — domains never to use: left out of every search, refused by every fetch, whatever else trusts them.

A domain covers itself and every subdomain (gov.uk covers hmrc.gov.uk), and is stored as app/util/web_domains.py reads it — lowercase, ASCII, no scheme, path, www. or wildcard — so a pasted link and a typed name are one value. Saving refuses an entry that names no domain (localhost, uk, an IP address), an empty list and more than 50 (422, Action.problems, also applied to generated rules), and stores the rest normalised (Action.normalise). The builder shows each as a chip (DomainListInput) the way it will be stored.

One policy a turn. The engine merges every applicable Tools rule's (WebPolicy.merge): only what every only list allows (a subdomain counts as within its domain), every trusted source and every blocked one, blocked winning. Merging can only tighten. only lists that share nothing leave no source: the web is off for the turn, and the tools and the answering model say so. The result is RulePass.web_policy; each rule's activity row records applied with its own domains and only — what it set on the run, never what the turn searched for.

Delivered beside the spend limit. Every path that evaluates the rules sets both with ai_client.in_turn_governance(rule_pass) (the chat socket use_turn_governance): the agent socket and batch prompt, model chat, skill runs, evaluation cells and dashboard tiles. The policy travels as X-Web-Policy (compact JSON, WebPolicy.encode) on every svc-ai call the turn makes. tests/test_turn_spend_limit.py holds every caller of evaluate_input to the helper. A resume after a pause uses the tighter of the turn's first policy and the re-check's (spend_limits.web_for_resume): a source a rule trusted only while the turn waited is not opened to it. A skill run's resumed segment is governed by its own fresh check, as its spend is.

Held by every web tool, at call time. svc-ai's middleware reads the header into app/common/web_policy.py. web_search, url_fetch and render_document's image fetches build their domain policy with DomainPolicy.for_run(config), which reads the request's policy each time it checks a URL — so it holds however the tool was reached: an agent's tool loop, a skill's tool node, a worker's general tools, a tool the planner added, retrieval workers. tests/tools/test_governed_web_policy.py fails on a tool under app/tools/ that builds any other policy (the webhook tool, which calls one configured address, is the exception). In search, trusted results outrank every other (rank_results(…, preferred)); when the first page has none, one more search scoped to them with site: runs (_trusted_search) — at most one extra Brave call a search, none when the clause would not fit. The answering node's <request_context> names the sources (web_policy.request_context_lines), so the cached system message is unchanged.

It fails closed. A policy is a restriction somebody wrote: a header svc-ai cannot read, or one too large to send (over 6,000 characters), allows no source — never none.

Settled after the run: "applied" only where it changed a search (October 2026). A Tools rule's action sets the run's sources, so its activity row read applied on every turn it governed, whether or not a search ever met it, and whether or not the agent searched at all. Now each web_search keeps a report (app/util/web_search_report.py, see web-search.md), and once the run is over svc-core settles the turn's Tools rules on them (web_search_summary.settle):

  • a rule stays applied when it changed a search: a blocking rule left a result out, an only-these rule left a result out, limited a query to its sources or refused the domains asked for, the rules left no source at all, or a trusting rule's sources were put first;

  • otherwise it reads no_change: "in force; the agent did not search the web", or "changed none of 4 searches".

Which rule a removal belongs to is read from the hosts the report names: a host a blocking rule's domains cover is that rule's, a host outside an only-these rule's domains is that rule's; a removal no named host explains (a search names at most ten) goes to every rule of its kind. Each settled row's detail gains detail[action].web — searches, narrowed, sites left out, sites put first, closed — counts only, never a host: the activity log keeps the rule's own words, not what the turn read. The rows written before the model are rewritten in the turn's own transaction (governance_activity.settle_tools, input phase, this turn's rows only), and the trace's policy node is corrected in place (build_rule_trace_update), on the chat socket and the batch prompt alike. Activity reads "Ruled out tabloid.example on the web — left out 2 sites in 1 of 3 searches". In the chat, a Tools rule draws attention to the answer only when it narrowed a search (decisionAttention.rulesActed): putting a source first is not something that happened to the answer.

The answer also stores what the turn's searches came to, meta.web_search (see web-search.md): the outcome, the engines' failures, what each check removed, and per Tools rule the hosts it left out or put first — counts only while a withhold rule governs the turn. The decision record's Web sources section shows each search and what each rule did.

Not settled yet: skill runs, evaluation cells and dashboard tiles, whose Tools rows still read applied. url_fetch keeps no report, so a page a rule refused to read does not count as the rule acting.

A notice under the answer, and an edit a step away (October 2026). When a Tools rule narrowed a search, the answer says so in one quiet line (components/chat/ChatPanel/WebSourcesNote.tsx, computed from meta.web_search by util/webSearchNotice.ts): "Searched only gov.uk and ico.org.uk — set by “UK regulators only”; left out bbc.co.uk", "Left out news.tabloid.example — ruled out by “No tabloids”", or "“Only gov.uk” allows only gov.uk, and no source was left to search". A rule that only put its sources first, and a search that found what it looked for, say nothing. When no rule was the reason — the engines found nothing, or could not answer — the line says that instead ("No trust rule limited this search. The search engine was unavailable (its usage quota is used up).") and offers Ask again on the latest answer, so a provider's failure is never read as a rule.

What the reader may do about a rule is the API's to say. GET /rules/{id} serves can_change — may_change_here: the Governance level the change needs (an editor, or a writer for a rule they created), and the request's workspace owning the rule, so never a built-in or what a project inherits — and home_workspace_name. Whoever may change it gets Edit rule, the rule's edit page with the one change that would let the agent use the site in its address (editRuleHref): ?add_trusted=bbc.co.uk for an only-these rule, ?remove_blocked=tabloid.example for a blocking one. The builder makes that change once, on the rule as it opens (rules/domainEdit.ts, normalised as svc-core stores a domain), and says what it did and that nothing changes until it is saved; a full list (50 domains), a source already covered, or removing the only source a rule blocks is explained and changes nothing. Saving is the rule's ordinary PATCH, so it writes a version: a link never changes a rule. Anyone else reads "Set by Acme — a governance editor there can change it", linked to the rule's page. PATCH and DELETE /rules/{id} now check the same (verify_change_here), where fe-core alone had refused an inherited rule, and the rule's page and edit page offer no change can_change denies.

What it does not govern. Agent-time web access only: knowledge crawls, source discovery, feed tiles, favicons, webhooks, geocoding and MCP servers keep their own policies. Built-in Trusted sources: UK & EU regulators (#11) puts GOV.UK, legislation.gov.uk, the ICO and the EU's institutions first; Trusted sources: wire services & public broadcasters (#13) is the list CHAINR Bot puts first.

CHAINR Bot's own sources give way to the rules (October 2026). The bot's searches put a platform list of publishers first where no workspace rule chose sources (platform_sources, see chainr-bot.md). It never restricts: a Tools rule covering the bot that trusts sources or allows only some replaces it, what a rule blocks comes off it, and a turn the rules leave no source puts nothing first. It is no rule: it writes no activity row and is never settled, and a search's report says sources_set_by: platform, so the summary attributes nothing to a workspace rule for it.

Shown on knowledge sources, display only. A knowledge source's trust panel reads the Tools rules governing the workspace (trust.ToolsRulesSignal): a site of its content that a rule blocks is a conflict, one a rule trusts is met. That is a reading of the rules against the source, never enforcement: knowledge retrieval is not filtered by Tools rules, and the panel says so. See the knowledge guide.

Withholding an answer

withhold (Output, October 2026) is the backstop for answers that must not reach people as written — a customer-facing agent's, say. Its params are message (what people receive instead) and review (default on: send the answer to review, the one place it is then kept; off, it is kept nowhere).

It runs last. The engine applies it after every other Output rule, whatever its priority (rule_engine.evaluate_output): a flag_for_review still sees the leaked key, a redact_pii still redacts, and then — if a withhold rule matched — the text becomes its message (the first such rule's, in priority order) and the pass carries withheld (rule_engine.Withheld: the message, the answer as the other rules left it, the rule, the workspace). Its activity row is applied with the message and review, never the answer.

Held until checked. Its conditions read the finished answer, so whether it fires is known only at the end. While a withhold rule governs a turn (rule_engine.may_withhold, its conditions aside), nothing of the answer reaches the person, or anywhere they can read, before the Output rules have run (app/services/withholding.py):

  • the chat socket streams no tokens, worker tokens or sources; it says the answer appears once checked (HELD_STATUS), and sends the answer's sources after the check, redacted;

  • svc-ai's trace frames pass through an allow-list (held_frame) — what ran, when, on which model, at what cost; never a node's input, output preview or state, a tool's arguments or result, or a system node's result — shown and stored alike; a pause passes, since it is checked before it is sent;

  • the stored answer keeps no worker text (segments) and no critique or gaps from the quality check (checked_verdict), only its outcome and score;

  • a turn stopped or failed part-way stores HELD_TEXT, never what it had written (the chat socket and model chat's Stop).

What is stored. The conversation holds the rule's message with meta.withheld (rule, version, whether it went to review) and no sources; the response frame and model chat's PromptResponse carry withheld. The answer goes to a review item of kind withheld (review.record_withheld, once per turn and rule), on review_flags.withheld_text (migration 107) — served only by the review queue (Schema.Review.Queued), to those who may review it. The decision record lists a turn's items as Review.Read, which has no such field, and says the answer was withheld (AnswerSection.withheld_by); the data export marks the column withheld (ExportTable.hidden). In a Personal workspace the person is their own reviewer.

Every path. The chat socket and batch prompt, model chat, evaluation cells (graded as the message, the cell's tool calls kept by name only, never corrected by a structured retry) and dashboard tiles, skill runs (the message as the run's output; no outputs, state, sources or step outputs) and pauses (hitl.audit_pause: an approval gate holds nothing, a clarification asks nothing; what it held goes to review with the turn).

svc-ai only observes it (rule_vocabulary.WithholdAction): while one governs a run (RulesEnforcer.may_withhold), memory keeps the request alone, tool calls are traced without arguments or results, and the stored execution keeps no output preview and an empty reply — all of which Activity and the decision record read.

Built-in Withhold answers that leak credentials (#12) withholds a response matching the credential pattern and sends it to review.

Quotas: rate limits and cost caps

rate_limit and cost_cap refuse an invocation once the allowance for its period is used. Both are policy actions, so they run before the prompt reaches the model — a cap that only noticed afterwards would have already spent the money.

ActionAllowanceDefault when no period is named
cost_capmax_usda trailing day

Both take the same choices (cost-control plan A1.1, October 2026), each a parameter whose values are a registry served in the rule catalogue, so the builder, the generators and the check on a saved rule read one list:

  • period (rules/periods.py, catalogue quota_periods): rolling — the trailing window_seconds, always moving, what every quota was before — or a calendar day, week (from Monday) or month, in UTC like svc-ai's spending ceiling. A calendar period is a budget: it starts again from nothing at its boundary, and its events carry resets_at. window_seconds applies to rolling only, and the builder shows it only then (ActionParam.shown_when).

  • share (quota_shares): shared — one allowance for everyone the rule covers — or per_member, the same allowance for each member, counting their own rows only (Span.member).

  • execution_types (the ledger's UsageEnum.ExecutionType): count only these kinds of work, and stand aside for the rest — a budget for evaluations alone. Empty is all of them.

  • on_reach (quota_responses): block refuses with the rule's message; warn lets the call through and records that the allowance was passed (warned, outcome applied) — a soft budget.

  • alert_at (quota_alerts, cost_cap only, cost-control plan A2): when to tell those who govern the workspace, in their inbox — half used, 80%, used up, heading over before it resets. Absent means 80%, used up and heading over; empty means none. See Alerts and the inbox.

  • reserve (quota_reserves, cost_cap only, cost-control plan A1.4): typical — the default — starts a turn only when what is left covers what a turn like it usually costs (the 90th percentile of the same resource's recent turns, usage.typical_turn_cost; $0.05 with too little history), so a turn is refused up front rather than cut off part-way through an answer; none starts any turn while anything is left. A refusal for room records reserve_usd and reserve_basis.

A cost cap that lets a turn through also limits it: what is left is the most the turn may spend, and svc-ai stops the turn's next model call once it has spent that (X-Spend-Limit). The stop is recorded on the activity log as an output-phase blocked row for the cap, with stopped_mid_turn, limit_usd and spent_usd, and the turn is stored with a message naming the budget. The deployment's platform allowance, when one is set, is judged first, as a cost cap no workspace can edit ("Platform allowance" on the log, no rule id). See A turn's own limit and Platform allowances.

A used-up cost cap stops more than turns (cost-control plan A1.5): generation flows, knowledge and repository search, indexing an upload, website crawls and simulation runs ask the same caps and the allowance first (rule_engine.evaluate_budgets, through budgets.gate.check) — those alone, with each cap's conditions and kinds of work as written, and no reserve. A cap that is used up refuses the work with a 403 (code: "budget"), a held upload is indexed when the budget starts again, a scheduled crawl is recorded held, and a person's refusal is on the activity log as a blocked row. See Every path stops at a used-up budget.

A quota under its allowance records what it counted too — an event with changed: false (outcome still no_change) carrying the spend or count, the allowance, remaining_usd, the period and when it resets — so the activity log can say "Under the cost cap — $31.20 of $50.00 this month". The built-in Monthly budget ($100 a calendar month, adopted by copy) is the starting point. Written in an organisation, a cap is one budget for the organisation and its projects (see below); marking it Required for all projects makes it apply inside them, and pinning it to a project gives that project its own allocation out of the organisation's population.

Governance → Spend reads every cost cap governing a workspace as a budget — spent, remaining, the period before, a forecast, and for those who govern the workspace what each member spent — from the cap's own reading, so a budget shown reached is one the next turn meets; and Add budget writes one without the builder (an organisation-wide Required cap, or an allocation pinned to a project). See Budgets.

Counting is scoped the way the rule is, not the way the invocation is, and counts the population of the workspace that owns the rule: a personal rule counts its owner's workspace and personal projects, an organisation's rule the organisation and all its projects, a project's rule the project — whoever invokes (see Whose rules apply). One evaluation now considers rules at several scopes at once — a global cap, the project's, and one pinned to a single agent can all match the same turn — and each counts a different population. UsageWindows hands each rule the window for its own scope, cached per scope so three rules capping the same agent cost one set of queries. The ledger records invocations that already happened, so max_invocations: 1 permits the first call and refuses the second.

Each scope decides for itself how it narrows the ledger, because they do not all count on the same axis. A ledger row records the resource that ran — no row will ever carry scope_type = project — so owner_project_id and owner_organisation_id are stamped alongside it, and an ownership-scoped quota counts on those instead. Those two columns arrived with migration 51 and are not backfilled: the ledger does not record what a resource's ownership was at the time, and inventing it from today's graph would put figures in an audit ledger that were never observed. An organisation- or project-scoped quota therefore counts from that migration forward.

A model-scoped quota counts every turn the model answered — prompted directly, or reached through an agent, a skill, an evaluation cell or a dashboard tile — on ai_model_id, the model that ran (ModelScope.usage_filter). Until October 2026 it counted rows recorded at model scope, which only a direct prompt is: a model's cap governed agent turns on the model without ever counting them.

The ledger

governance_usage (svc-core, postgres-core) holds one append-only row per governed invocation — tokens, an estimated cost, the scope, and when. A chat turn's row is written in the same transaction as the turn it documents, so it can never count a turn that was rolled back. An evaluation run is the exception, on purpose: each cell, and each call the judge makes grading one, is written in a transaction of its own the moment it finishes (runner.ledger_as_it_goes). A run's calls used to reach the ledger only when the whole run ended, so the cap judging cell 40 had not seen cells 1–39 and a run could spend past any cap by its whole cost. The money is spent whether or not the run's results are stored; only cells still in flight can now overshoot.

svc-ai owns the authoritative per-invocation record (LLMInvocation), and svc-core deliberately does not read it here: a cap has to be judged before svc-ai is called, and putting a synchronous cross-service hop in front of every governed request would make a svc-ai outage a governance failure — where fail-open and fail-closed are both bad answers. A local counter avoids the question.

Nothing edits these rows, so they carry no version history: the ledger is the evidence.

The ledger also records invocations that were attempted and failed (outcome, migration 56) — because an error rate per agent or per model has to be counted somewhere, and svc-ai's record carries no agent, project or organisation to count one against. A failed, refused or stopped turn carries what its calls cost before it ended (see cost-monitoring.md), because they were paid for — and a cost cap counts it: UsageWindow's cost reader reads every row that was paid for. A rate limit and a latency route still count only ok rows, the work the user actually got, so a provider outage cannot use up anyone's hourly allowance. A blocked invocation gets no ledger row; the rules that refused it are already recorded in governance_events, and writing it twice would have one turn owned by two surfaces that both claim to be authoritative. The exception is a block svc-ai enforced after the run had already made calls: those were paid for, and the ledger is where money is recorded. See statistics.md for the second reader this feeds.

Cost is what svc-ai measured. svc-ai meters every call it makes and prices it on the model that made it (cost-monitoring.md); record_usage(..., measured=) stores that. app.services.usage.estimate_cost — the request's tokens at the named model's catalogue price — is only the fallback for a call svc-ai did not meter. The figure is stored rather than recomputed later, because a model's price can change and a cap must be judged against what the call cost then.

A model that publishes no price yields None, not 0. That distinction is the point: a cost cap reading an unpriced model as free would never fire, which is exactly the silent non-enforcement this feature exists to prevent. So a cap counts an unpriced call at what svc-ai's ceiling counts it at — its tokens at the catalogue's dearest input and output rates — kept on the row as unpriced_estimate_usd (migration 95) beside the measured cost, which spend figures go on showing as a lower bound ("at least"). Rows from before migration 95 carry no estimate, and their unpriced calls still count nothing.

Routing rules were removed (October 2026)

Routing rules moved a turn to another model before it was sent: a fallback chain, the cheapest or the fastest model, or one with a capability or in a data region (fallback, route_cheapest, route_fastest, require_capability). They asked people to manage models, when what they care about is speed, quality and cost — which an agent's cost profile (Thorough / Balanced / Economy) and a workspace's budgets already set. Migration 104 deleted every routing rule, users' and the built-in Route long prompts alike, each with a deleted version marked as a CHAIN-R release (resource_versions.origin), and withdrew projects' declarations of them. app/services/turn_routing.py, rule_engine.resolve_routing and the four actions are gone; the model catalogue they ranked is app/services/model_catalogue.py, which an Economy lighter model and a native sibling are still chosen from. An evaluation run from the time a rule routed its cells still says so on the cell (run_metadata.routed_model).

Built-in rules

app/services/system_resources/rules.py declares twelve rules for the controls most deployments want: PII redaction on prompts and responses, blocking credentials and prompt injection in prompts, flagging leaked credentials in responses, a monthly budget and a daily spend cap, the evidence gate (excluding CHAINR Bot by a condition on its fixed id), putting UK and EU regulators first on the web and putting wire services and public broadcasters first (two Tools rules; the second is CHAINR Bot's own preferred sources, web_sources.domains()), withholding answers that leak credentials, and reviewing answers whose quality check failed or could not run (quality_check in failed, unavailable). A tenth, Route long prompts, went with routing rules (migration 104). They are is_system rows (migration 78) with fixed ids …000000000401 onwards, provisioned at startup like the other built-ins, with each release that changes one written as a version with no actor.

A built-in governs nobody. _get_applicable_rules loads only owned rules (the invoker's, and those of the organisations and projects in the chain) and also filters is_system out explicitly, so a built-in, which has no owner, cannot be pulled in. Built-ins are stored inactive and global.

Adopted by copy, not by reference. Other built-ins (the bot, skillsets, News) are used as they stand. A rule carries decisions only its owner can make: its scope, its thresholds, whether it is on. So the Rules tab draws each built-in as a template in its layer, and Use (or "Use this rule" on its page) opens the builder at /rules/new?from=<id> with the definition filled in, and POST /rules takes based_on_rule_id. The server accepts only a built-in there (422 otherwise), and records based_on_version itself from the built-in's current version. A release never changes an adopted rule. The rule's page says when the built-in has a newer release.

API. GET /rules?include_system=true appends the built-ins after the caller's rules, for the Rules tab only: every count of "your rules" reads the plain listing. GET /rules/{id} and the history routes use verify_resource_read; every write refuses a built-in (403).

Held to the generated-rule checks. tests/test_built_in_rules.py runs each definition through _validate_conditions / _validate_actions (the generative flow's validators), checks the patterns fit the 512-character regex limit both engines enforce, and runs them through condition_matches against lists of true and false positives. Names are short because cards truncate them.

Left out on purpose, because they would not do what their name says today:

  • A rate limit. Evaluation runs are concurrent and write the same ledger, so any default low enough to stop a runaway loop refuses chats while an evaluation runs.

  • Flag expensive or slow invocations. See the dead fields above.

A released built-in is corrected in place, never removed: users' rules point at it.

The evidence gate: require_evaluation

Rules govern each invocation; evaluation governs each configuration. The evidence gate is where the two meet. It is a policy action that lets an agent answer only when the version in force has passed an evaluation. That means a completed, scored run of the agent as configured at that version, which reaches the dataset's pass mark without regressing.

ParameterMeaning
min_scoreThe mean score to reach, 0–1. Empty means each dataset's own pass mark (0.8 unless the dataset sets one).
messageShown to the caller when refused, followed by the reason.

The refusal says why in words a caller can act on, for example: "This agent version has not passed its evaluation. It scored 0.62 on “Hallucination & grounding”, below the pass mark of 0.90." The activity log records the agent version, the reason and the runs the refusal rests on (batch_ids).

What it reads. It reads the completed runs of the agent's owner (evidence.evidence_owner) made since the agent's current version existed, through services/evaluation/evidence.py. An organisation's agent is judged on the organisation's evaluations, the same for every member: a member's private evaluation of it doesn't count, for them or anyone. A personal agent is judged on its owner's evaluations, and a built-in agent on the invoker's own. Governance → Evaluation → Assurance reads through the same module, so an agent the gate lets through is exactly an agent Assurance marks Passing, and a test pins that. "As configured" is decided when the run starts: a variant on another model or temperature, with a candidate prompt, or with different knowledge or tools, is an experiment about an alternative and is not evidence about the agent. Where one run evaluated the agent twice, the worse result stands. A run nobody has scored yet (manual grading) is not evidence either way.

What it stands aside for.

  • Evaluation runs (execution_type = "evaluation"). An evaluation is how a version earns its evidence, so gating it on having some would make a new version impossible to clear. Every other path is gated: chat, skill runs through an agent, dashboard tiles that borrow one, and answers to a paused turn.

  • Invocations with no agent. A direct model prompt has no version to evaluate. Scope the rule to the agents it should govern, or leave it global.

Typical use. A global or project-scoped rule with no dataset makes "no unevaluated agent version answers anyone" a platform guarantee. An agent-scoped rule pinned to a gold dataset, such as Hallucination & grounding at 0.9, makes one agent's answers conditional on one measured property. Editing the agent starts a new version, and the gate refuses it until that version is evaluated. Change control is therefore enforced, not advised.

It is core_only, like the quotas: the evidence lives in postgres-core.

The activity log: what the rules actually did

governance_events is the third audit table, beside governance_usage (what an invocation consumed) and review_flags (what a rule asked a person to look at). This one records the evaluation itself: one row per applicable rule per invocation, written by rule_engine.evaluate_input / evaluate_output through app/services/governance_activity.py, and read at GET /app/rules/activity — fe-core → Governance → Rules → Activity.

The rules that did nothing are the point. Before this, a rule's effects existed only as events inside a conversation's execution trace, and an action with nothing to do emitted no event at all. A redaction rule over a prompt containing no PII therefore looked exactly like a rule that had never been evaluated, and "was this invocation governed, and by what?" — the first question an audit asks — had no answer anywhere in the product.

So the outcome is a four-way distinction, not a boolean:

OutcomeMeaning
appliedit matched and its actions changed something
no_changeit matched, its actions ran, there was nothing to do
not_matchedits conditions did not hold, so no action ran

Three of those four are a rule working correctly. StatusBadge's GOVERNANCE_OUTCOME scale reflects that: no_change is success (a clean prompt is the reassuring answer, not an absent one), applied is done, not_matched is neutral.

Read a message at a time

GET /app/rules/activity returns groups, one per invocation, paged by invocation rather than by event. One turn is routinely governed by half a dozen rules across both phases; flat, they interleave with every other agent's traffic, and "what happened to this message?" — the question somebody monitoring a fleet is actually asking — stops being answerable. Paging by row would also cut a turn in half at a page boundary and show a reader half its governance.

The grouping key is governance_events.invocation_id (migration 54), minted once per request by the caller and put on both phases' evaluation contexts via rule_engine.INVOCATION_CONTEXT_KEY. Nothing else on the row could do it: a conversation has many turns, and the input and output passes are two separate evaluations seconds apart. Every path that evaluates rules mints one — the agent stream, the agent HTTP endpoint (which hands it to prompt_agent for the output phase), the direct model prompt, a skill run (one id across its segments) and an evaluation or dashboard cell.

Since migration 91 the same id is on everything else the turn writes: both of its messages (chat_messages.invocation_id), its ledger row (governance_usage), any review flag (review_flags), a skill run (skill_runs, a UUID since 91), and svc-ai's model and tool traces (core_invocation_id, svc-ai migration 26, from the X-Invocation-Id header that ai_client.in_invocation / use_invocation set around the turn's svc-ai calls). It is the key the decision record joins on. Rows svc-core writes take it as an argument, not from the contextvar: most are written in a run_in_executor thread, which does not inherit one. tests/test_invocation_ids.py fails on a record_usage or record_flags call that does not pass it; usage.record_measured (generation, retrieval, indexing) is exempt, because that spend is no one turn's. Migration 91 backfilled answers a rule ran on (through governance_events.message_id); nothing else recorded its turn before then.

Rows with no invocation_id — written before the column existed — group under their own id rather than collapsing into one NULL bucket, which is what coalesce(invocation_id, id) in invocation_page is for. They are not backfilled: grouping them by conversation and timestamp proximity would put a claim in an audit table that was never observed.

Each group carries its own per-outcome counts (the card's header), and subject — the agent's name, resolved server-side in one query for the page. Resolved rather than denormalised: the event has to outlive the agent, but while the agent exists its current name is the one a reader recognises, and a deleted one reads as "Deleted agent" the same way a deleted rule does. Models are deliberately not resolved — they are svc-ai's records, so naming one would put a cross-service call on a log page.

Opening the message

Each group carries conversation_id and message_id, and the card's Open message link goes to …/chat?conversation=<id>&message=<id> — the deep link both chat pages read (chatMessageHref in routes/resourceHref.ts builds it; Activity's run panel uses the same one). The chat selects that conversation, scrolls the message into view and rings it.

Both ids are written after the fact. Access and Input rules run before the prompt is sent and Output rules before the response is saved, so neither exists when the evaluation is recorded; governance_activity.link_invocation updates every row of the invocation in one statement once the turn persists, from each of the four paths that persist one (the agent stream and its blocked turn, the agent HTTP endpoint and its blocked turn, and the direct model prompt). A turn that never persisted has no message to point at, the link is absent, and that is the honest answer rather than a link to the agent's chat at whatever it happens to be showing.

How an outcome is decided

Every event an action emits may carry changed. Absent means True — flag_for_review has acted by definition. The actions that can run and find nothing to do say so explicitly:

  • redact_pii emits {"changed": false} when nothing matched, and {"changed": true, "redacted": {"email": 2, "card": 1}} when something did. Both services do this with the same detectors (pii.Redactor, one file carried by both).

  • rate_limit / cost_cap emit no event at all while under their limit, which reads as no_change; over it they emit their figures and a block decision.

  • A block folds its message onto the blocking action's event, so the row names one action and says what the caller was told.

What is recorded, and what deliberately is not

detail is keyed by action type and filtered through governance_activity.DETAIL_KEYS — redaction kinds and counts, a block's message, the figures a quota was judged against. Never the matched text. A log quoting what a redaction rule removed would be a durable copy of exactly the thing the rule exists to destroy, kept longer than the conversation it came from. An action added later has to opt its parameters in, so a future action carrying matched text cannot start leaking it into the log by default.

Transaction semantics

Rows are appended to the caller's session and not committed by the service, exactly as usage.record_usage does: the log belongs to the same transaction as the turn it describes. Two call sites need care and have it — the agent paths evaluate rules in a short-lived session of their own, and a blocked turn unwinds past the ordinary commit, so both call governance_activity.commit(thread_db) (which never raises, and rolls back rather than masking the block in flight).

Recording never fails an invocation. A record about a call is worth less than the call.

What it does not cover yet

Only svc-core's own evaluations are logged: every applicable rule against the prompt and against the final response. svc-ai re-enforces the forwardable rules inside a graph run, and those events reach the execution trace but not this table — recording both would show one rule twice for one turn, which is a worse answer than showing it once. The enforced_in column exists so that can change without a migration.

One consequence is visible: when svc-ai redacts a response before svc-core's audit pass sees it, this table records svc-core's no_change for that rule, while the turn's execution trace (below) shows applied, enforced in both.

In the execution trace

The same evaluations also go on the turn's execution trace, as the __policy__ and __audit__ system nodes that the chat's execution pipeline and the Activity page render. Each node's result carries:

  • evaluations: every applicable rule with its outcome, actions, detail and enforced_in (core, ai or both). evaluate_input / evaluate_output return a RulePass, which unpacks as (text, events) as before and adds .evaluations. A RuleBlock carries the evaluations up to and including the refusal, so a blocked turn shows what else ran on the prompt.

  • events: the raw action events, kept for the rule-hit charts and for older readers.

svc-ai's own enforcement of the same rules is merged into the entry for that rule; it never gets a node of its own (rule_engine.build_turn_rule_trace). Where the two services disagree, the stronger outcome wins, so a redaction svc-ai made is not undone by svc-core finding nothing left to redact. A stream sends the policy node before svc-ai runs, then corrects it in place with a second system_node_result frame (build_rule_trace_update) once svc-ai reports back. Before this, those events arrived as a second policy node and a second audit node after the answer: the same rule appeared twice, and the policy stage was drawn twice in the pipeline.

Traces persisted before evaluations existed are rebuilt from their events in fe-core (util/ruleTrace.ts). The view marks them as showing only the rules that acted, because the rules that stood aside were never recorded.

The reviewer queue

flag_for_review used to record a trace event and nothing else — the flag showed up inside a conversation's execution trace, which is not a place anybody reviews. It now writes a row to review_flags, and /app/reviews is the queue somebody works through, surfaced as Governance → Rules → Reviews in fe-core.

The queue holds everything that needs a person's decision, not only rule flags. review_flags.kind (migration 75) says what raised an item:

kindRaised byCarries
regressionAn evaluation run whose verdict is regressed (evaluation/assurance.open_regression_review)The experiment and run, the agent when the run evaluated exactly one, and what moved (regressed metrics, cases that broke).
withheldAn Output rule's withhold with review on (review.record_withheld)The rule, the turn, and the answer it withheld (withheld_text, served only here — see "Withholding an answer"). No excerpt.

A regression is queued once per run, for the evaluation's owner: the user, or, for an evaluation an organisation or project owns, that organisation's or project's governance editors (admins included). A rule flag goes to the rule's owner the same way, so a flag an organisation's rule raises on a member's response is the organisation's governance editors' to review, not the member's. Both kinds follow the same rules: resolution is terminal, and retention applies to rule flags only, since regressions carry no retention_days.

Endpoint
GET /app/reviews/summaryCounts per status — the queue header, and a stat widget's source.
GET /app/reviews/{id}One flag.
PATCH /app/reviews/{id}Record a decision: reviewed or dismissed, with an optional note.

Flags are recorded after the turn is persisted, so each one points at a conversation that exists and a turn that failed to persist leaves no flag behind pointing at nothing. Flags svc-ai raised arrive on rule_events and land in the same queue — a reviewer never has to know which service noticed.

One flag per rule per turn. A forwarded Output rule runs twice on the same answer: in svc-ai when it finishes, and here on the response svc-core stores. A turn that paused is also audited at the pause. Each pass raised its own flag, so one flagged answer showed as two or three queue items until October 2026. record_flags now collapses repeats within a call, keeping svc-core's own event, which carries the workspace. It also skips a rule that has already flagged the turn (invocation_id), which covers a skill run flagged at its pause and again when it finishes. Duplicates raised before the fix stay in the queue: they are audit records, and dismissing the spare is the way to clear one.

Resolving can also judge the answer. PATCH /app/reviews/{id} takes an optional verdict (accepted / rejected). It is recorded as the turn's decision outcome, with source review and the flag's id, in the same transaction as the decision, because a warranted flag can still sit on a right answer. A correction is made on the decision record, where the answer is.

The question is read, not copied. A rule flag is served with the question its answer was for (question), so a reviewer can judge the answer against what was asked. review.questions reads it per page from the turn: the user's stored message (post-redaction) or the skill run's request. It is not stored on the flag, so it goes when the conversation does, unlike the excerpt. Flags from before turns had ids (migration 91) have none.

The excerpt is taken after Output rules have run, so a rule that redacts PII has already done so. The queue must not become the one place the unredacted text survives.

Resolution is terminal

There is no reopen endpoint, and re-resolving an already-resolved flag is a 409. That is what lets one reviewed_by_user_id/reviewed_at pair on the row stand in for a full version history: a review decision is a record, not a setting, and overwriting it would destroy the audit answer the flag exists to give. If reopening is ever wanted, the flag needs a history trail first.

Rule identity is denormalised onto the flag rather than joined. Rule.name is mutable and a rule can be deleted outright — and a flag that resolved to nothing is exactly the evidence an audit needs. rule_version pins which revision fired.

Retention

flag_for_review takes a retention_days parameter. Leaving it empty keeps the flag indefinitely, which is the default on purpose: destroying audit evidence has to be a decision stated on the rule, not a platform default nobody chose. A non-numeric, zero or negative value also keeps the flag — never silently delete on a value nobody can parse.

The value is carried on the event, not read from the rule at write time, so the retention that applies is the one in force when the flag was raised rather than whatever the rule says later.

Expired flags are deleted by the hourly review_retention job (scheduler.md), across every owner. The queue's own read path still purges the queue being read, as the fallback for a deployment with the scheduler disabled or a replica that is not the elected leader — which is also what left every other owner's expired flags in place when it was the only mechanism. A retention period is still "deleted no earlier than" rather than "deleted exactly at" — the job's interval bounds how late — but the gap is now an hour rather than however long until somebody next opens the queue. Over-retention remains the safer direction to be wrong in.

Failure semantics

Quotas extend the engine's general rule — what cannot be evaluated does not fire:

  • no max_invocations / max_usd on the action → logged, never fires

  • the ledger query fails → logged, the rule stands aside

  • the ledger write fails → logged, the invocation proceeds

All three fail open. Refusing a user's request on a number the engine never obtained is a worse failure than allowing it and logging loudly — the operator sees the error either way, but only one of those takes the platform down when the ledger has a bad day. The bias is toward under-counting, never toward refusing on a figure that was never real.

The evidence gate follows the same rule, and draws one line precisely: unreadable evidence is not missing evidence.

  • the evaluation runs cannot be read → logged, the rule stands aside

  • a min_score that is not a number in 0–1 → logged, and the datasets' own pass marks apply (never "anything passes")

  • the runs are read and show no passing evaluation of this version → refused, which is the gate's purpose

  • the agent has no recorded version → refused: no evaluation can be tied to the configuration that would answer

Why svc-ai never sees them

Quota actions are marked Enforcement.core_only, and serialize_rules strips them before forwarding a rule to svc-ai (dropping the rule entirely if nothing else remains). svc-ai has no access to the ledger by design, so forwarding one would make it warn about an unsupported action on every invocation for a rule that is being enforced correctly — here.

The catalogue surfaces this as enforced_in on every action, so the builder can tell a quota action from a text one. An action type svc-core does not recognise is still forwarded: svc-ai owns its own vocabulary, and a newer svc-ai may understand something this svc-core does not.

Failure semantics

Every unrecognised or ill-formed thing never matches and never fires, and logs a warning:

  • an unknown field or operator

  • an operator paired with a field type it does not apply to (estimated_cost_usd contains 5)

  • a regex that does not compile or exceeds the length cap — for both matches and not_matches, so a broken negative rule does not start firing on everything

  • an action in the wrong layer (block on an Output rule)

  • a field with no value in this context

The alternative — treating "I cannot evaluate this" as "the condition holds" — makes one malformed block rule refuse every invocation on the platform.

A field that simply has no value resolves to None and does not match, without logging: partially-populated contexts are normal, and warning on them would fire on every invocation.

Tracing a result to the configuration that produced it

Every user-created resource already had an immutable version trail (see the history rules in CLAUDE.md). What was missing was the link from a result back to it: a conversation told you which agent answered, but not which revision of that agent — so a prompt edited five times since left every earlier result unattributable.

Each agent turn now records the version in force on the assistant message's meta:

meta: { agent_version: 7, agent_id: "…" }

Captured when the agent's configuration is read, not when the turn is persisted. An edit landing mid-turn must not make the record claim a revision that never ran that prompt. Blocked and errored turns are stamped too — a refusal is the case most likely to be challenged later, so it is the one that least tolerates an unattributable configuration.

A resource with no history rows yet records nothing rather than guessing 1: a number nothing supports is worse than an absent one.

app.services.history.current_version is the single lookup behind this — one grouped max(version_number) query, so stamping provenance never costs a query per resource. The rule engine's rule_version stamp goes through the same function; it previously kept a private copy of that query, and asking the same question two ways invites the two answers to drift. It never raises: provenance metadata is worth less than the invocation it describes.

Reading it back

On the Activity page an assistant message carries a v7 badge beside its model badge, linking to …/agents/id/{id}?version=7. The agent's own history panel reads that parameter and opens on that revision instead of the newest — landing on the newest would answer a question nobody asked and quietly show a configuration that is not the one under investigation. initialVersion only seeds the view, so clicking through the timeline afterwards works normally.

Where the agent has since been deleted the badge still states the version but does not link: there is nothing left to resolve it against, and saying so is better than a dead link.

A direct model prompt carries no version, because models are svc-ai's records and svc-core's mirror has no history (the "Model has no history" gap in CLAUDE.md) — deliberately, not by omission.

Keeping the two in sync

The services are separate images with separate dependency trees and cannot share code, so the mirror is pinned by matching tests:

  • svc-core/tests/test_rule_vocabulary.py

  • svc-ai/tests/inference/test_rule_vocabulary.py

Each holds a literal manifest of every operator, field and action key, the actions per layer. svc-core's pins every layer's set and the subset it forwards (none of Access's); svc-ai's pins Input's and Output's, which must match it. Widen one service alone and the other's test fails. Keep the lists literal — deriving them from the registry would make the test pass by construction and pin nothing.

The quota and evidence actions are deliberately absent from svc-ai's manifest: they read svc-core's ledger and evaluations, and are resolved before that service is called. svc-core's manifest therefore pins two sets, the full one and the forwarded subset, and it is the forwarded subset that must match svc-ai's list.

Generating rules

POST /app/rules/generate proposes rules from a description of what the user wants governed, and POST /app/rules/create-from-config persists a reviewed proposal. The frontend entry point is the Generate button on Governance → Rules, beside New Rule.

The flow follows the skillset/toolkit/knowledge generative flows — GenerationRun opened at invocation, redacted arguments, output stamped is_ai_generated + generation_id, a ResourceVersion per created rule — with one thing that is specific to governance.

The vocabulary travels with the request. svc-core sends the same catalogue /app/rules/catalogue serves the builder (each layer with its label, question, fields and actions, the operators, the scopes) plus what this user may pin a rule to, and svc-ai's prompt quotes it verbatim. Nothing about the grammar is written down in svc-ai/app/routers/rules_setup.py: a field invented there would produce a rule that stores, lists as active, and never matches, because conditions.condition_matches logs a warning and returns False for a field it does not know. Adding a field to the registry therefore reaches the generator with no svc-ai release, exactly as it reaches the builder with no frontend release.

A rule that cannot be enforced is dropped whole, never repaired. app/router/app/rules/setup.py re-validates every proposed rule against the registries — the authoritative check, since svc-ai's copy of the grammar arrived from here. A rule is dropped, with a warning naming it and the reason, when:

RejectedWhy not repair it
a field with no value in that layer's phase (response on an Input rule)same: the condition would never match, so the rule fires on everything else
unknown scope, or a scope_id that resolves to nothing this user ownsfalling back to the whole scope widens it; an unresolvable pin is what POST /app/rules already refuses
an action not registered for that layer, or a required action parameter left emptya rate_limit with no max_invocations cannot be evaluated

Values are coerced to the type each registry entry declares (structured output is all strings; the engine compares numbers and booleans), and action parameters arrive as key/value pairs and are flattened into the stored action block.

create-from-config runs the same validation and refuses with 422 rather than dropping: by then a person has reviewed the blocks, and a silent shrink at that point would hide a rule they believe they approved. It also runs the ordinary _verify_scope from the rules router, so the two creation paths cannot disagree about what a valid pin is. A reviewed rule posts its actions back in their stored shape — parameters inline, not as key/value pairs — and validation reads both shapes (app/services/rules/proposals.py). Until October 2026 it read only the pairs, so a reviewed block lost its message to the default and a reviewed rate_limit was refused for want of the limit it carried.

Agent setup writes rules in the same vocabulary. POST /app/agents/generate sends catalogue.generation_vocabulary() — the catalogue above, every layer, so an agent's proposed rules may cap its spend as well as redact — and svc-ai renders it into the agent generator's prompt with the same renderer the rule flow uses (svc-ai/app/services/rule_catalogue.py). Every proposed rule goes through app/services/rules/proposals.py, dropped with its reason on /generate and refused on /create-from-config. Before this, agent setup kept its own copy of the grammar in svc-ai (Literal types and a prompt written by hand) plus a second validator in svc-core; the prompt went on offering the log action for months after migration 79 removed it, while the schema beside it refused the value. One vocabulary, one validator: an action added to the registry is proposable by both flows the moment it is enforceable.

Where it lives in fe-core

One page: Governance, third in the main nav after Inference and Knowledge, with two tabs: the two kinds of standard a fleet is held to.

TabOpens onA link away
EvaluationAssurance: which agent versions have evidence behind them.Datasets and the experiments on them, and Reports. See Evaluation.

Each tab opens on the standard and reaches what follows from it through SubsectionLinks, with a back link out, as Evaluation does. Activity sits before Reviews deliberately. It is the evidence a reviewer reads a flag against, and the only place a rule that ran and correctly did nothing is visible at all. Its card counts the last day's rule evaluations; the Reviews card counts what is pending. Both were tabs beside Rules and Evaluation until October 2026, which made what the rules did read as two more standards; ?section=activity and ?section=reviews still open them, now inside the Rules tab. Evaluation moved here from Inference, and every old address redirects.

Rules were previously two subpages of Inference (?section=rules under Agents, ?section=model_rules under Models), each showing a scope-filtered slice of the same list, and Reviews was a separate top-level page. That split made a rule read as a property of the page you found it on: a global rule appeared twice, a skill-scoped rule was only reachable from the agents side, and a project-wide rule had nowhere to appear at all. Both old ?section= values redirect.

The Rules tab (apps/user/pages/rules/RulesGrid.tsx, wave 3 of the October 2026 redesign) reads as the request's own path:

  • The layer flow (LayerFlow.tsx, in ResourceCollection's summary slot) sits under the stats: one step per layer in flow order, each with its icon, label, question and how many of the workspace's rules it holds, and the model marked between Input and Output. A step filters the page to its layer (?layer=); the selected step again shows them all. It replaced the layer filter in the toolbar.

  • One section per layer, headed by its label and question (the catalogue's), with Add opening the builder on that layer (/rules/new?layer=). The workspace's rules come first; then the layer's templates (the built-ins), as dashed cards with Use and how many rules started from each. A layer that already holds rules of the workspace's folds its templates behind "Show N templates"; one that holds none shows them, as the place to start. A search never folds a match away. Scope and status filters drop templates, since only rules in force answer them. The separate Built-in section is gone.

  • Cards say what a rule does, in svc-core's words: each action summarises its own block (Action.summarise: "Caps spend at $100 a month", "Redacts email addresses from the answer", "Sends the answer to review, kept 90 days"), served one line per action as Rule.Read.summaries (app/services/rules/summary.py). An action its layer does not carry reads "Does nothing: …", because the engine skips it. Then the description, when it applies ("Always" or "When N conditions hold"), its scope, Active / Off, and its priority only when it is not the default.

Cells are neutral: a layer is named by its icon, label and place from the one registry in apps/user/pages/rules/ruleLayer.ts, never by a tint, and the card's glyph names it to a screen reader rather than repeating the section heading. The red, blue and amber cells and saturated rails the rule types carried read louder than the rules; colour on these pages is kept for meanings — a rule's Active / Off state (RULE_STATE) and an activity row's outcome (GOVERNANCE_OUTCOME). Old activity rows and traces that name a type read through layerOf, as migration 105 sorted the rules.

The builder (NewRule.tsx's RuleBuilder) asks in the order a person thinks a rule: where in a request it acts (the layer), what it does (actions), when (always, until a condition is added), what it covers (scope and target), then its name — which follows the first action's label until the person writes one. Priority and Active sit under "More settings". The same builder edits: Edit on a rule's page opens /governance/rules/id/<id>/edit (EditRule.tsx), which saves through PATCH /rules/{id}. A built-in, an inherited or required rule, one from another workspace, or one the caller may not change (can_change false: a governance writer and another member's rule) goes back to its page instead, which offers no Edit, toggle or delete for it either; svc-core refuses the same change (verify_change_here). ?add_trusted= / ?remove_blocked= pre-fill one domain change for review (see the Tools layer).

A rule's page (RuleViewer.tsx) shows its place among the layers under the title (LayerPosition), then What it does (each action's summary with its settings), When it applies (conditions by the catalogue's field and operator names, or "Always — to every request in its scope"), and Where (its scope, and "Required for all projects" where that applies), then its edit history.

With one merged list, the scope becomes the column a reader scans by — so describeScope resolves a pinned scope_id through /app/rules/targets and the row says "Support Agent", not eight characters of a UUID. A pin whose resource no longer resolves falls back to the kind: a deleted target is exactly when the label matters, and the raw id tells the reader nothing.

Testing

make test-core                     # includes test_rule_engine + test_rule_scopes + test_rule_vocabulary + test_rule_setup + test_governance_activity
make test-ai                       # includes tests/inference/test_rules + test_rule_vocabulary + routers/test_rules_setup
cd modules/fe/core && npx vitest run src/apps/user/pages/rules src/apps/user/pages/Governance.test.tsx

The frontend tests serve a catalogue containing fields and scopes that have never been hard-coded in the frontend and assert they reach the DOM — the property being tested is that the builder renders from the backend, not from a list of its own. NewRule.test.tsx's catalogue offers a project scope for exactly that reason: it was never in the old hard-coded list.