Control Flow

Conditional and logical operators for controlling execution flow.

Keywords

  • if - Logical condition
  • when - Temporal/state condition
  • while - Loop condition
  • for - Iteration
  • in - Collection membership
  • of - Collection iteration
  • and - Logical AND
  • or - Logical OR
  • not - Logical NOT

Conditional Keywords

if - Logical Condition

Used for logical conditions in agent capabilities.

Usage

agent ConditionalAgent {
    can process if valid
    can approve if criteria_met
    must reject if policy_violated
    cannot proceed if unauthorized
}
✨ Edit in Studio

Multiple Conditions

agent SmartAgent {
    can execute if authorized and validated
    can approve if criteria_met or override_enabled
    cannot proceed if not ready
}
✨ Edit in Studio

when - Temporal/State Condition

Used for state-based or temporal conditions.

Usage

agent StateAgent {
    can process when ready
    must validate when receiving_input
    can notify when completed
    should cleanup when finished
}
✨ Edit in Studio

State Transitions

workflow OrderFlow {
    state pending -> processing
    state processing -> completed
}

agent OrderAgent {
    can accept when pending
    can process when validated
    must notify when completed
}
✨ Edit in Studio

if vs when

KeywordUse CaseExample
ifLogical conditionsif valid, if authorized
whenState/temporal conditionswhen ready, when completed
agent ExampleAgent {
    # Logical condition - checks a boolean value
    can approve if criteria_met
    
    # State condition - checks current state
    can process when in_ready_state
    
    # Combined
    can execute when ready and if authorized
}
✨ Edit in Studio

Loop Keywords

while - Loop Condition

Express looping behavior (primarily declarative).

agent LoopingAgent {
    can retry while attempts_remaining
    should process while items_pending
    must validate while data_available
}
✨ Edit in Studio

for and in - Iteration

Express iteration over collections.

Basic Iteration

agent IteratorAgent {
    can process for each item in collection
    must validate for all records in dataset
    should notify for every user in list
}
✨ Edit in Studio

Collection Processing

agent BatchProcessor {
    can transform for each document in batch
    must check for all entries in queue
    should aggregate for every value in results
}
✨ Edit in Studio

of - Collection Iteration (Alternative)

Alternative syntax for iteration.

agent CollectionAgent {
    can process each of items
    must validate all of records
    should update any of pending_tasks
}
✨ Edit in Studio

Logical Operators

and - Logical AND

Combine multiple conditions (all must be true).

agent LogicalAgent {
    can execute if authorized and validated
    can proceed when ready and if approved
    must check if valid and if complete
}
✨ Edit in Studio

Multiple AND Conditions

agent MultiConditionAgent {
    can approve if authenticated and authorized and validated
    must reject if expired or invalid or unauthorized
}
✨ Edit in Studio

or - Logical OR

Combine conditions (at least one must be true).

agent AlternativeAgent {
    can proceed if admin or owner
    can approve if manager or supervisor
    should notify if urgent or high_priority
}
✨ Edit in Studio

not - Logical NOT

Negate a condition.

agent NegationAgent {
    can proceed if not blocked
    cannot execute if not authorized
    should warn if not validated
}
✨ Edit in Studio

Combined with AND/OR

agent ComplexAgent {
    can execute if authorized and not suspended
    can approve if valid or not strict_mode
    must reject if not authenticated and not public_access
}
✨ Edit in Studio

Complex Conditions

Multiple Operators

agent ComplexConditionAgent {
    # AND + OR
    can approve if (admin or manager) and validated
    
    # NOT + AND
    can execute if authorized and not suspended
    
    # Complex combination
    can proceed if (authenticated and validated) or (admin and not restricted)
}
✨ Edit in Studio

Nested Conditions

agent NestedAgent {
    can process if valid and (
        (premium_user and feature_enabled) or
        (admin and override_mode)
    )
}
✨ Edit in Studio

Real-World Examples

Access Control

