SSyncropel Docs

CEL Expressions

Write rules and conditions in one expression language. The same syntax works for triggers, routing, task preconditions, status rules, health checks, approval policies, permissions, and fan-out joins.

Overview

Syncropel uses CEL (Common Expression Language) for every condition you write: event triggers, routing rules, task preconditions, task status rules, health checks, approval policies (the aitl context), and permissions. You write the condition once and it works the same way everywhere.

CEL is Google's safe, type-checked expression language, also used by Kubernetes, gRPC and Envoy. Syncropel adds functions for records, tasks, threads, trust, and system state.

Quick Start

Validate an expression without running it:

spl expr check 'record.act == "KNOW" && record.body.verdict == "accept"' --context trigger

Evaluate an expression against your workspace's current state:

spl expr eval 'system.uptime_secs > 3600' --context health_check

Both commands report compile errors at the exact character position, so you can fix the syntax before you use the expression.

The eight contexts

Each place you use an expression has its own context, which decides which names you can use. You choose the context with --context on the command line. A trigger expression that uses tasks fails to compile, because tasks isn't available in the trigger context.

ContextUsed ForPrimary Bindings
triggerEvent triggers matching incoming recordsrecord, records, system, task(), trust(), thread(), now(), current_actor()
routingRouting rulesrecord, thread(), system, trust(), task(), now(), current_actor(), fanout_status()
preconditionTask readiness gatingrecords, tasks, task(), trust(), thread(), now(), system, current_actor()
fold_ruleWorking out a task's statusrecords (the task thread), task, thread(), now(), current_actor()
health_checkspl health check predicatessystem, tasks, trust(), now(), current_actor(), fleet_instances_live()
aitlDeciding what to do with an AI proposalrecord, proposal_confidence, meta_trust, system, now(), current_actor()
permissionAllowing or denying requestsrecord, current_actor(), resource, trust(), task(), system, now(), fleet_frozen_namespaces() / fleet_emergency_active()
joinFan-out: when is the parent intent satisfied?children, parent, now()

Standard Library Reference

record

A single Syncropel record (available in trigger, routing, aitl, permission contexts):

record.act          // string: "KNOW", "DO", "INTEND", "LEARN", etc.
record.actor        // string: actor DID
record.thread       // string: thread ID
record.body         // map: the payload, access as record.body.topic, record.body.domain, etc.
record.body.topic   // dot-access works for any body field
record.clock        // int: logical timestamp
record.data_type    // string: "SCALAR", "FORMULA", etc.
record.parents      // list<string>: parent record IDs

records

