Download all docs
apps

Condition

The if/else fork of a Triform automation: it evaluates a CEL expression against the flow context and routes execution down a then or else branch, synchronously and with no I/O, so every decision point in a flow is one small, predictable step.

Working with it

Selecting a Condition reveals its settings in the properties panel; it has no dedicated full-screen workbench.

How it appears

The same element type rendered as a definition, a circle instance, and a live workspace card.

If
type

Condition

Branch automation based on conditions (if/else)

appsatomdefinition

When to use / not

When to use

  • Branching a flow on a boolean check — route to a different downstream element when input.status == 'success' or input.score >= 75.
  • Multi-way routing where the first matching case wins — fan an order or a user into high-value / standard / fallback handlers via the branches array plus a default_branch.
  • Gating an expensive step behind a cheap, synchronous predicate so the rest of the flow only runs when a condition holds.

When not to use

  • Repeating a step over a collection or until a predicate flips — that is loop, not a one-shot branch.
  • Pausing the flow for a delay, a schedule, or an external signal before continuing — use wait.
  • Deriving the decision itself requires an API call, a database lookup, or multi-step computation — compute that in a python (or other action) element first and let condition evaluate its boolean output; CEL expressions are simple comparisons only.

Topology

Lives nested inside a parent element rather than standing alone — it is created in the context of its container.

Properties

expressionstringrequired
CEL expression to evaluate
modestring
Evaluation mode

Capabilities

Defined for this element
  • Evaluate
  • Observe

Operations

  • activityGET
  • attachmentsGET
  • batch_statsGET
  • branchesGET
  • composePOST
  • contextGET
  • createPOST
  • deleteDELETE
  • disablePOST
  • enablePOST
  • evaluatePOST
  • export_bundleGET
  • getGET
  • import_bundlePOST
  • intentionGET
  • promotePOST
  • readmeGET
  • readme_updatePOST
  • remove-modifierPOST
  • restorePOST
  • schemaGET
  • sourceGET
  • source_branchesGET
  • source_promotePOST
  • source_repairPOST
  • source_statusGET
  • source_validatePOST
  • statsGET
  • treeGET
  • updatePATCH
  • update_metaPATCH
  • validatePOST
  • versionGET

Ports

Inputs

  • inputrequest
  • resultrequest

Composition

Uses
Referenced by

Errors / when it fails

All branches must have a target element specified
Fails unless: all(branch.target != '' for branch in branches)
Consider defining default_branch for unmatched conditions

Validation rules

  • all_matches mode with many branches may cause fan-out complexity
  • Condition with 'true' expression and no branches may be unnecessary

Condition (condition)

Category: apps | Form: | Symbol: If

Branch automation based on conditions (if/else)

Evaluates CEL-subset expressions for automation branching. Set spec.expression for the main condition (e.g., input.score >= 70). Supports: comparison (==, !=, <, <=, >, >=), logical (&&, ||, !), field access (input.foo.bar), literals (strings, numbers, booleans, null). Context is passed via evaluate operation’s context field — the entire input is used if no context key provided. Define spec.branches as array of {condition, label} for multi-branch routing. Set spec.default_branch for fallback. Mode: first_match (default) stops at first true branch. Empty expression evaluates to true. Missing fields resolve to null (falsy). Use validate operation to check expression syntax before saving. Common mistake: using full CEL features (macros, has()) that aren’t supported — stick to comparison and logical operators.

Guide

Branch flow based on conditions (if/else)

What It Does

Condition evaluates a CEL (Common Expression Language) expression against the current flow context and routes execution to one of two branches based on the boolean result. It is the if/else primitive of the actor layer — every decision point in a flow passes through a condition element. Evaluation is synchronous and lightweight with no external I/O, making it suitable as a high-frequency routing step.

Element Definition

PropertyValue
Typecondition
Categoryapps
Formatom
Symbolfork_right / #F59E0B

Properties

FieldTypeDefaultDescription
expressionstringtruePrimary CEL expression to evaluate (required)
modestring (enum)first_matchEvaluation mode: first_match (stop at first true branch) or all_matches (evaluate all)
branchesarrayConditional branches (if/else-if). Each item: condition (CEL), target (element ref), label
default_branchstringTarget element reference for the else/fallthrough case
timeout_msinteger5000Evaluation timeout in milliseconds

Ports

DirectionPortTypeRequiredDescription
InputinputrequestYesCEL expression and context to evaluate
OutputresultrequestYesEvaluation result with boolean result and branch selection (then or else)

Topology

  • Lives in: apps/automation/condition/ repository
  • Referenced by: projects
  • Accepts modifiers: requirements
  • Uses resources: variable

Capabilities

CapabilityDescription
cel-evaluationCommon Expression Language support
branchingIf/else flow control
context-accessAccess flow context in expressions

Error Codes

