scrusted-yaml 0.2.0

Validates, loads and resolves scripted-yaml files: YAML with FEEL formulas in marked keys, reloaded live.
Documentation

Scrusted-yaml

CI

Business rules in YAML, computed in Rust, changed while the server runs.

Rate limits, validation rules, permissions, prices, order states: keep them in files you can read and change, and let your Rust application run them.

See the examples side by side → Rust code today, the rule file, and the Rust code that reads it, with a live reload simulation.

  • Live reload. Edit a rule file on a running server. The change goes live only after it validates and its tests pass, in one atomic swap; a broken change is refused and the previous version keeps serving.
  • Built for Laravel Rust. scrusted-yaml-laravel reads config/*.yml live in development and compiles them into the binary for production, where a broken rule fails cargo build.
  • Typed results. A file resolves into your own serde structs. A change that no longer fits the struct is refused at reload, not discovered on a request.
  • Fast. Formulas are parsed once. Resolving is synchronous, Send + Sync, and takes microseconds, so it runs inside a request handler.
  • Safe to edit. The validator refuses the formula mistakes that silently give a wrong answer, and evaluation has limits on steps, depth and time.
  • Same files as scripted-yaml, the TypeScript library. One conformance suite of more than 4,000 cases checks that both give the same results.
  • Self-contained files, with $vars for inputs, $schema for structure, $tests for examples, and $extends for patches and templates (state machines, menus, forms).
  • Skills for coding agents: scrusted-yaml skill --install teaches an agent to write rule files, move Rust logic into them and build an editor for them.

Application code and business rules

Application code reads requests, talks to the database and renders pages. Along the way it makes decisions: how many requests a free team gets, who may publish a post, when an order can ship. Written in Rust, each decision is a match or an if deep in a handler, and changing it means a pull request, a build and a deploy.

Business rules take those decisions out into a file. The code keeps the types, the I/O and the wiring; the file keeps the numbers, the conditions and the texts. Someone who does not write Rust can read the file, and change it while the server runs.

Why YAML?

YAML is readable and compact. On top of it, scripted-yaml adds a little:

  • formulas in FEEL, the expression language of decision tables: per_minute!: if vars.plan = "pro" then 600 else 60
  • {{ }} in text: subject: Invoice #{{ vars.invoice.number }} is paid
  • $vars to declare the inputs a file needs
  • $schema (inline) or $dsl (shared) to check its structure
  • $if!, $each!, $when to make parts of it conditional
  • functions the application passes in, and ten built-in text functions

Brief

Rate limits per plan

The limits live in a middleware. Nobody outside the backend team sees them, and raising the free plan's limit takes a deploy:

#[middleware]
async fn api_limits(request: Request, next: Next) -> Response {
    let team = request.team();
    let per_minute = match team.plan {
        Plan::Free => 60,
        Plan::Pro => 600,
        Plan::Enterprise => 3_000,
    };
    Throttle::per_minute(per_minute).by(format!("team:{}", team.id)).handle(request, next).await
}

Write them in a file instead:

# rules/rate-limits.yml
$vars:
  plan: { about: The team's plan. }

plans:
  free:
    per_minute: 60
  pro:
    per_minute: 600
  enterprise:
    per_minute: 3000

per_minute!: dig(plans, vars.plan).per_minute

The middleware reads the version being served now:

#[derive(Deserialize)]
struct Limits {
    per_minute: u32,
}

#[middleware]
async fn api_limits(request: Request, next: Next) -> Response {
    let team = request.team();
    let limits: Limits = SCRUSTED.resolve_as("rate-limits.yml", &vars! { plan: team.plan }, &ResolveOptions::default())?;
    Throttle::per_minute(limits.per_minute).by(format!("team:{}", team.id)).handle(request, next).await
}

A free team floods the API during a launch. Lower its limit on the running server, and the next request reads the new value:

 plans:
   free:
-    per_minute: 60
+    per_minute: 30

Install

[dependencies]
scrusted-yaml = { version = "0.2", features = ["live"] }   # with live reload
# scrusted-yaml = "0.2"                                    # validate, load, resolve only
serde = { version = "1", features = ["derive"] }

The command line, to validate and test rule files in CI:

cargo install scrusted-yaml-cli

In a Laravel Rust application, use scrusted-yaml-laravel instead: a service provider that reads config/*.yml live in development and compiles the files into the binary for production (below).

The FEEL evaluator alone is the crate scrusted-feel.

When not to use it

  • Complex logic. Formulas are for rules a person reads and changes: thresholds, conditions, visibility, prices. Algorithms, I/O and anything async stay in Rust.
  • Untrusted authors. A rule file can call the functions and markers your application registers. Let the people who own the rules edit them, not the users of your application.
  • Static config. If nothing in a file is computed and nothing changes at runtime, plain serde config is simpler.

Quick start

use scrusted_yaml::{MemoryFiles, ResolveOptions, ScrustedYaml, vars};

#[derive(serde::Deserialize)]
struct Limits {
    per_minute: u32,
    per_day: Option<u32>,
    bucket: String,
}

let rules = MemoryFiles::from_pairs([(
    "rate-limits.yml",
    "$vars:\n  plan: { default: free }\nper_minute!: if vars.plan = \"pro\" then 600 else 60\nper_day!: if vars.plan = \"free\" then 1000 else null\nbucket: api-{{ vars.plan }}\n",
)]);
let scrusted = ScrustedYaml::builder().files(rules).build()?;
let document = scrusted.load("rate-limits.yml")?;

let limits: Limits = document.resolve_as(&vars! { plan: "pro" }, &ResolveOptions::default())?;
assert_eq!((limits.per_minute, limits.per_day, limits.bucket.as_str()), (600, None, "api-pro"));
# Ok::<(), Box<dyn std::error::Error>>(())

In an application, read the files from a folder with DiskFiles::new("rules/"), and serve them with live reload (next section).

Live reload

This is the reason to use the library on a server. With the feature live, the files under a folder are loaded at start and watched while the application runs.

use std::sync::{Arc, LazyLock};
use scrusted_yaml::{DiskFiles, MarkerOutput, ResolveOptions, ScrustedYaml, live::Live, vars};

pub static SCRUSTED: LazyLock<Live> = LazyLock::new(|| {
    ScrustedYaml::builder()
        .files(DiskFiles::new("rules/"))
        .marker("job", |source| Ok(MarkerOutput::Host(Arc::new(Job::named(source.to_text())))))   // run!job: SendReceipt
        .strict(true)                             // a warning blocks a change too
        .run_tests(true)                          // each file's $tests must pass
        .shape::<Limits>("rate-limits.yml")       // the file must still give a Limits
        .build()
        .and_then(|library| library.live())       // loads every file, then watches the folder
        .expect("rules/ does not load")           // at boot, a bad file stops the app
});

When a file changes, it goes through these gates, in order:

  1. Read the new text.
  2. Parse the YAML and every formula.
  3. Validate: names, schema, the refused formula mistakes.
  4. Dependents: every file that $extends, $imports or $dsls it loads again.
  5. Tests: the $tests of every file in the set pass.
  6. Shape: each file registered with .shape::<T>() still deserializes into T.
  7. Swap: the new set is published with one atomic pointer write.

If a gate fails, nothing is published: the previous version keeps serving, and the problems, with file and line, go to your listener.

SCRUSTED.on_reload(|event| match event {
    ReloadEvent::Reloaded { generation, files } => tracing::info!(generation, ?files, "rules reloaded"),
    ReloadEvent::Refused { files, problems } => tracing::error!(?files, ?problems, "rule change refused"),
});
  • No request sees half a change. SCRUSTED.snapshot() gives one generation: a request that reads several files reads them all from the same version, and a request that started on version 6 finishes on 6.
  • No lock on the request path. Reading the live version is one atomic load; resolving is in memory.
  • Admin pages. status() lists each file's live version and its last refused change; rollback(file) publishes the previous good version through the same gates; reload_now() re-reads everything, for a deploy hook.
  • Files on disk are watched, debounced (150 ms by default). Files in a database, or any other impl Files, are polled with .poll(Duration::from_secs(5)); with several servers, each one polls and runs the gates itself.
Change Takes effect
a number, threshold, text, condition live
an item added to a table or list (a plan, a menu item, a transition) live, when Rust reads it through a field it already has
a new field your Rust struct must read deploy: the struct changes
a new marker or host function deploy: a file can only call what the app passes

Laravel Rust

scrusted-yaml-laravel wires all of this into a Laravel Rust application with one service provider and one switch:

providers.add(RulesProvider::new(compiled!("config")).shape::<Limits>("rate-limits.yml"));
RULES_MODE Rules come from
auto (default) live when APP_ENV=local, compiled otherwise
live config/*.yml on disk, reloaded on save through the gates above
compiled built into the binary; compiled! runs the same checks and $tests during cargo build, so a broken rule fails the build

Handlers take Inject<Rules>, and laravel rules:status and laravel rules:test come with it. See its README.

Examples

The examples use Laravel for Rust: its middleware, policies, notifications and workflows. Scrusted-yaml knows no framework; the same calls work in an axum or actix handler. Each example shows the rule file and the Rust code that reads it, and they are ordered by how much a team usually gains from moving the rule out of the code.

All of them read the live library from the section above, SCRUSTED.

1. Rate limits per plan and route

The full version of the brief above: limits per plan, a smaller share for expensive routes, and no daily cap for enterprise.

# rules/rate-limits.yml
$vars:
  plan: { about: The team's plan. }
  route: { optional: true, about: The route group. }

plans:
  free:
    per_minute: 60
    per_day: 1000
  pro:
    per_minute: 600
    per_day: 50000
  enterprise:
    per_minute: 3000
    per_day: null

routes:
  uploads:
    share: 6
  search:
    share: 2

limit!: dig(plans, vars.plan)
route_rule!: |
  if vars.route = null then null
  else dig(routes, vars.route)

per_minute!: |
  if route_rule = null then limit.per_minute
  else floor(limit.per_minute / route_rule.share)
per_day!: limit.per_day
bucket!: if vars.route = null then "api" else vars.route
#[derive(Deserialize)]
struct Limits {
    per_minute: u32,
    per_day: Option<u32>,
    bucket: String,
}

#[middleware]
async fn api_limits(request: Request, next: Next) -> Response {
    let team = request.team();
    let limits: Limits = SCRUSTED.resolve_as("rate-limits.yml", &vars! {
        plan: team.plan,
        route: request.route_group(),
    }, &ResolveOptions::default())?;

    let mut throttle = Throttle::per_minute(limits.per_minute)
        .bucket(&limits.bucket)
        .by(format!("team:{}", team.id));
    if let Some(day) = limits.per_day {
        throttle = throttle.and(Limit::per_day(day));
    }
    throttle.handle(request, next).await
}

A free team uploading gets 10 per minute in the bucket uploads; an enterprise team gets 3,000 per minute and no daily cap.

2. Validation rules that depend on plan and tenant

The input struct keeps the types and the fixed checks. Which fields are required, and their limits, depend on the plan and the tenant, so they live in the file.

# rules/validation/signup.yml
$vars:
  input: { about: The submitted fields. }
  tenant: { about: Settings of the tenant. }

team!: vars.input.plan = "team"

fields:
  - id: company
    required!: team
    max: 120
  - id: seats
    required!: team
    min: 2
    max!: if vars.tenant.tier = "enterprise" then 500 else 50
  - id: vat_id
    required!: vars.input.country in vars.tenant.vat_countries
    pattern: '^[A-Z]{2}[0-9A-Z]{8,12}$'
#[derive(Deserialize)]
struct Form {
    fields: Vec<FieldRule>,
}

#[derive(Deserialize)]
struct FieldRule {
    id: String,
    required: bool,
    min: Option<f64>,
    max: Option<f64>,
    pattern: Option<String>,
}

impl ValidatesRequest for Signup {
    async fn rules(&self, request: &Request, rules: Rules) -> Rules {
        let form: Form = SCRUSTED.resolve_as("validation/signup.yml", &vars! {
            input: self,
            tenant: request.tenant(),
        }, &ResolveOptions::default())?;
        for field in &form.fields {
            rules.field(&field.id, field.to_rules());   // Rule::required(), Rule::max(n), Rule::regex(p)
        }
        rules
    }
}

unique and exists stay in Rust: they query the database. The same file can also draw the form in the browser, with scripted-yaml.

3. Authorization policies

The policy keeps its methods, so user.authorize(PostPolicy::update, &post) still fails to compile on a typo. The answer comes from the file.

# rules/policies/posts.yml
$vars:
  user: { optional: true, about: The signed-in user; null for a guest. }
  post: { about: The post. }

signed_in!: vars.user != null
is_owner!: signed_in and vars.user.id = vars.post.user_id
is_editor!: signed_in and vars.user.role in ["editor", "admin"]

abilities:
  update:
    $value!: is_owner or is_editor
    message: Only the author or an editor can change this post.
  publish:
    $value!: is_editor and vars.post.status = "review"
    message: An editor publishes a post once it is in review.
  delete:
    $value!: signed_in and vars.user.role = "admin"
    message: Only admins delete posts.
#[derive(Deserialize)]
struct Policy {
    abilities: HashMap<String, Ability>,
}

#[derive(Deserialize)]
struct Ability {
    #[serde(rename = "$value")]
    allowed: bool,
    message: String,
}

#[policy]
impl PostPolicy {
    pub fn update(user: Option<&User>, post: &Post) -> Access { decide("update", user, post) }
    pub fn publish(user: Option<&User>, post: &Post) -> Access { decide("publish", user, post) }
    pub fn delete(user: Option<&User>, post: &Post) -> Access { decide("delete", user, post) }
}

fn decide(ability: &str, user: Option<&User>, post: &Post) -> Access {
    // every silent null is an error here: a null must never read as "no" or "yes"
    let options = ResolveOptions { strict_nulls: true, ..Default::default() };
    match SCRUSTED.resolve_as::<Policy>("policies/posts.yml", &vars! { user: user, post: post }, &options) {
        Ok(policy) => match policy.abilities.get(ability) {
            Some(Ability { allowed: true, .. }) => Access::allow(),
            Some(denied) => Access::deny(&denied.message),
            None => Access::deny("No rule for this action."),
        },
        Err(_) => Access::deny("Permission rules are unavailable."),
    }
}

Anything other than true denies. Give policy files $tests, so a reload that would open a door is refused.

4. Prices, discounts and shipping options

# rules/shop/discounts.yml
$vars:
  cart: { about: The order. Its subtotal is used here. }
  customer: { about: The buyer. Past orders and tags. }

is_vip!: |
  count(vars.customer.orders) >= 10
  or "vip" in vars.customer.tags

discount:
  loyalty!: if is_vip then vars.cart.subtotal * 0.05 else 0
  volume!: if vars.cart.subtotal >= 200 then 15 else 0
  $value!: max(loyalty, volume)
  note: The bigger of the two discounts applies.

to_pay!: vars.cart.subtotal - discount

shipping:
  - name: Standard
    price!: if to_pay >= 50 then 0 else 4.90
  - name: Express
    price: 12.90
    $if!: is_vip

message: You pay {{ to_pay }} and save {{ discount }}.
#[derive(Deserialize, Serialize)]
struct Checkout {
    to_pay: Decimal,
    discount: Discount,
    shipping: Vec<Shipping>,
    message: String,
}

#[derive(Deserialize, Serialize)]
struct Discount {
    #[serde(rename = "$value")]
    amount: Decimal,
    note: String,
}

async fn checkout(request: Request) -> laravel::Result<Response> {
    let cart = Cart::current(&request).await?;
    let customer = request.user().customer().await?;   // I/O stays in Rust; the results are passed in

    let price: Checkout = SCRUSTED.resolve_as("shop/discounts.yml", &vars! { cart: cart, customer: customer }, &ResolveOptions::default())?;
    view("checkout", price)
}

A VIP cart of 240 gets the volume discount of 15 (more than the loyalty 12), pays 225, and is offered Express. Numbers are decimals: money adds up exactly.

5. Order processing as a state machine

Built on the bundled template scripted-yaml/state-machine. Each state lists the events it takes and where they lead; a guard is a formula that gives the next state, or null while the event is not allowed. on names the job to dispatch on entering a state, and _ the one for every move. The jobs come from functions the file declares and the application passes, so validate refuses a name nobody declared.

# rules/orders/order-states.yml
$extends: scripted-yaml/state-machine

$vars:
  order:
    about: total, in_stock

# The application passes these; each returns the job to dispatch.
$functions:
  SendReceipt(order):
  RefundPayment(order):
  WriteAudit(order, event):

# Each state lists the events it takes and where they lead.
# A formula is a guard: null means "not now".
states:
  draft:
    pay!: if vars.order.total > 0 then "paid" else null
    cancel: cancelled
  paid:
    ship!: if vars.order.in_stock then "shipped" else null
    cancel: refunded
  shipped:
    deliver: delivered
    return: refunded
  delivered:
  cancelled:
  refunded:

# The job to dispatch on entering a state; `_` on every move.
on:
  paid!: SendReceipt(vars.order)
  refunded!: RefundPayment(vars.order)
  _!: WriteAudit(vars.order, vars.event)
#[derive(Deserialize)]
struct Machine {
    next: State,
    allowed: Vec<Event>,
    error: Option<String>,
    effects: Vec<Marked<Job>>,   // the jobs the declared functions built
}

#[derive(Deserialize)]
struct OrderRef { id: u64 }

// each declared function builds a job and does nothing else: resolving is synchronous
fn jobs() -> Functions {
    Functions::new()
        .add("SendReceipt", |o: Typed<OrderRef>| Ok::<_, HostError>(Job::value(SendReceipt { order_id: o.0.id })))
        .add("RefundPayment", |o: Typed<OrderRef>| Ok::<_, HostError>(Job::value(RefundPayment { order_id: o.0.id })))
        .add("WriteAudit", |o: Typed<OrderRef>, event: String| Ok::<_, HostError>(Job::value(WriteAudit { order_id: o.0.id, event })))
}

pub async fn fire(order: &mut Order, event: Event) -> laravel::Result<()> {
    let machine: Machine = SCRUSTED.resolve_as("orders/order-states.yml", &vars! {
        state: order.state,
        event: event,
        order: &*order,
    }, &ResolveOptions::default().functions(jobs()))?;
    if let Some(error) = machine.error {
        return Err(Error::conflict(error));   // "Cannot ship from draft"
    }
    order.state = machine.next;
    order.save().await?;
    for job in machine.effects {
        job.get().dispatch().await?;
    }
    Ok(())
}

// the buttons on the order page: the same file, without an event
pub fn actions(order: &Order) -> Vec<Event> {
    SCRUSTED.resolve_as::<Machine>("orders/order-states.yml", &vars! { state: order.state, order: order }, &ResolveOptions::default().functions(jobs()))
        .map(|machine| machine.allowed)
        .unwrap_or_default()
}

Job::value wraps a job as a Value::Host, so it comes back in effects as itself. Shipping a paid order in stock moves it to shipped and dispatches only WriteAudit. A new state needs a variant in the Rust enum first: the shape gate refuses a file that names one Rust does not know.

6. Which channels a notification takes

channels() runs once per recipient, is synchronous and cannot query the database. Resolving a loaded file has the same shape.

# rules/notifications/invoice-paid.yml
$vars:
  user: { about: Who receives it, with their settings. }
  invoice: { about: The paid invoice. }

large!: vars.invoice.amount >= 1000

channels:
  - name: mail
  - name: sms
    $if!: |
      vars.user.phone != null
      and (large or vars.user.sms_receipts)

subject: 'Invoice #{{ vars.invoice.number }} is paid'
sms: 'Paid: {{ vars.invoice.amount }} {{ vars.invoice.currency }}. Thank you!'
#[derive(Deserialize)]
struct InvoiceRules {
    channels: Vec<Channel>,
    subject: String,
    sms: String,
}

impl InvoicePaid {
    fn rules(&self, user: &User) -> InvoiceRules {
        SCRUSTED.resolve_as("notifications/invoice-paid.yml", &vars! { user: user, invoice: &self.invoice }, &ResolveOptions::default())
            .unwrap_or_else(|_| InvoiceRules::mail_only())   // a rule error never drops the email
    }
}

#[notification]
impl InvoicePaid {
    fn channels(&self, user: &User, channels: &mut Selected<Self, User>) {
        for channel in &self.rules(user).channels {
            match channel.name.as_str() {
                "mail" => channels.add(Mail),
                "sms" => channels.add(Sms),
                _ => {}
            }
        }
    }

    fn sms(&self, user: &User) -> String {
        self.rules(user).sms
    }
}

An invoice of 1,200 EUR to a user with a phone goes by mail and SMS, with the subject Invoice #1042 is paid.

7. Throttling sign-in and one-time codes

# rules/attempts.yml
$vars:
  action: { about: "login, otp or password_reset" }
  failures_today: { type: number, about: Failed attempts of this account today. }

actions:
  login:
    per_minute: 5
  otp:
    per_minute: 3
  password_reset:
    per_minute: 2

per_minute!: dig(actions, vars.action).per_minute
captcha!: vars.failures_today >= 5
locked!: vars.failures_today >= 20
message!: |
  if locked
  then "Too many failed attempts today. Reset your password to sign in."
  else "Too many attempts. Try again in a minute."
#[derive(Deserialize)]
struct Attempts {
    per_minute: u32,
    captcha: bool,
    locked: bool,
    message: String,
}

async fn sign_in(request: Request, form: Valid<SignIn>) -> laravel::Result<Response> {
    let failures = Failures::today(&form.email).await?;   // fetched first, passed in
    let rules: Attempts = SCRUSTED.resolve_as("attempts.yml", &vars! {
        action: "login",
        failures_today: failures,
    }, &ResolveOptions::default())?;

    if rules.locked {
        return Err(Error::locked(&rules.message));
    }
    if rules.captcha && !form.captcha_passed() {
        return Ok(Response::needs_captcha());
    }
    rate_limit::attempt(&format!("login:{}", form.email), Limit::per_minute(rules.per_minute)).await??;
    // ... check the password
}

During an attack, lower the attempts or the captcha threshold without a deploy.

8. A navigation menu for each user

Built on the bundled template scripted-yaml/navigation-ui, which also computes the active item, the breadcrumbs and the sitemap.

# rules/ui/navigation.yml
$extends: scripted-yaml/navigation-ui

$vars:
  user: { about: The signed-in user. }
  features: { about: Feature flags of the team. }

$replace:
  menu:
    - label: Dashboard
      path: /
    - label: Projects
      path: /projects
    - label: Reports
      path: /reports
      $if!: vars.features.reports
    - label: Admin
      $if!: vars.user.role = "admin"
      items:
        - label: Users
          path: /admin/users
        - label: Billing
          path: /admin/billing
          $if!: vars.user.owner
#[derive(Serialize, Deserialize)]
struct Navigation {
    menu: Vec<MenuItem>,
    active: Vec<String>,
    breadcrumbs: Vec<Crumb>,
}

// shared Inertia props, the same for every page
fn shared_props(request: &Request) -> laravel::Result<Navigation> {
    Ok(SCRUSTED.resolve_as("ui/navigation.yml", &vars! {
        path: request.path(),
        user: request.user(),
        features: request.team().features(),
    }, &ResolveOptions::default())?)
}

At /admin/users, an admin who is not the owner sees Dashboard, Projects, Reports and Admin with Users only, and the breadcrumbs Admin › Users.

9. Decisions inside a durable workflow

A workflow's handle replays from the top and must make the same decisions every time. Resolve the rule file inside a step: the step's result is recorded, so a run in flight keeps the decision it made, even after the file changes. The order of steps stays in Rust.

# rules/workflows/onboarding.yml
$vars:
  user: { about: The new user, with their plan. }
  active: { type: boolean, optional: true, about: Logged in since sign-up; null before the check. }

nudge_after_days!: if vars.user.plan = "trial" then 2 else 5
send_nudge!: vars.active = false
nudge_template!: |
  if vars.user.plan = "trial" then "trial-ending"
  else "getting-started"
assign_manager!: vars.user.plan = "enterprise"
#[derive(Serialize, Deserialize)]
struct Onboarding {
    nudge_after_days: u32,
    send_nudge: bool,
    nudge_template: String,
    assign_manager: bool,
}

#[workflow(name = "onboard-user", queue = "workflows")]
impl OnboardUser {
    async fn handle(self, run: &Run) -> laravel::Result<()> {
        run.step("send welcome email", self.send_welcome_email()).await?;

        let plan = run.step("decide", self.decide(None)).await?;   // recorded once, replayed as recorded
        if plan.assign_manager {
            run.step("assign manager", self.assign_manager()).await?;
        }
        run.sleep(plan.nudge_after_days.days()).await?;

        let active = run.step("check activity", self.has_logged_in()).await?;
        let later = run.step("decide again", self.decide(Some(active))).await?;
        if later.send_nudge {
            run.step("send nudge", self.send_nudge(&later.nudge_template)).await?;
        }
        Ok(())
    }
}

impl OnboardUser {
    async fn decide(&self, active: Option<bool>) -> laravel::Result<Onboarding> {
        Ok(SCRUSTED.resolve_as("workflows/onboarding.yml", &vars! { user: self, active: active }, &ResolveOptions::default())?)
    }
}

The file language

You write It means
key: value data; only {{ formula }} inside text is computed
key!: formula the value is one formula
key!name: value the value goes to the application's marker function name
$keyword: a word of the language: $vars, $value, $if!, $schema, …

Formulas

Formulas are FEEL, the expression language of DMN.

vars.method = "GET"                          equals is ONE =; text in double quotes
a and b     a or b     not(a)                not is a function
vars.NAME != null                            "is set": an unset variable is null
if a then b else c                           else is required
x in ["a", "b"]      day between 1 and 5     one of; within
cart.items[price > 10].name                  pick items; a bare name is a field of the item
count(list)  sum(list)  list[1]  list[-1]    lists count from 1
for item in list return item.price * 2       one result per item
some item in list satisfies item.price > 5   also: every
{ base: 10, total: base * 2 }.total          named steps

A key is computed only when something reads it, once per resolve, and the order of keys means nothing. A path names a key of the file: discount.loyalty, or an item of a list by its id: stages.explore.when.

The built-in functions are FEEL's (string join, starts with, substring, round half up, date and time, …) and ten one-word text functions: trim, lowercase, uppercase, capitalize, slug, snakecase, kebabcase, camelcase, pascalcase, titlecase; and dig(map, key), the one-word get value(map, key) for a key known only at run time.

The validator refuses forms that would silently give a wrong answer, and says how to write them:

Written Message
a == b equals is one =
not x not is a function: write not(x)
x in [1, 2] and y put the in test in brackets: (x in [..]) and y
a && b, !a write and, or, not(a)
c ? a : b write if c then a else b
'text' text is in double quotes
if a then b if needs an else
list[0] positions start at 1
list[not(x)] compare it: [not(x) = true]

Keywords

$vars:                                    # the inputs; required unless optional or a default
  cart: { about: The order. }
  coupon: { optional: true, type: text }
  TOKEN: { optional: true, secret: true } # kept out of error messages
  '/[A-Z_]+/': { optional: true }         # any upper-case name

$functions:
  inCart(wanted)!: vars.cart.items[category = wanted]   # defined in the file
  fileCount(mask):                                 # passed by the application
    about: How many files match the mask.

$import:
  ./settings.yml: settings                # another file's data, as settings.currency

discount:
  loyalty!: if count(vars.cart.orders) >= 10 then vars.cart.subtotal * 0.05 else 0
  volume!: if vars.cart.subtotal >= 200 then 15 else 0
  $value!: max(loyalty, volume)           # reading `discount` gives this
  note: The bigger of the two applies.

shipping:
  - name: Standard
    price: 4.90
  - name: Express
    price: 12.90
    $if!: vars.cart.subtotal > 50         # the item exists only when true ($unless! too)
  - $each!: settings.warehouses           # one item per value
    $as: warehouse
    name: Pickup in {{ warehouse.city }}

checkout:
  methods: [card]
  $when:                                  # every matching case applies; $else when none did
    - $if!: vars.cart.subtotal > 1000
      methods: [card, bank_transfer]

$tests:                                   # run by `scrusted-yaml test` and before a reload
  - about: A big cart gets the volume discount
    vars:
      cart: { subtotal: 250, orders: [] }
    expect:
      discount: 15
      count(checkout.methods): 1

$schema (or a shared $dsl: ./kind.dsl.yml) says which keys a file has:

$schema:
  required: [stages*:Stage]               # many: a list, or a map by name
  optional: [summary]
  Stage:
    key: id                               # the field that names an item
    required: [id, title]
    optional: [run, task, continueOn:Continue, files+]   # files+: one or a list
    rules:
      - valid!: (task != null) != (run != null)
        message: a stage has either task or run
  Continue: [fail, gate]                  # a set of allowed words

$extends makes a file a patch of another one, or of a bundled template (scripted-yaml/state-machine, scripted-yaml/navigation-ui, scripted-yaml/forms):

$extends: ./web-testing.yml

stages:
  $before:                                # new items at the start ($after: at the end)
    lint:
      title: Lint
  explore:
    $replace:                             # overwrite fields of one item
      when!: base and vars.CI != null     # `base` is the value it replaces
  $remove: [results]

The full reference is SPEC.md, section 4.

The Rust API

Libraries, files and markers

use scrusted_yaml::{MarkerOutput, MemoryFiles, ScrustedYaml, Value};

let scrusted = ScrustedYaml::builder()
    .files(MemoryFiles::from_pairs([("jobs.yml", "deploy!sh: ./deploy.sh\nready!: deploy\n")]))
    // `key!sh:` hands its value to this function; what it returns becomes the value
    .marker("sh", |source: &Value| Ok(MarkerOutput::Value(Value::Bool(source.to_text().ends_with(".sh")))))
    .strict(true) // warnings are errors
    .build()?;

assert!(scrusted.validate("jobs.yml").is_empty());
# Ok::<(), Box<dyn std::error::Error>>(())
  • DiskFiles::new("rules/") reads a folder (paths cannot leave it), MemoryFiles holds texts, and any impl Files (a database, an object store) works too.
  • A marker function may return a MarkerOutput::Host(Arc<dyn HostValue>) instead: the value is kept as it is, and HostValue::read runs only when a formula reads the key. In a typed result, a Marked<T> field gets it back.
  • .computed_marker(name, f) computes {{ }} and formulas inside the value first. .marker_names([...]) registers names only, for a validator.

Validating

# use scrusted_yaml::ScrustedYaml;
let scrusted = ScrustedYaml::builder().build()?;
let problems = scrusted.validate_text("total!: price * qty\nprice: 4\n", "cart.yml");
assert_eq!(problems[0].to_string(), "cart.yml:1  total!  unknown name \"qty\"; for text, remove the \"!\"");
# Ok::<(), Box<dyn std::error::Error>>(())

Each Problem has file, line, column, key, message and severity. Validation runs no marker and computes no formula.

Resolving

use scrusted_yaml::{Functions, HostError, ResolveOptions, ScrustedYaml, Vars, vars};

let scrusted = ScrustedYaml::builder().build()?;
let document = scrusted.load_text(
    "$vars:\n  user: {}\n$functions:\n  greeting(name):\nhello!: greeting(vars.user.name)\n",
    "hello.yml",
)?;

let options = ResolveOptions::default()
    .functions(Functions::new().add("greeting", |name: String| -> Result<String, HostError> { Ok(format!("Hi, {name}")) }));

// variables from vars! or from any Serialize
#[derive(serde::Serialize)]
struct User { name: String }
let vars = Vars::from_serialize(&serde_json::json!({ "user": User { name: "Ada".into() } }))?;

let value = document.resolve(&vars, &options)?;
assert_eq!(value.as_map().unwrap()["hello"].as_str(), Some("Hi, Ada"));

// all missing variables are reported at once, before anything is computed
let error = document.resolve(&vars! {}, &options).unwrap_err();
assert!(error.message().contains("missing required variable"));
# Ok::<(), Box<dyn std::error::Error>>(())
  • resolve gives a Value; resolve_as::<T> gives any serde::Deserialize type. A node with $value keeps it under the key $value: map it with #[serde(rename = "$value")].
  • ResolveOptions also holds strict_nulls (every silent null is an error, for authorization files), clock (what now() and today() read) and limits (steps, depth, sizes and time per resolve; Limits::none() for tests).
  • A failure (ResolveError) names the file, the key and why.
  • document.test(&options) runs the file's $tests; document.merged_text() gives a patch with its base applied, as one file.
  • Documents are immutable, cheap to clone, and many threads resolve one at once.

Numbers are decimals: 0.1 + 0.2 = 0.3 is true.

The command line

scrusted-yaml validate rules/*.yml --markers sh      # problems; exit code 1 on an error
scrusted-yaml test rules/*.yml                       # pass / FAIL per $tests entry
scrusted-yaml resolve rules/rate-limits.yml --vars vars.yml --json
scrusted-yaml resolve rules/rate-limits.yml --var plan=pro
scrusted-yaml merged rules/smoke.yml                 # a patch with its base applied
scrusted-yaml types rules/pipeline.yml > src/pipeline.rs   # Rust structs from $schema
scrusted-yaml templates                              # the bundled templates
scrusted-yaml skill --install                        # the skills for coding agents (below)

--markers names the markers the files use; --computed the computed ones; --strict makes warnings errors. The output and exit codes are scripted-yaml's, so editors and CI read both.

Skills for coding agents

The command line carries three skills that teach a coding agent (Claude Code, Codex, OpenCode) to work with rule files:

Skill For
scrusted-yaml writing and checking rule files: formulas, $vars, $schema, $tests, $extends, the mistakes the validator refuses, and reading a file into a Rust struct
scrusted-yaml-convert moving a match or an if chain out of Rust into a rule file, typing the result, serving it live, and proving with a test that nothing changed
scrusted-yaml-ui building an admin page that edits the rules on the running server: save through the live checks, show why a change was refused, roll back
scrusted-yaml skill                    # print the skills
scrusted-yaml skill --install          # install into .claude/skills and .agents/skills of this project
scrusted-yaml skill --install global   # install into your home directory

Every example a skill quotes is a file beside it, validated and tested with the crate.

Differences from scripted-yaml

A file both libraries accept gives the same result in both, except:

  • Numbers are decimals, not binary doubles.
  • The forms in the table under "Formulas" are refused at validation.
  • A formula computes only the if branch it takes.
  • A missing map key gives null without an error (strict_nulls makes it one).
  • A YAML tag (ok!: !x) is an error, not dropped.
  • $import takes .yml and .yaml files only. A function comes from $functions, passed by the application; a Markdown file is read by the application and passed as a variable.
  • Evaluation has limits.

Each case is in conformance/differs/ with both answers; SPEC.md section 2.3 and its "Implementation notes" explain why.

Contributing

cargo test --workspace --all-features
cargo clippy --workspace --all-targets --all-features -- -D warnings
cargo fmt --check

SPEC.md is the specification and CLAUDE.md the working rules. The conformance suite is regenerated from scripted-yaml with bun: sh tools/fetch-reference.sh, then bun tools/conformance/generate.ts (see conformance/README.md).

License: MIT.