A list of records (available in the trigger, precondition and fold_rule contexts; fold_rule is the context for rules that work out a task's status from its records). Use CEL's built-in macros:

records.exists(r, r.act == "KNOW" && r.body.topic == "feature_enabled")
records.filter(r, r.actor.startsWith("did:sync:agent:")).size()
records.all(r, r.body.reviewed == true)
records.map(r, r.cost_usd).reduce(acc, x, acc + x, 0.0)

task(alias)

Look up a single task by alias:

task("TASK-0163").status        // string: "approved", "blocked", "active", etc.
task("TASK-0163").priority      // string: "critical", "high", etc.
task("TASK-0163").assigned_to   // string: actor DID
task("TASK-0163").age_secs      // int: seconds since creation
task("TASK-0163").cost_usd      // double
task("TASK-0163").exists        // bool: false for unknown aliases

Defensive check: task("TASK-0163").exists && task("TASK-0163").status == "approved".

tasks

List of all known tasks (available in precondition and health_check contexts):

tasks.filter(t, t.status == "blocked").size()
tasks.exists(t, t.priority == "critical" && t.age_secs > 3600)
tasks.all(t, t.cost_usd < 5.0)

thread(id)

Look up a thread by ID:

thread("th_abc...").status          // string
thread("th_abc...").last_clock      // int
thread("th_abc...").record_count    // int
thread("th_abc...").participants    // list<string>: actor DIDs

trust(actor, domain) and trust_count(actor, domain)

The trust score for an actor in a domain, and how many observations it is based on:

trust("did:sync:agent:dev", "code") > 0.5
trust_count("did:sync:agent:dev", "code") >= 10   // require minimum evidence

system

Workspace state (available in most contexts):

system.uptime_secs                             // int
system.records_total                           // int
system.threads_total                           // int
system.daemon_version                          // string: server version
system.active_dispatches                       // list<Dispatch>
system.active_dispatches.all(d, d.duration_secs < d.timeout_secs * 2)
system.today.dispatches                        // int
system.today.cost_usd                          // double
system.today.tasks_completed                   // int

Each Dispatch has: task_alias, actor, duration_secs, cost_usd, timeout_secs, sub_thread.

current_actor(), current_namespace(), and now()

current_actor()                                // string: caller's DID
current_actor().startsWith("did:sync:user:")   // is a user (not agent)
current_namespace()                            // string: current namespace ID
current_namespace().startsWith("acme-corp/")   // scope to all descendants
now()                                          // int: unix seconds

current_namespace() returns the namespace the expression is evaluated for ("default" if none is set). Use .startsWith("parent/") to match everything under a parent namespace. A record's own namespace is record.body.namespace. See namespaces.

proposal_confidence and meta_trust (aitl context only)

For deciding what to do with AI proposals:

proposal_confidence                    // double in [0, 1]
meta_trust.wilson_lb                   // double: the proposer's track record (a conservative score)
meta_trust.total_proposals             // int
meta_trust.accepted                    // int
meta_trust.rejected                    // int

resource (Permission context only)

The resource being accessed, for gating API requests:

resource                               // string: "record_write", "dispatch", "aitl_decide", etc.
resource == "record_delete" && current_actor() == "did:sync:user:admin"

Fleet bindings

These functions work only in the contexts named below.

fleet_frozen_namespaces(): Permission context only. Returns a list<string> of namespace IDs currently under a soft or hard freeze. Used in the default permission rule that denies new INTEND/DO/CALL in frozen namespaces:

!fleet_frozen_namespaces().exists(ns,
  record.body.namespace == ns &&
  (record.act == "INTEND" || record.act == "DO" || record.act == "CALL"))

fleet_hard_frozen_past_grace(): Permission context only. Returns a list<string> of namespaces where a hard freeze is past its grace period. Used in the rule that denies everything at that point:

!fleet_hard_frozen_past_grace().exists(ns, record.body.namespace == ns)

fleet_emergency_active(): Permission context only. Returns bool. True if an emergency stop is active. Paired with an allow-only-reads clause:

!fleet_emergency_active() ||
(record.act == "GET" || record.act == "KNOW" || record.act == "LEARN")

fleet_instances_live(): Health check context only. Returns list<string> of instance DIDs currently live. Useful for health rules like "at least one worker must be reachable":

fleet_instances_live().filter(did, did.contains("worker-")).size() >= 1

fanout_status(thread_id): Routing and Permission contexts. Given a thread ID, returns one of "none", "spawning", "in_progress", "ready_to_join", "done". Useful for routing rules that check whether a parent fan-out has already completed before acting on child records.

children (Join context only)

The results reported so far by a fan-out's child tasks. Available only in the join context, which decides when the parent intent is satisfied.

children                                    // list<ChildResult>
children.size()                              // int: how many reported so far
children.all(c, c.verdict == "accept")       // "all" shorthand
children.exists(c, c.verdict == "accept")    // "any" shorthand
children.filter(c, c.verdict == "accept").size() >= 3   // k-of-n with K=3

Each ChildResult has the fields:

c.index              // int: subtask number (starts at 0, matches its position in body.subtasks)
c.thread             // string: child thread ID
c.worker             // string: worker DID that executed the subtask
c.verdict            // string: "accept" | "reject" | "failed" | "timeout"
c.cost_usd           // double: subtask cost
c.wall_time_secs     // int: elapsed wall-clock seconds
c.summary            // string: from the child's KNOW body

Custom join conditions can combine these:

// All succeed AND total cost is under budget AND no single child cost too much
children.all(c, c.verdict == "accept") &&
children.map(c, c.cost_usd).reduce(acc, x, acc + x, 0.0) < 10.00 &&
children.all(c, c.cost_usd < 5.00)
// K-of-N with at most M failures allowed
children.filter(c, c.verdict == "accept").size() >= 3 &&
children.filter(c, c.verdict == "failed" || c.verdict == "timeout").size() <= 1

The parent binding in the join context is the fan-out parent record itself, available for referencing the original body or metadata:

parent.body.namespace         // the fan-out's declared namespace
parent.body.subtasks.size()   // total subtask count

Common Recipes

Trigger on Task Approval

spl config add-trigger \
  --name on-approval \
  --expression 'record.act == "KNOW" && record.body.verdict == "accept"' \
  --target did:sync:agent:reviewer

Routing Rule by Domain

spl config add-rule \
  --name code-to-dev \
  --expression 'record.act == "INTEND" && record.body.domain == "code"' \
  --target did:sync:agent:dev

Precondition via Expression

spl task add "ship v1.0" \
  --alias REL-0001 \
  --expression 'task("TASK-0163").status == "approved" && task("TASK-0164").status == "approved" && trust("did:sync:agent:dev", "code") > 0.5'

The shortcut --depends-on TASK-0163,TASK-0164 means the same thing, so you can mix both forms.

Health Check for Stuck Dispatches

spl config add-health \
  --name no-stuck-dispatches \
  --severity critical \
  --description "Alert if any dispatch runs past 2x its timeout" \
  --expression 'system.active_dispatches.all(d, d.duration_secs < d.timeout_secs * 2)'

Health Check for Daily Cost Budget

spl config add-health \
  --name daily-cost-budget \
  --severity warn \
  --expression 'system.today.cost_usd < 10.0'

Auto-apply high-confidence proposals

spl config add-decision-policy \
  --name auto-apply-high-confidence \
  --action auto_apply \
  --priority 100 \
  --expression 'proposal_confidence > 0.8 && meta_trust.wilson_lb > 0.7'

Permission: users can approve decisions

spl config add-permission-rule \
  --name users-approve-own \
  --action allow \
  --priority 100 \
  --expression 'current_actor().startsWith("did:sync:user:") && resource == "aitl_decide"'

See Permission enforcement below.

Debugging

Compile Errors

spl expr check reports the exact position:

$ spl expr check 'record.act == "KNO" && record.clock + "x"' --context trigger
✗ compile error: type error: cannot add int and string at column 36

Type errors are caught when the expression is checked, and a rule with invalid CEL is refused when you add it.

Evaluation Errors

Reading a field that is missing from record.body.* gives an error when the expression runs. Check first with has():

has(record.body.priority) && record.body.priority == "critical"

Performance

Expressions are fast. A simple one evaluates in well under a millisecond, and a records.exists over 10,000 records takes under 100 ms. Expressions are cached after the first use. To see how the cache is doing:

curl -s http://localhost:9100/v1/engine/expression_cache/stats | jq

Permission enforcement

Permission rules are off by default. Turn them on explicitly:

# 1. Author an admin allow rule FIRST. It must cover EVERY resource
#    `spl config permissions-disable` touches (otherwise you'll lock
#    yourself out and need permissions-unlock to recover):
#      * record_write: POST /v1/records (the record that turns enforcement off)
#      * thread_read:  GET /v1/threads/.../state (read last_clock first)
#      * config_read:  GET /v1/config/* (so you can list rules)
spl config add-permission-rule \
  --name admin-self \
  --action allow \
  --priority 10000 \
  --expression 'current_actor() == "did:sync:user:YOUR_ADMIN_DID" && (resource == "record_write" || resource == "thread_read" || resource == "config_read")'

# 2. Then author your policy rules
spl config add-permission-rule \
  --name users-read-only \
  --action allow \
  --priority 100 \
  --expression 'current_actor().startsWith("did:sync:user:") && (resource == "thread_read" || resource == "record_read")'

# 3. Finally, enable enforcement. A safety check runs first
#    and refuses if your admin rule doesn't cover all three resources
#    above, preventing the lockout trap before it happens.
spl config permissions-enable

How it works: with enforcement on, rules are checked from highest priority to lowest, and the first match wins. If no rule matches, the request is denied. Every denial is logged. GET /health is always allowed.

Safety check: before turning enforcement on, spl config permissions-enable checks that you could still turn it off. If your rules don't cover record_write, thread_read and config_read for the workspace's own identity, it refuses and prints the add-permission-rule command you need.

Emergency unlock: if you lock yourself out (for example by disabling the admin rule), recover with:

spl stop                          # stop the server first
spl config permissions-unlock     # turns enforcement off
spl serve                         # restart; enforcement is off

permissions-unlock works on the local database directly, so permission rules can't block it. It refuses to run while the server is still up (use --force to override). It works only with the default local database. For a --memory server, just restart.

Older match forms

The simpler match options still work. If you give both an older form and an expression, the expression is used.

WhereSimple formCEL form
Triggers--match "act=KNOW,body.topic=verdict"--expression 'record.act == "KNOW" && record.body.topic == "verdict"'
Routing--domain code --act INTEND--expression 'record.act == "INTEND" && record.body.domain == "code"'
Preconditions--depends-on TASK-0163,TASK-0164--expression 'task("TASK-0163").status == "approved" && task("TASK-0164").status == "approved"'

--depends-on behaves the same as the CEL form, and it is the easiest choice for "all of these tasks approved".

References

On this page