# Learn the rule language

Build the rules of a payments agent in short examples, from one amount limit to rules that read earlier calls in the run or the session.

You can write an Amiril rule as text, in the rule language. This guide builds the rules of a payments agent one idea at a time. The first four examples grow one rule step by step, and each one after that adds one more thing a rule can do.

## Block a call over a limit [#block-a-call-over-a-limit]

```amiril
@id("payment-cap")
block (
    agent,
    tool == "issue_payment"
)
when {
    call.args.amount > 10000
};
```

- `@id("payment-cap")` names the rule. The model reads this id when the rule blocks a call.
- `block` is the effect. The call does not run.
- The head, in parentheses, picks the calls the rule checks. `agent` alone means every agent. `tool == "issue_payment"` means calls to that tool.
- `when { ... }` fires the rule when its condition is true.
- `call.args.amount` reads the `amount` argument of the call being checked.

## Describe a good call with `unless` [#describe-a-good-call-with-unless]

```amiril
@id("payment-cap")
block (
    agent,
    tool == "issue_payment"
)
unless {
    call.args.amount > 0 && call.args.amount <= 10000
};
```

`unless` fires the rule when its condition is false, so you write what a good call looks like. This one also blocks an amount of zero or less. `&&` means and, `||` means or and `!` means not.

A call with no `amount`, or with `amount` set to `null`, makes neither condition true. So the `when` rule above lets it run, and this `unless` rule blocks it. Test for the value with `present()` when such a call should pass.

## Pick the agent and the tools [#pick-the-agent-and-the-tools]

```amiril
@id("payment-cap")
block (
    agent == "payments",
    tool in ["issue_payment", "refund_payment"]
)
unless {
    call.args.amount > 0 && call.args.amount <= 10000
};
```

`agent == "payments"` applies the rule to one agent only. Use a name your agent is seen under in Amiril, such as the name you give it in the SDK. A rule that names an agent Amiril has never seen does not save. Amiril sees an agent once it runs with the SDK, or once a trace from it arrives. `tool in [...]` lists several tools, and `tool` alone covers every tool.

## Tell the model why with `@sentence` [#tell-the-model-why-with-sentence]

```amiril
@id("payment-cap")
@sentence("A payment of {amount} is over the 10000 limit")
block (
    agent,
    tool == "issue_payment"
)
when {
    call.args.amount > 10000
};
```

When a rule fires, it gives one sentence. If the rule blocks the call, the model reads that sentence. You also see it on the rule's page and in test results. Without `@sentence`, the sentence is the rule's id and the values it read:

```text
payment-cap (amount 20000).
```

With `@sentence`, it says what went wrong. `{amount}` fills in the value of the argument:

```text
A payment of 20000 is over the 10000 limit.
```

## Allow listed values with `in` [#allow-listed-values-with-in]

```amiril
@id("currency-allowed")
@sentence("Payments in {currency} are not allowed")
block (
    agent,
    tool == "issue_payment"
)
unless {
    call.args.currency in ["USD", "EUR", "GBP"]
};
```

`in` checks a value against a list. A list takes fixed values only, such as numbers and quoted strings.

## Check a format with `matches` [#check-a-format-with-matches]

```amiril
@id("invoice-id-format")
block (
    agent,
    tool == "issue_payment"
)
unless {
    present(call.args.invoice_id)
        && matches(call.args.invoice_id, "^INV-[0-9]{6}$")
};
```

