Evals

Invariants

Rules over a whole run, such as approval before any send or one charge per booking, checked over every event and shared with Viewport HITL.

A tool-sequence assertion checks one run's shape. An invariant states a rule that must hold at every step, in every run: "every send_campaign has an approval before it", "at most one charge per booking", "never call delete_account". The document format is invariant/v1 from Viewport Core, the same one Viewport HITL enforces before each action at runtime. One policy file, both places: HITL blocks the violation in production, Evals proves in CI that the agent never needed blocking.

A policy file

policies/campaigns.yaml
# The campaign policy. Viewport HITL enforces it before every send at runtime; Viewport Evals asserts the same
# invariants over finished runs in tests. One file, both places.
version: 1

rules:
  drafting: { allow: draft_campaign }
  sends:
    ask: send_campaign
    reason: A campaign send reaches real customers

invariants:
  - name: approval before any send
    each: { tool: send_campaign }
    after: { approval: { tool: send_campaign, status: [approved] } }
    same: $.call_id

  - name: one send per audience per day
    each: { tool: send_campaign }
    limit: { max: 1, by: $.args.audience, per: 24h }

HITL reads the whole file; Evals reads its invariants: list. Load it in code, or reference it from a case with expect: { invariants: { file: policies/campaigns.yaml } } (relative to the case file).

main.py
POLICY = load_invariants(Path(__file__).parent / "policies/campaigns.yaml")
main.ts
const policy = loadInvariantsSync(join(import.meta.dirname, "policies/campaigns.yaml"));

Operators

Each invariant has a unique name and exactly one operator.

OperatorHolds when
afterevery event matching each has an earlier event matching after
not_afterno event matching each has an earlier event matching not_after
followed_byevery event matching each has a later matching event; within: 24h bounds the gap (Evals only)
limitat most max events matching each per partition by a path, optionally per a time window; sum limits the total of a numeric path instead of the count
neverno event matches (no each)

A selector picks events:

  • { tool: send_campaign, args: <matcher>, ok: true }: tool calls. tool takes a name, a glob (mcp__crm__*) or a list; ok: true keeps successful calls, ok: false failed ones.
  • { approval: { tool: send_campaign, status: [approved] } }: approval events, with HITL's statuses allowed, approved, denied, expired and cancelled.
  • { event: <type>, where: <matcher> }: any other event type.

same correlates the two events of after, not_after and followed_by: a path ($.call_id), a list of paths, or a map { "$.args.customer_id": "$.args.id" }. Between a tool call and its approval, $.call_id falls back to the approval's tool_call_id when a side has no call id. Without same, correlation is by order only, and viewport-evals validate warns.

The rules fail closed: a path that does not resolve, a non-numeric sum, or a missing timestamp under per or within is a violation, never a pass.

An invariant whose each matches no event in a run holds vacuously: nothing was guarded, often because the tool was never called or never recorded. The assertion still passes, but it carries a note (each {"tool":"send_sms"} matched no event in this run, so nothing was checked), the pretty reporter prints it under the case, and the verdict JSON keeps it on the assertion. To make "it happened" a requirement, add a count next to the invariant (tools: { counts: { send_sms: { min: 1 } } }).

A per window counts every earlier event of the same partition whose time is within per of the guarded event's, in either direction and with both ends inclusive. An event listed earlier but stamped later still counts, so a trajectory with out-of-order timestamps cannot slip past a limit.

In code and in YAML

t.upholds(invariants) returns a Check (truthy in Python); t.violations(invariants) lists each violation with its invariant, event index and message; vitest has expect(t).toUphold(invariants). A passing run and a failing one:

main.py
async def test_every_send_is_approved_first_and_each_audience_gets_one_send() -> None:
    model = script(DRAFT, turn(send("spring-regulars"), send("lapsed-riders")), reply("Sent to 2,452 riders."))
    w = campaigns.create()

    async with trace() as t:
        await marketing_agent(model.async_anthropic(), reviewed(w.tools), PROMPT)

    assert t.upholds(POLICY)
    assert [a.tool_name for a in t.approvals] == ["send_campaign", "send_campaign"]
    assert w.changed == ["$.drafts['CMP-1']", "$.sends['SND-1']", "$.sends['SND-2']"]