CodeClassRetryableDescription
CONDITION_INVALID_EXPRESSIONvalidationNoCEL expression is invalid
CONDITION_EVALUATION_FAILEDinternalNoExpression evaluation failed at runtime

Quick Start

Creating via API

Create a condition element inside a project:

POST /api/{circle}/{project}/
Content-Type: application/json

{
  "element_type": "condition",
  "slug": "check-premium",
  "name": "Check Premium User",
  "spec": {
    "expression": "input.user.tier == 'premium'",
    "mode": "first_match"
  }
}

Basic Usage

Invoke the condition with a CEL expression and context:

POST /api/{circle}/{project}/check-premium/ops/invoke
Content-Type: application/json

{
  "expression": "input.score >= 75",
  "context": {
    "score": 82
  }
}

Response:

{
  "result": true,
  "branch": "then",
  "evaluated_value": true
}

Project Patterns

How Condition Fits Into Projects

Condition is always an intermediate element in a project — it receives the output of a previous step, evaluates it, and routes to different downstream elements based on the result. The result.branch field ("then" or "else") is what downstream elements check to determine whether they should run. In development stage, conditions evaluate immediately with no caching. In demo and live stages, they behave identically since they perform no I/O.

Multi-branch routing uses the branches array: each entry specifies a CEL expression and a target element. The first matching branch wins (in first_match mode) and default_branch acts as the fallthrough else.

Example Project Spec

# Route orders to different handlers based on value
elements:
  - element_type: condition
    slug: order-routing
    spec:
      expression: "input.order_total > 1000"
      mode: first_match
      branches:
        - condition: "input.order_total > 10000"
          target: "high-value-handler"
          label: "High value"
        - condition: "input.order_total > 1000"
          target: "standard-handler"
          label: "Standard"
      default_branch: "low-value-handler"

Common Patterns

Payment Validation Gate

A condition that gates processing on a valid payment response:

POST /api/{circle}/{project}/

{
  "element_type": "condition",
  "slug": "payment-valid",
  "spec": {
    "expression": "input.status == 'success' && input.amount > 0"
  }
}

Wire the result output to a function element. In the downstream function, check that it was called only when branch == "then".

Multi-Tier Access Control

Use multiple branches to route users to different frontend:

POST /api/{circle}/{project}/

{
  "element_type": "condition",
  "slug": "access-tier",
  "spec": {
    "mode": "first_match",
    "branches": [
      {
        "condition": "input.user.role == 'admin'",
        "target": "admin-dashboard",
        "label": "Admin"
      },
      {
        "condition": "input.user.subscription == 'pro'",
        "target": "pro-dashboard",
        "label": "Pro"
      }
    ],
    "default_branch": "free-dashboard"
  }
}

Applying Modifiers

ModifierUse case
requirementsRequire that specific variable resources are present before the condition evaluates

Common Mistakes

Using template syntax instead of CEL. The condition element uses CEL, not Jinja-style {{ }} templates. Write input.count > 10 not {{ inputs.count > 10 }}.

Forgetting to set default_branch. If all branches evaluate to false and no default_branch is set, the condition result has no target to route to. Always set a fallthrough branch unless flow termination on no-match is intentional.

Using mode: all_matches when you expect exclusive routing. In all_matches mode, multiple branches can activate simultaneously. For exclusive if/else-if/else routing, use first_match (the default).

Putting complex business logic in expressions. CEL expressions should be simple comparisons. If the routing logic requires API calls, database lookups, or multi-step computation, put that logic in a function element first and let the condition evaluate the function’s boolean output.

Relationships

  • Uses: variable

Capabilities

  • cel-evaluation: Common Expression Language support
  • branching: If/else automation control
  • context-access: Access automation context in expressions

Properties

PropertyTypeDefaultDescription
expressionstring"true"CEL expression to evaluate
modestring"first_match"Evaluation mode
branchesarrayConditional branches evaluated in order (first match wins in first_match mode)
default_branchstringTarget element slug/path for the else case — executed when no branch matches
timeout_msinteger5000Maximum time for CEL expression evaluation in milliseconds

Operations

activity

Get /ops/activity | Auth: Read

Get activity events for this element

Scope depends on element capabilities: individual elements query by element_id, project-form elements with activity-scope-members include member activities, circle-level elements with activity-scope-all query the entire circle. Gracefully returns empty list if activities table is missing (old circles).

attachments

Get /ops/attachments | Auth: Read

List all modifiers and resources attached to this element

Returns both modifiers (policy enforcement) and resources (data injection) with is_modifier flag to distinguish. Items in the generated MODIFIER_TYPES list are modifiers; everything else is a resource. Includes cascade_policy and version pin info.

batch_stats

Get /ops/batch_stats | Auth: Read

Get per-element statistics for all children of this element