agent AccessController {
    # Simple conditions
    can view if authenticated
    can edit if owner
    can delete if admin
    
    # Combined conditions
    can moderate if admin or moderator
    can publish if editor and approved
    
    # Negation
    cannot access if suspended
    cannot modify if locked or archived
    
    # Complex logic
    can approve if (
        (manager and department_match) or
        (admin and not restricted)
    ) and not suspended
}
✨ Edit in Studio

Order Processing

agent OrderProcessor {
    # State conditions
    can accept when pending
    can validate when received
    can process when validated
    
    # Logical conditions
    can ship if payment_completed and stock_available
    can cancel if not shipped
    
    # Combined
    can refund when delivered and if within_refund_period
    cannot refund if damaged or used
    
    # Complex business logic
    can express_ship if (
        premium_customer or express_selected
    ) and stock_available and not restricted_item
}
✨ Edit in Studio

Content Moderation

agent ContentModerator {
    # Auto-approval logic
    can auto_approve if (
        trusted_user and
        not flagged and
        content_score_high
    )
    
    # Auto-rejection logic
    must auto_reject if (
        contains_prohibited_words or
        spam_detected or
        duplicate_content
    )
    
    # Escalation logic
    should escalate if (
        not clearly_safe and not clearly_unsafe
    ) or (
        flagged_by_users and flag_count_high
    )
    
    # Special handling
    can bypass_check if admin and emergency_mode
    cannot publish if not reviewed or flagged
}
✨ Edit in Studio

Workflow Automation

agent WorkflowAutomation {
    # Iteration
    can process for each task in queue
    must validate for all items in batch
    
    # Looping
    can retry while attempts_remaining and not succeeded
    should backoff while rate_limited
    
    # State-based
    can advance when prerequisites_met
    must checkpoint when phase_complete
    
    # Conditional routing
    can route_to_fast_track if (
        simple_case and auto_approved
    ) or priority_customer
    
    can route_to_manual_review if (
        complex_case or flagged
    ) and not auto_processable
}
✨ Edit in Studio

Best Practices

Condition Clarity

  1. Use descriptive condition names

    • Good: if payment_verified
    • Avoid: if check1
  2. Break complex conditions into parts

    agent WellStructured {
        # Instead of complex nested conditions
        can approve if eligible
        can approve if override_enabled
        
        # Where eligible = authenticated and validated and not_suspended
    }
    
    ✨ Edit in Studio
  3. Use appropriate keywords

    • if for logic: if valid, if authorized
    • when for state: when ready, when completed

Combining Conditions

Precedence

Spectral follows standard logical precedence:

  1. not (highest)
  2. and
  3. or (lowest)
# This:
can execute if not blocked and ready or override

# Is equivalent to:
can execute if ((not blocked) and ready) or override

# For clarity, use explicit grouping:
can execute if (not blocked and ready) or override
✨ Edit in Studio

Pattern Examples

Guard Conditions

agent GuardedAgent {
    # Prevent execution
    cannot proceed if not initialized
    cannot execute if suspended or locked
    
    # Allow only when ready
    can process when initialized and if configured
}
✨ Edit in Studio

Fallback Logic

agent FallbackAgent {
    can use_primary_method if available
    can use_backup_method if primary_failed or not available
    can use_emergency_fallback if all_methods_failed
}
✨ Edit in Studio

Progressive Enhancement

agent ProgressiveAgent {
    # Basic functionality
    can basic_process if authenticated
    
    # Enhanced functionality
    can advanced_process if premium_user
    
    # Full functionality
    can full_featured_process if enterprise_user and feature_enabled
}
✨ Edit in Studio

Conditional Syntax Summary

PatternExampleUse Case
Simple ifif validSingle logical condition
Simple whenwhen readySingle state condition
andif a and bAll conditions must be true
orif a or bAny condition must be true
notif not aNegate condition
Complexif (a and b) or (c and not d)Multiple combined conditions
Loopwhile conditionRepeated execution
Iterationfor each item in listCollection processing

Related Keywords


Next Steps