`present()` is true when the call has the argument. `matches()` tests the whole value against a regular expression, so `"^INV-"` alone matches only the value `INV-`. To test how a value starts, use `starts_with(call.args.invoice_id, "INV-")`. The [reference](/rules/reference#functions) lists the other functions, such as `len()` and `is_number()`.

## Check the day with `weekday` [#check-the-day-with-weekday]

```amiril
@id("no-weekend-payments")
block (
    agent,
    tool == "issue_payment"
)
when {
    weekday(ctx.now, "Europe/London") in ["Sat", "Sun"]
};
```

`weekday()` gives the day of the week, from `"Mon"` to `"Sun"`, in a time zone such as `"Europe/London"`. `ctx.now` is the time of the call. `hour()` and `date()` read the hour and the date the same way. These functions need SDK 0.1.0 or later.

## Require an earlier call with a pattern [#require-an-earlier-call-with-a-pattern]

```amiril
@id("verify-before-pay")
@sentence("{payee} was not verified earlier in this run")
block (
    agent,
    tool == "issue_payment"
)
unless {
    verify_payee{ args.payee == call.args.payee }
};
```

A run is one piece of work by your agent, such as answering one message. `verify_payee{ ... }` is a pattern, and it matches earlier calls in the run. It is true when an earlier call to `verify_payee` meets the condition in its braces. Inside the braces, `args.payee` is the earlier call's argument and `call.args.payee` is the current call's. Only earlier calls that succeeded count.

## Read an earlier result with `latest` [#read-an-earlier-result-with-latest]

```amiril
@id("verified-payee")
block (
    agent,
    tool == "issue_payment"
)
unless {
    payee = call.args.payee;
    registered = latest(verify_payee{ args.payee == payee }).result.registered;

    registered == true
};
```

`latest(verify_payee{ ... })` picks the most recent matching call, and `.result.registered` reads a field of what it returned. This rule blocks a payment unless the check said the payee is registered.

A line such as `payee = call.args.payee;` names a value. Named values go first inside the `when` or `unless` braces, and the condition below can use them.

## Allow one payment per invoice with `@per` [#allow-one-payment-per-invoice-with-per]

```amiril
@id("one-payment-per-invoice")
@per("invoice_id")
block (
    agent,
    tool == "issue_payment"
)
when {
    issue_payment{}
};
```

A session is the runs that share a session id, such as one conversation. The SDK takes the id from your framework, or from your code when you [mark the run](/sdk/no-framework#mark-the-run).

`@per("invoice_id")` makes the pattern match only earlier calls with the same `invoice_id` as the current call. It looks in every run of the session. The empty braces of `issue_payment{}` add no other condition. So the first payment for an invoice runs, and a second payment for it is blocked. A payment for another invoice runs.

## Cap a session total with `sum` and `@scope` [#cap-a-session-total-with-sum-and-scope]

```amiril
@id("session-payment-total")
@scope("session")
@sentence("This payment brings the session total to {session_total}, over 50000")
block (
    agent,
    tool == "issue_payment"
)
unless {
    session_total = sum(issue_payment{}.args.amount, call.args.amount);

    session_total <= 50000
};
```

`sum(issue_payment{}.args.amount, call.args.amount)` adds the amounts of earlier payments to this one. By default a rule reads earlier calls in the same run. `@scope("session")` makes it read every run in the session instead.

A named value can go in the sentence too. Values the sentence does not name are added in parentheses at the end:

```text
This payment brings the session total to 60000, over 50000 (amount 30000).
```

## Flag calls past a budget with a pattern slot [#flag-calls-past-a-budget-with-a-pattern-slot]

```amiril
@id("run-call-budget")
flag (
    agent,
    tool
)
unless {
    len(calls(*[status == "any"]{})) < 40
};
```

`flag` lets the call run and marks it for review. In the pattern `*[status == "any"]{}`, the `*` matches a call to any tool.

Square brackets after the tool contain a pattern slot, which changes the calls a pattern matches. By default a pattern counts only calls that succeeded. `status == "any"` counts failed and blocked calls too.

`calls(...)` returns the matching calls and `len()` counts them. The rule flags each call after the run's first 40.

## Act by amount with `bands` [#act-by-amount-with-bands]

```amiril
@id("payment-bands")
bands (
    agent,
    tool == "issue_payment"
)
by {
    call.args.amount
}
then {
    <= 1000: allow,
    <= 10000: flag,
    else: block
};
```

`bands` measures the value in `by` and acts by its size. A payment of up to 1000 runs. Up to 10000, it runs and is flagged. Anything larger is blocked.

## Next steps

- [Rule language reference](https://docs.amiril.ai/rules/reference.md): Every part of the rule language on one page. Annotations, effects, head slots, clauses, reads, operators, functions, patterns and syntax limits.
- [Rule recipes](https://docs.amiril.ai/rules/recipes.md): Complete rules to paste into the rule editor and adapt to your agent. Start from a payment cap, a format check, a required order or a budget per run.
- [Write your first rule](https://docs.amiril.ai/rules/first-rule.md): Start from a rule Amiril drafted for an issue, or from a blank rule. Save it, publish it in Shadow, then switch it to Enforce in one environment.
- [Test a rule on past calls](https://docs.amiril.ai/rules/test.md): Replay a rule over the tool calls your agents already made and see which ones it would have fired on, before it blocks anything.

## More detail

- [Rule language grammar](https://docs.amiril.ai/assistant/rules/grammar.md): The full grammar of rule text: lexical rules, the shape of a rule, expressions, reads, patterns, normal form, and worked rules.
- [Rule errors](https://docs.amiril.ai/assistant/rules/errors.md): Every way rule text or a rule save is rejected: syntax messages, Amiril's own checks, the SDK loader's problem codes, and save and publish refusals, each with its meaning and fix.
- [SDK behaviour in detail](https://docs.amiril.ai/assistant/sdk.md): The Amiril SDK past the setup guides: per-framework gaps, run ids and sessions, hook order and its errors, restarts, shutdown, offline behaviour, model messages, tested versions.