Returns per-child stats plus an aggregate. Most meaningful on compound or manifest form elements (repositories, circles, projects); atoms have no children so the result is an empty children array with a zeroed aggregate. Uses efficient GROUP BY SQL. Weighted averages for eval scores.

branches

Get /ops/branches | Auth: Read

List defined branches and their conditions

Read-only: returns the branches array and default_branch from the element’s spec. No input required.

compose

Post /ops/compose | Auth: Execute

Batch add and remove modifiers on this element in a single call

Declarative composition: add modifiers by ref path (slug or path@version) and remove by attachment ID, all in one atomic call on the target element. Each ‘add’ entry resolves the source element, validates topology, attaches with optional priority and cascade policy. Each ‘remove’ entry deletes the attachment row. Returns a summary of what was added and removed. Example: compose({ add: [{ref: “my-prompt”}, {ref: “rate-limit/api@v2”, priority: 50}], remove: [{attachment_id: “uuid”}] })

context

Get /ops/context | Auth: Read

Get connected elements (graph traversal)

Graph traversal showing all connected elements with their relationship type (contains, contained_by, references, referenced_by, attaches, etc.). Use ?depth=N to control traversal depth (default 1) and ?types=actor,data to filter by element types.

create

Post /ops/create | Auth: Write

Create child element

POST to the parent path — element_type goes in the request body, NOT the URL. Both element_type and slug are required and must be non-empty. Name is derived from slug if omitted. Writes to both Git and PostgreSQL. All elements are stored flat under the circle — no intermediate library wrapper rows.

delete

Delete /ops/delete | Auth: Admin

Delete element (soft delete)

Soft delete — sets state to ‘deleted’ but retains the record. Cannot delete elements that have children (has_no_bond precondition) or active runs. Requires admin auth and confirmation.

disable

Post /ops/disable | Auth: Admin

Disable element (hides and prevents use)

Idempotent — safe to call on already-disabled elements. Optionally pass a reason string. Disabled elements cannot be invoked or executed. Inverse of enable.

enable

Post /ops/enable | Auth: Admin

Enable element (makes usable and visible)

Idempotent — safe to call on already-enabled elements. Transitions element to ready/enabled state. Cannot enable deleted elements. Inverse of disable.

evaluate

Post /ops/evaluate | Auth: Execute

Evaluate condition expression against context

Evaluate the element’s CEL expression against provided context. Pass context object (or entire input is used as context). Returns result (boolean), matched_branch (if branches defined), and evaluation_path showing each sub-expression result. Empty expressions evaluate to true.

export_bundle

Get /ops/export/bundle | Auth: Read

Export element as downloadable git bundle

On non-root-namespace elements, returns a binary git bundle. On root-namespace (circle) elements, dispatch hands off to the circle’s own export_bundle op, which returns a multi-element JSON envelope with one base64 bundle per child element — this is intentional, not an error.

get

Get /ops/get | Auth: Read

Get element details

Element is already resolved by the routing layer — this returns the cached element, not a fresh DB query. Use the path /api/{circle}/{slug} to address elements.

import_bundle

Post /ops/import/bundle | Auth: Write

Import git bundle into element

Accepts a base64-encoded git bundle in the JSON bundle_base64 field. Use overwrite=true to replace existing elements with same slug (default skips duplicates). Imported elements get new UUIDs. Returns counts of imported/skipped elements and any errors.

intention

Get /ops/intention | Auth: Read

Get element intention with full inheritance chain

Returns three levels: direct (this element’s intention), inherited (from category and root), and resolved (final merged intention). Useful for understanding an element’s purpose in context of its hierarchy.

promote

Post /ops/promote | Auth: Admin

Promote element configuration to a target environment

Only for manifest-form elements (projects). Environments advance: dev → demo → live. dev→demo requires member+ role, demo→live requires admin. Freezes member versions at promotion time (creates snapshot). Persists environment config to spec.environments.

readme

Get /ops/readme | Auth: Read

Get element README.md content

Reads README.md from the element’s git repository. Returns empty content (not an error) if no README exists. Always returns markdown format.

readme_update

Post /ops/readme_update | Auth: Write

Update element README.md content

Creates or overwrites README.md in the element’s git repo. Commits to the draft branch. Content must be provided as a markdown string.

remove-modifier

Post /ops/remove-modifier | Auth: Execute

Remove an attached modifier from this element by attachment ID

Removes a modifier/resource attachment by its row ID. The ID comes from the attachments or context API. This is the reverse of attach — called on the target element, not the source.

restore

Post /ops/restore | Auth: Admin

Restore element to a specific version

Automatically snapshots the current state before restoring (creates a ‘Before restore to vN’ version entry). Writes restored spec to git as .triform/spec.yaml. Git failures warn but don’t fail the operation — DB state is authoritative. Cannot restore deleted elements.

schema

Get /ops/schema | Auth: Read