main.ts
test("every send is approved first, and each audience gets one send", async () => {
  const model = script(draft, turn(send("spring-regulars"), send("lapsed-riders")), reply("Sent to 2,452 riders."));
  const world = campaigns.create();

  const t = await trace(() => marketingAgent(model.anthropic(), reviewed(world.tools), PROMPT));

  expect(t).toUphold(policy);
  expect(t).toHaveRequestedApproval("send_campaign");
  expect(t.approvals).toHaveLength(2);
  expect(world.changed).toEqual(["$.drafts['CMP-1']", "$.sends['SND-1']", "$.sends['SND-2']"]);
});
main.py
async def test_a_run_without_the_review_gate_breaks_both_rules_at_the_exact_step() -> None:
    # A refactor dropped the gate, and the model resent to an audience after a slow response.
    model = script(DRAFT, send("spring-regulars"), send("spring-regulars"), reply("Sent, twice to be safe."))
    w = campaigns.create()

    async with trace() as t:
        await marketing_agent(model.async_anthropic(), list(w.tools), PROMPT)

    assert not t.upholds(POLICY)
    found = t.violations(POLICY)
    assert [(v.invariant, v.index) for v in found] == [
        ("approval before any send", 5),  # the first send
        ("approval before any send", 8),  # the resend
        ("one send per audience per day", 8),
    ]
    # Each violation names the offending event and why it broke the rule.
    assert found[2].message == (
        'events[8] send_campaign({"audience":"spring-regulars","campaign_id":"CMP-1"}) is number 2 for '
        '$.args.audience = "spring-regulars" in the last 24h, over max 1'
    )

main.ts
test("a run without the review gate breaks both rules, at the exact step", async () => {
  // A refactor dropped the gate, and the model resent to an audience after a slow response.
  const model = script(draft, send("spring-regulars"), send("spring-regulars"), reply("Sent, twice to be safe."));
  const world = campaigns.create();

  const t = await trace(() => marketingAgent(model.anthropic(), world.tools, PROMPT));

  expect(t).not.toUphold(policy);
  const found = t.violations(policy);
  expect(found.map((v) => [v.invariant, v.index])).toEqual([
    ["approval before any send", 5], // the first send
    ["approval before any send", 8], // the resend
    ["one send per audience per day", 8],
  ]);
  // Each violation names the offending event and why it broke the rule.
  expect(found[2]?.message).toBe(
    'events[8] send_campaign({"audience":"spring-regulars","campaign_id":"CMP-1"}) is number 2 for ' +
      '$.args.audience = "spring-regulars" in the last 24h, over max 1',
  );
});

In a case, expect.invariants takes a list of invariants, { file } references, or both. Each invariant is one assertion, invariants.<name>. Invariants in suite defaults and those shipped by world packs are added to a case's own, never replaced. The booking example writes its rules inline:

evals/booking.yaml
# yaml-language-server: $schema=https://getviewport.com/schemas/evals/case/v1.json
# A week at the studio as one case: Odile texts on Monday, pays the deposit, and gets her reminder on Friday.
# Every step of input.script is an episode; `advance` moves this run's simulated clock and wakes due timers.
id: inquiry-to-paid-booking-to-reminder
description: Hold, deposit, confirmation, then a reminder 24 hours before the appointment.
clock: { start: 2026-11-23T09:00:00Z }

world:
  studio:
    seed:
      events:
        E-1:
          id: E-1
          title: "Booked: ceramic coat for Ruiz"
          start: "2026-11-28T13:00:00Z"
          end: "2026-11-28T16:00:00Z"
          attendees: [[email protected]]
          status: confirmed
  shop:
    seed:
      customers:
        CU-1:
          id: CU-1
          name: Odile Ferreira
          email: [email protected]
          card: { brand: visa, last4: "4242", status: valid }

input:
  script:
    - user: "Can you do a full detail on Saturday at 9? This is Odile Ferreira, customer CU-1."
    - event: { type: checkout.completed, booking_id: B-1, customer_id: CU-1, amount: 5000 }
    - advance: 5d

expect:
  tools:
    in_order: [find_free_slots, create_event, send_deposit_link, create_charge, confirm_booking, send_reminder]
    calls:
      - { tool_name: create_charge, args: { amount: 5000, idempotency_key: "deposit:B-1" } }
  events:
    # The reminder fires in the advance episode, 24 hours before 9:00 Saturday.
    - type: tool_call
      where: { tool_name: send_reminder, episode_id: ep_2, started_at: "2026-11-27T09:00:00.000Z" }
      count: 1
  invariants:
    - name: no booking confirmation before the deposit is paid
      each: { tool: confirm_booking }
      after: { tool: create_charge, ok: true }
    - name: at most one deposit per booking
      each: { tool: create_charge, ok: true }
      limit: { max: 1, by: $.args.idempotency_key }
    - name: reminders only for confirmed bookings
      each: { tool: send_reminder }
      after: { tool: confirm_booking }
  world:
    studio:
      only_changed: ["$.events['E-2']"]
      state:
        { events: { E-2: { title: "Booked: full detail for Odile Ferreira (B-1)", start: "2026-11-28T09:00:00Z" } } }
    shop:
      changed: ["$.charges['CH-1']"]
      state: { charges: { CH-1: { amount: 5000, customer_id: CU-1 } } }
  output: { contains: booked }

Approvals and gated actions

Two streams read approval events. approvals holds human approvals (decision: ask), once per approval id. gated holds every policy outcome for a gated action, including automatic allow and deny, with status and decision maps. A policy that simply allowed a read never counts as an approval. Both take the usual sequence keys.

Next: worlds.

On this page