Get element input/output schema (MCP tools/list compatible)

Returns type-level port schemas from the TypeRegistry — not instance-specific overrides. Includes direction (input/output), required flag, and JSON schema per port. Useful for understanding what data an element accepts and produces.

source

Get /ops/source | Auth: Read

Get any file’s content from the element’s git repository

Reads an arbitrary file from the element’s CAS-backed git tree by its relative path. Same store as readme, just generalized. Path safety: rejects .. traversal, leading /, and null bytes. Use this to view main.py for action elements, asset files for SPAs, etc. Returns empty content (not an error) if the file doesn’t exist.

source_branches

Get /ops/source/branches | Auth: Read

List Source branches for this element

Returns the standard draft/demo/live Source branches, their current commits, and promotion relationships. Use GET /api/{element_path}/ops/source/branches.

source_promote

Post /ops/source/promote | Auth: Write

Promote Source branch forward

Promotes draft to demo or demo to live through the generated element op path. Direct Git pushes to demo/live are blocked by Source policy.

source_repair

Post /ops/source/repair | Auth: Write

Inspect or repair the element Source index

Runs Source repair through the element operation path. Defaults to dry_run=true; set dry_run=false only after reviewing a dry-run report.

source_status

Get /ops/source/status | Auth: Read

Get Source control status for this element

Returns the branch-aware clone URL, checkout commands, current draft commit, child source-link count, portable export summary, Source health, warnings, and auth hints for the addressed element. Use the element-first path: GET /api/{element_path}/ops/source/status.

source_validate

Post /ops/source/validate | Auth: Read

Validate Source branch contents

Validates a Source branch before accepting local Git workflow changes or promotion. Defaults to branch=draft and rejects runtime data, generated output, secret material, and unreadable CAS refs.

stats

Get /ops/stats | Auth: Read

Get aggregate statistics for this element

Health status is computed: error if errors_per_day > 5 or success_rate < 0.8, warning if errors_per_day > 0 or success_rate < 0.95. Firing alerts escalate health to error/warning. Default period is ‘day’. Returns runs_per_day, success_rate, avg_duration_ms, and more.

tree

Get /ops/tree | Auth: Read

Get the element’s position in the graph — ancestors, children, references, and subtree statistics

Uses per-circle ElementGraph cache for O(1) lookups. Returns ancestors (containment chain), children (direct), members (references), referenced_by (reverse refs), attachments, and subtree stats. Default depth is 3, max is 10. Pass ?include_metadata=true for name/state on each node.

update

Patch /ops/update | Auth: Write

Update element

Partial update — send only the fields you want to change. spec, name, and intention are all independently optional. spec MUST be a JSON object when present; deep-merged into the existing spec by default. Empty {"spec":{}} preserves existing spec content but still records a new version (no-op for content, not for version state). To clear/replace the entire spec wholesale send {"spec":{...},"deep":false}. List-typed spec fields use replace semantics (the patch list replaces the existing list, no array merging). Coordinates Git + DB writes. Slug cannot be changed after creation.

update_meta

Patch /ops/update_meta | Auth: Write

Update element metadata (lightweight merge — does NOT bump version or snapshot spec)

Shallow JSONB merge into element.meta. Top-level keys in the provided value replace existing meta values; other keys are preserved. Used for UI metadata like canvas positions, panel state, viewer preferences. Wire-shape op_name is update_meta (distinct from update) so SSE subscribers + the cache auto-invalidator can distinguish lightweight metadata changes from spec edits without inspecting the payload. The MutatingElementStore wrapper stamps this op_name on the lifecycle event emitted by update_element_meta storage calls.

validate

Post /ops/validate | Auth: Read

Validate condition expression syntax

Syntax-check a CEL expression without executing it. Pass expression string. Returns valid (boolean) and errors array. Catches unbalanced parentheses, invalid operators, and structural issues. Use this before saving expressions to spec.

version

Get /ops/version | Auth: Read

Get current version or full history

Returns current version by default. Pass ?history=true for full version history (up to ?limit=N, default 50). Versions are backed by the element_versions table. Every spec update creates a new version entry.

Error Codes

CodeClassRetryableDescription
CONDITION_INVALID_EXPRESSIONvalidationnoCEL expression is invalid
CONDITION_EVALUATION_FAILEDinternalnoExpression evaluation failed

Lifecycle / runtime

Defined for this element

Before invoke

  • validate_input
  • check_rate_limit

After invoke

  • record_metrics
  • emit_traces

On error

  • log_error
  • record_error_metric

Observability

Defined for this element

Metrics

  • evaluation_count
  • duration_ms
  • error_rate

Events

  • condition.completed
  • condition.failed

Pricing / cost

Platform default

Operation costs

  • create: free
  • update: free
  • delete: free
  • get: free
  • list: free
  • invoke: 10000 micro-AU
  • tool_use: free