# Alloy Language Specification v3.3

## Table of Contents

1. [Language Overview and Philosophy](#1-language-overview-and-philosophy)
   - [Agent-First Design Philosophy](#11-agent-first-design-philosophy)
   - [Why Agent-First Design Matters](#12-why-agent-first-design-matters)
   - [Language Characteristics](#13-language-characteristics)
2. [Syntax Grammar](#2-syntax-grammar)
   - [Bracket Syntax Rules](#21-bracket-syntax-rules)
3. [Type System](#3-type-system)
4. [Core Primitives](#4-core-primitives)
5. [Multi-Agent Collaboration](#5-multi-agent-collaboration)
6. [Memory Primitives](#6-memory-primitives)
   - [Memory Query Language](#63-memory-query-language)
7. [Meta-Programming Patterns](#7-meta-programming-patterns)
8. [Error Handling](#8-error-handling)
9. [Control Flow and Composition](#9-control-flow-and-composition)
10. [Examples](#10-examples)
11. [Standard Library](#11-standard-library)
   - [Agent-First Standard Library Design](#111-agent-first-standard-library-design)
12. [Runtime Semantics](#12-runtime-semantics)
13. [Implementation Notes](#13-implementation-notes)

---

## 1. Language Overview and Philosophy

### 1.1 Agent-First Design Philosophy

Alloy is a complete general-purpose programming language designed specifically for the age of AI agents. While humans can write Alloy code, the language is fundamentally optimized for AI agents to read, write, generate, and maintain. This agent-first approach influences every aspect of the language design, from syntax to semantics.

Alloy provides all the constructs of a modern programming language - primitive types, tools, control flow, variables, and standard programming patterns - with AI integration as a first-class citizen on top of these foundations. This makes it a complete programming language that happens to have excellent AI integration, rather than just an AI orchestration tool.

**Agent-First Design Principles:**
- **Verbosity Over Brevity**: Agents prefer explicit, descriptive code over terse shortcuts
- **Natural Language Patterns**: Syntax follows natural language conventions that agents understand intuitively
- **Self-Documenting Code**: Code should read like documentation, with clear intent at every level
- **Complete Error Handling**: Agents excel at comprehensive error handling patterns
- **Explicit Over Implicit**: Clear, obvious behavior over clever language features
- **Infinite Typing Speed**: Since agents don't tire from typing, verbosity is a feature, not a burden

### 1.2 Core Design Philosophy

Alloy is a complete general-purpose programming language that treats artificial intelligence as a first-class citizen alongside traditional deterministic computation. The language provides all the capabilities of modern programming languages - variables, tools, control flow, data structures, and error handling - with AI integration seamlessly woven into the fabric of the language.

**Foundational Principles:**
- **Complete Programming Language**: Full support for all programming paradigms and patterns
- **AI as Infrastructure**: AI models are treated as computational primitives, similar to tools or objects
- **Natural Composition**: AI agents, data structures, and deterministic tools compose naturally
- **Maximum Readability**: Code reads like well-structured English documentation
- **Error Transparency**: AI uncertainty and failures are handled explicitly through the type system
- **Agent Productivity**: Every language feature is evaluated for agent generation and maintenance ease
- **Hybrid Computation**: Seamless integration of deterministic logic with AI reasoning

### 1.2 Why Agent-First Design Matters

AI agents are fundamentally different from human programmers in ways that should influence language design:

**Agent Advantages:**
- **Infinite Patience**: Agents don't get tired of verbose, explicit code
- **Perfect Memory**: Agents can handle complex, consistent naming schemes
- **Natural Language Processing**: Agents excel at code that reads like documentation
- **Error Completeness**: Agents naturally write comprehensive error handling
- **Consistency**: Agents maintain perfect naming and style consistency
- **Pattern Recognition**: Agents identify and follow consistent code patterns effortlessly
- **Documentation Generation**: Agents naturally create self-documenting code

**How Agents Write Code Differently:**

```alloy
// Agents naturally write this (explicit, self-documenting)
user_authentication_result, authentication_error = authentication_service ValidateUserCredentials provided_credentials
when authentication_error exists then {
    log_authentication_failure(authentication_error)
    redirect_user_to_login_page()
    return
}

// Instead of this (terse, requires human context)
auth = svc.validate(creds) || login()
```

**Agent Code Generation Patterns:**
- **Complete Error Handling**: Agents naturally consider all error cases
- **Descriptive Naming**: Agents use full, meaningful identifiers without fatigue
- **Explicit Flow Control**: Agents prefer clear, obvious control structures using `when` over `if` for natural language flow
- **Comprehensive Logging**: Agents include detailed logging and monitoring
- **Input Validation**: Agents systematically validate all inputs
- **Natural Language Conditionals**: Agents generate `when...then...otherwise` constructs that read like natural English rather than terse programming syntax

**Benefits for Both Agents and Humans:**

*For Agents:*
- **Natural Generation**: Code patterns match agent reasoning processes
- **Easier Maintenance**: Verbose code is easier for agents to modify correctly
- **Better Error Recovery**: Explicit error handling enables sophisticated recovery
- **Improved Accuracy**: Self-documenting code reduces generation errors

*For Humans:*
- **Immediate Comprehension**: Code intent is clear without additional documentation
- **Reduced Context Switching**: Variable names carry full semantic meaning
- **Self-Reviewing Code**: Logic errors become obvious from naming and structure
- **Maintenance Friendly**: Changes are safer when intent is completely explicit
- **Onboarding Speed**: New team members understand code faster

*For Teams:*
- **Consistent Style**: Agent-generated code maintains perfect consistency
- **Living Documentation**: Code serves as always-up-to-date documentation
- **Reduced Code Review Time**: Intent is clear, reducing review cycles
- **Better Collaboration**: Humans and agents can work on the same codebase seamlessly

### 1.3 Language Characteristics

Alloy is a complete general-purpose programming language that provides all modern programming constructs:

**Core Programming Features:**
- **Primitive Types**: Strings, numbers, booleans, null, lists, dictionaries
- **Variables and Assignment**: Full variable declaration and assignment support
- **Control Flow**: Conditionals (when/then/otherwise), loops (for, while), pattern matching
- **Tools**: First-class tools with parameters, return values, and type hints
- **Data Structures**: Objects (things), arrays, dictionaries with full manipulation capabilities
- **Error Handling**: Comprehensive error types and propagation patterns
- **Modules and Composition**: Code organization and reusability patterns

**Language Design:**
- **Paradigm**: Multi-paradigm (procedural, object-oriented, functional)
- **Typing**: Dynamic with optional type hints
- **Execution**: Interpreted with potential for compilation
- **Concurrency**: Async-first for AI operations
- **Memory Management**: Garbage collected

**AI Integration as First-Class Citizen:**
- **Agents**: AI models as computational primitives
- **Multi-Agent Collaboration**: Swarm intelligence and coordination patterns
- **Memory Primitives**: Persistent, shared, and session memory for AI context
- **Meta-Programming**: Self-improving and self-generating code capabilities

This combination makes Alloy a complete programming language that happens to excel at AI integration, rather than an AI-specific domain language.

---

## 2. Syntax Grammar

### 2.1 Bracket Syntax Rules

Alloy follows consistent bracket syntax rules across all language constructs to maintain clarity and predictability for both agents and humans:

#### 2.1.1 Core Bracket Rule

- **Single statement = inline without brackets**
- **Multiple statements = brackets required**

This rule applies consistently to all control structures (conditionals, loops) and agent operations.

#### 2.1.2 Conditional Statements

```alloy
// Single statement - inline
when age > 18 then allow_access()
when error exists then return error_message

// Multiple statements - brackets required
when age > 18 then {
    log_access_attempt()
    allow_access()
    update_user_status()
}

when error exists then {
    log_error(error)
    notify_admin()
    return error_message
} otherwise {
    continue_processing()
}
```

#### 2.1.3 Loop Statements

```alloy
// Single statement - inline
for user in users process_user(user)
while has_data read_next_item()

// Multiple statements - brackets required
for user in users {
    validate_user(user)
    process_user(user)
    log_result(user)
}

while has_data {
    item = read_next_item()
    process_item(item)
    update_progress()
}
```

#### 2.1.4 Agent Block Syntax

```alloy
// Single agent command - inline
result, error = claude Analyze data

// Multiple agent commands - block with must/should
result, error = claude {
    must Analyze data
    should Include confidence_scores
    must Generate summary
}

// Agent blocks with implicit variable access
user_data = "some text to analyze"
result, error = claude {
    must Analyze user_data
    should Include confidence_scores
    should Provide reasoning
}
```

**Agent Block Execution Semantics:**
- **Implicit variable access**: Agent blocks can access any variables in current scope
- **Single combined input**: All commands become ONE system prompt + user message
- **One API call**: Results in single LLM call, single output
- **Must/should distinction**: Both included in prompt, agent interprets priority

**Must vs Should Operations:**
- **must**: Commands that must always be included in the agent's processing, regardless of input
- **should**: Commands that should be executed only if appropriate for the input/context (agent decides based on complexity, ambiguity, etc.)

Both must and should commands can succeed or fail - error handling is handled separately by the Result pattern.

Agent decides whether to execute "should" commands based on context, confidence, and input complexity. The agent makes contextual decisions about whether "should" commands are warranted based on the input and situation.

#### 2.1.5 Tool Definitions

Tools support two forms for maximum flexibility:

```alloy
// Full form: tool body assigns to variable, no explicit return needed
tool calculate_tax takes amount, rate returns result {
    result = amount * rate / 100
}

tool process_user takes user_data returns result {
    validate_user(user_data)
    process_data(user_data)
    result = processed_result
}

// Inline form: for simple one-line tools  
tool square takes x returns x * x
tool greeting takes name returns "Hello, " + name + "!"
```

### 2.2 Agent Block Semantics

Alloy introduces a sophisticated semantic system for agent blocks that distinguishes between required and optional operations:

#### 2.2.1 Must vs Should Operations

**Must Operations (`must`):**
- **Semantics**: This command must always execute regardless of input
- **Execution**: Always executed by the agent
- **Use Cases**: Operations that are essential for any valid response

**Should Operations (`should`):**
- **Semantics**: This command should execute only if appropriate for the input/context
- **Execution**: Agent decides whether to execute based on context, confidence, and input complexity
- **Agent Decision**: Agent evaluates whether the operation makes sense for the current input and situation

#### 2.2.2 Agent Decision Factors for Should Operations

Agents consider multiple factors when deciding whether to execute `should` commands:

- **Input Complexity**: Simple inputs may skip optional analysis, complex inputs trigger deeper processing
- **Context Appropriateness**: Agent evaluates whether the operation makes sense for the current context
- **Available Resources**: Time and computational constraints influence execution decisions
- **Confidence Level**: Agent's confidence in successfully completing the operation
- **Data Quality**: Quality and completeness of input data affects operation relevance

#### 2.2.3 Error Handling vs Execution Semantics

**Important distinction**: must/should semantics are about **execution requirements**, not error handling:

- **Execution Semantics**: Whether a command gets executed (must = always, should = conditionally)
- **Error Handling**: How failures are handled when commands do execute (handled by Result pattern)

Both `must` and `should` commands can succeed or fail when executed. Error handling is a separate concern from execution requirements and is managed through the Result pattern described in Section 8.

```alloy
// Example demonstrating must vs should semantics
analysis_result, error = data_analyst {
    must ValidateInputData input_dataset        // Always execute - essential operation
    should PerformOutlierDetection threshold: 2.5  // Execute if appropriate - agent decides based on data complexity
    must GenerateBasicStatistics                // Always execute - essential operation
    should CreateVisualization chart_type: "scatter"  // Execute if appropriate - agent decides based on data size/type
    must SummarizeFindings                      // Always execute - essential operation
}

// ValidateInputData: Always executed
// PerformOutlierDetection: Executed only if agent determines it's appropriate for the input
// GenerateBasicStatistics: Always executed
// CreateVisualization: Executed only if agent determines it's appropriate for the data
// SummarizeFindings: Always executed
```

### 2.3 Lexical Structure

#### 2.3.1 Identifiers and Keywords

Alloy encourages descriptive, verbose identifiers that clearly communicate intent. This is particularly important for agent-generated code, where clarity is paramount.

```ebnf
identifier ::= lowercase_start (letter | digit | '_')*
command_identifier ::= uppercase_start (letter | digit | '_')*
lowercase_start ::= 'a'..'z'
uppercase_start ::= 'A'..'Z'
letter ::= 'a'..'z' | 'A'..'Z'
digit ::= '0'..'9'
```

**Agent-Friendly Identifier Conventions:**
- Use full words instead of abbreviations: `user_authentication_service` not `auth_svc`
- Include context in names: `database_connection_error` not `db_err`
- Use descriptive verbs: `validate_user_credentials` not `check_user`
- Prefer longer, self-documenting names: `customer_order_processing_result` not `result`

#### 2.3.2 Reserved Keywords

Keywords are chosen to read like natural English, making agent-generated code highly readable:

```
agent, thing, tool, command, means, takes, returns, with, from, then, 
when, otherwise, while, for, in, true, false, null, async, await,
exists, is_empty, validate, process, handle_error, swarm, pattern,
memory, persistent, shared, Send, Broadcast, Request, Store, Recall,
Forget, Share, Generate, Optimize, Reflect, Review, alloy, must, should
```

#### 2.3.3 Literals

```ebnf
string_literal ::= '"' (char | escape_sequence)* '"'
number_literal ::= integer | float
integer ::= digit+
float ::= digit+ '.' digit+
boolean_literal ::= 'true' | 'false'
null_literal ::= 'null'
```

### 2.4 Program Structure

```ebnf
program ::= statement*

statement ::= 
    | agent_definition
    | thing_definition  
    | tool_definition
    | command_definition
    | assignment
    | expression_statement
    | control_flow

expression_statement ::= expression newline
```

### 2.5 Core Syntax Forms

#### 2.5.1 Agent Definition

```ebnf
agent_definition ::= identifier '=' 'agent' string_literal composition?

composition ::= 'with' composition_list
composition_list ::= composition_item (',' composition_item)*
composition_item ::= identifier | tool_call | system_prompt_block

system_prompt_block ::= '{' system_prompt_statement* '}'
system_prompt_statement ::= ('must' | 'should') string_literal
```

#### 2.5.2 Thing Definition

```ebnf
thing_definition ::= identifier '=' 'thing' property_list? composition?

property_list ::= 'with' property (',' property)*
property ::= identifier | property_assignment
property_assignment ::= identifier value
```

#### 2.5.3 Tool Definition

```ebnf
tool_definition ::= 'tool' identifier parameter_list? return_clause? block

parameter_list ::= 'takes' parameter (',' parameter)*
parameter ::= identifier type_hint?
type_hint ::= ':' type_name

return_clause ::= 'returns' type_name

block ::= '{' statement* '}'
```

#### 2.5.4 Command Definition

```ebnf
command_definition ::= 'command' command_identifier 'means' string_literal
```

#### 2.5.5 Expressions

```ebnf
expression ::= 
    | command_expression
    | dot_access
    | tool_call
    | data_extraction
    | chain_expression
    | binary_expression
    | primary_expression

command_expression ::= agent_ref (command_identifier expression* | agent_block)
agent_block ::= '{' agent_command_list '}'
agent_command_list ::= agent_command (',' agent_command)*
agent_command ::= ('must' | 'should') command_identifier expression*

dot_access ::= expression '.' identifier
tool_call ::= identifier '(' argument_list? ')'
data_extraction ::= identifier 'from' expression
chain_expression ::= expression 'then' expression
```

---

## 3. Type System

### 3.1 Type Hierarchy

Alloy uses a dynamic type system with the following core types:

```
Any
├── Primitive
│   ├── String
│   ├── Number
│   ├── Boolean
│   └── Null
├── Composite
│   ├── List
│   ├── Dict
│   └── Thing
├── Executable
│   ├── Agent
│   ├── Tool
│   └── Command
└── Result
    ├── Success[T]
    └── Error
```

### 3.2 Type Definitions

#### 3.2.1 Primitive Types

- **String**: UTF-8 encoded text
- **Number**: 64-bit floating point (integers are a subset)
- **Boolean**: `true` or `false`
- **Null**: Absence of value

#### 3.2.2 Composite Types

- **List**: Ordered collection of values `[item1, item2, ...]`
- **Dict**: Key-value mapping `{key: value, ...}`
- **Thing**: Enhanced dict with attached capabilities

#### 3.2.3 Executable Types

- **Agent**: AI model reference with optional tools
- **Tool**: Deterministic computation
- **Command**: Named AI instruction template

#### 3.2.4 Result Types

All AI operations and potentially-failing tools return Result types:

```
Result[T] = Success[T] | Error

Success[T] {
    value: T
    confidence?: Number  // For AI operations
    metadata?: Dict
}

Error {
    message: String
    code?: String
    details?: Dict
}
```

### 3.3 Type Coercion

Alloy performs automatic type coercion in specific contexts:

1. **String Context**: Any value can be converted to string representation
2. **Boolean Context**: Standard truthiness rules apply
3. **Number Context**: Strings representing numbers are automatically parsed

---

## 4. Core Primitives

### 4.1 Agent

An agent represents an AI model with optional tools and configuration. Agents can be defined with system prompts using `must` and `should` statements to establish their core behavior and contextual preferences.

#### 4.1.1 Agent Definition Syntax

```alloy
// Basic agent with descriptive name
claude_general_assistant = agent "claude-3.5-sonnet"

// Agent with tools using clean syntax
document_research_agent = agent "claude-3.5-sonnet" with web_search_tool, file_reader_tool

// Agent with explicit configuration parameters
fast_response_agent = agent "claude-3.5-sonnet" with {
    temperature_setting: 0.1,
    maximum_tokens_per_response: 1000,
    response_format: "structured"
}

// Agent with system prompt block
claude = agent "gpt-4o-mini" with {
    must "Act as a helpful programming assistant"
    must "Always provide working code examples"
    should "Explain complex concepts clearly"
    should "Include error handling in examples"
}
```

#### 4.1.2 Agent System Prompt Semantics

**System Prompt Synthesis:**
- `must` statements become **core system prompt requirements** that define essential agent behavior
- `should` statements become **contextual system prompt preferences** that guide but don't mandate behavior
- System prompt is synthesized from these statements and used for all interactions with this agent

**Must vs Should in System Prompts:**
- **Must**: Core behavioral requirements that the agent must always follow
- **Should**: Preferred behaviors that enhance the agent's responses when appropriate

```alloy
// Specialized agent with comprehensive system prompt
programming_assistant = agent "claude-3.5-sonnet" with {
    must "Provide syntactically correct code"
    must "Include comprehensive error handling"
    should "Explain the reasoning behind code choices"
    should "Suggest performance optimizations when relevant"
    should "Include usage examples for complex functions"
}
```

#### 4.1.3 Agent Runtime Structure

```
Agent {
    model: String           // Model identifier
    tools: List[Tool]       // Available tools
    config: Dict           // Model parameters
    context: List[Message] // Conversation history
    memory: Dict[String, Memory] // Named memory stores
}
```

#### 4.1.4 Agent Operations

- **Command Execution**: `agent CommandName arguments...`
- **Tool Access**: Agents can call their attached tools
- **Context Management**: Automatic conversation history tracking
- **Memory Operations**: Store, recall, and share information across sessions
- **Communication**: Send, broadcast, and request information from other agents

### 4.2 Thing

A thing is a flexible data structure that can have attached agents and tools, enabling data to have behaviors.

#### 4.2.1 Thing Definition Syntax

```alloy
// Basic thing with explicit, descriptive properties
user_profile = thing with user_name "Alice", user_age 30

// Thing with capabilities using clear naming
research_project = thing with {
    project_name: "AI Research",
    research_papers: [],
    project_status: "active"
} with agent document_research_agent

// Thing with both data and tools using verbose identifiers
shopping_cart = thing with cart_items [], cart_total 0 with tool calculate_cart_total, agent cart_optimization_agent
```

#### 4.2.2 Thing Runtime Structure

```
Thing {
    data: Dict             // Key-value properties
    agents: Dict[String, Agent]  // Named agent capabilities
    tools: Dict[String, Tool]    // Named tool capabilities
}
```

#### 4.2.3 Thing Operations

- **Property Access**: `thing.property`
- **Capability Access**: `thing.agent_name` or `thing.tool_name`
- **Method Calls**: `thing.tool_name(args)`
- **Agent Commands**: `thing.agent_name CommandName args`

### 4.3 Tool

Tools are deterministic computations that can be called by agents or directly in code.

#### 4.3.1 Tool Definition Syntax

```alloy
// Basic tool with descriptive name and clear purpose (full form)
tool generate_greeting_message takes user_name returns greeting {
    greeting = "Hello, " + user_name + "!"
}

// Inline form for simple tools
tool generate_greeting_message takes user_name returns "Hello, " + user_name + "!"

// Tool with multiple parameters using explicit, descriptive names
tool calculate_tax_amount takes purchase_amount: Number, tax_rate: Number returns calculated_tax {
    calculated_tax = purchase_amount * tax_rate
}

// Tool with comprehensive error handling that agents naturally write
tool perform_division_operation takes dividend: Number, divisor: Number returns division_result {
    when divisor == 0 then {
        division_result = (null, "Cannot perform division: divisor cannot be zero")
    } otherwise {
        division_result = dividend / divisor
    }
}
```

#### 4.3.2 Tool Runtime Structure

```
Tool {
    name: String
    parameters: List[Parameter]
    return_type: Type
    body: Block
}

Parameter {
    name: String
    type: Type
    required: Boolean
}
```

### 4.4 Command

Commands are named AI instruction templates that can be reused across agents.

#### 4.4.1 Command Definition Syntax

```alloy
command AnalyzeDataPatterns means "Examine the provided data thoroughly and identify key patterns, trends, and actionable insights"

command GenerateExecutiveSummary means "Create a concise executive summary highlighting the most important points and conclusions"

command GenerateContentFromSpecification means "Create new content based on the detailed specifications and context provided"

command ValidateDataIntegrity means "Verify that the provided data meets quality standards and is suitable for processing"
```

#### 4.4.2 Command Runtime Structure

```
Command {
    name: String
    template: String
    metadata?: Dict
}
```

---

## 5. Multi-Agent Collaboration

### 5.1 Swarm Definitions

Swarms enable coordinated multi-agent collaboration with built-in patterns for common workflows.

#### 5.1.1 Basic Swarm Definition

```alloy
// Sequential processing swarm
research_team = swarm researcher, analyzer, writer with pattern sequential

// Parallel processing swarm
support_team = swarm agent1, agent2, agent3 with pattern parallel

// Hierarchical organization swarm
hierarchy = swarm manager, worker1, worker2 with pattern hierarchical

// Review and consensus swarm
review_team = swarm reviewer1, reviewer2, editor with pattern review

// Debate and deliberation swarm
debate_team = swarm advocate, critic, mediator with pattern debate
```

#### 5.1.2 Built-in Collaboration Patterns

**Sequential Pattern**: Agents work in order, each building on the previous agent's output
- Agent A completes → Agent B begins with A's output → Agent C begins with B's output
- Error in any step stops the chain and returns the error
- Natural for pipeline processing workflows

**Parallel Pattern**: Agents work simultaneously on the same or different inputs
- All agents begin processing at the same time
- Results are collected when all agents complete
- Faster processing for independent tasks

**Hierarchical Pattern**: Manager agent delegates to worker agents
- Manager analyzes task and distributes work
- Workers execute assigned portions
- Manager synthesizes worker results into final output

**Review Pattern**: Multiple agents evaluate the same input independently
- Each agent provides independent analysis
- Results include all perspectives for comparison
- Useful for quality assurance and consensus building

**Debate Pattern**: Agents argue different perspectives before reaching conclusion
- Advocate presents one viewpoint
- Critic challenges and presents counterarguments
- Mediator synthesizes both perspectives into balanced conclusion

### 5.2 Custom Pattern Definition

Define custom collaboration patterns for specific use cases:

```alloy
// Define custom collaboration pattern
custom_review_pattern = pattern where
  first_agent sends results to second_agent
  when second_agent completes then third_agent begins
  all_agents share workspace
  final_agent synthesizes all_results

// Use custom pattern in swarm
specialized_review_team = swarm initial_reviewer, detail_checker, final_synthesizer with pattern custom_review_pattern

// Multi-stage custom pattern
complex_analysis_pattern = pattern where
  data_collector gathers input_sources
  when data_collector completes then parallel_analyzers begin
  parallel_analyzers = [analyst1, analyst2, analyst3]
  when parallel_analyzers complete then synthesis_agent combines all_results
  quality_checker validates synthesis_results

analysis_swarm = swarm data_collector, analyst1, analyst2, analyst3, synthesis_agent, quality_checker with pattern complex_analysis_pattern
```

### 5.3 Agent Communication

Agents in swarms can communicate directly using natural language operations:

```alloy
// Direct communication between agents
researcher Send findings to analyzer
analyzer Broadcast insights to research_team
summarizer Request clarification from researcher about data_point

// Communication with structured data
data_analyst Send {
    analysis_results: processed_data,
    confidence_score: 0.87,
    recommendations: ["action1", "action2"]
} to project_manager

// Broadcasting to entire swarm
team_leader Broadcast {
    status_update: "Phase 1 complete",
    next_phase_instructions: "Begin analysis of collected data",
    deadline: "2024-01-15"
} to research_team

// Requesting specific information
report_writer Request "executive summary of findings" from analysis_team
```

### 5.4 Swarm Execution Examples

#### 5.4.1 Sequential Research Pipeline

```alloy
// Define specialized agents
data_collector = agent "claude-3.5-sonnet" with web_search, file_reader
data_analyzer = agent "claude-3.5-sonnet" with stats_analysis, visualization
report_writer = agent "claude-3.5-sonnet" with doc_generation, formatting

// Create sequential research team
research_pipeline = swarm data_collector, data_analyzer, report_writer with pattern sequential

// Execute research project
research_topic = "impact of remote work on productivity"
final_report, pipeline_error = research_pipeline Execute research_topic

when pipeline_error exists then {
    print "Research pipeline failed: " + pipeline_error.message
} otherwise {
    print "Research complete. Report: " + final_report.value
}
```

#### 5.4.2 Parallel Document Review

```alloy
// Define review specialists
content_reviewer = agent "claude-3.5-sonnet" with grammar_check, style_analysis
technical_reviewer = agent "claude-3.5-sonnet" with fact_checker, citation_validator
legal_reviewer = agent "claude-3.5-sonnet" with compliance_checker, risk_assessment

// Create parallel review team
review_panel = swarm content_reviewer, technical_reviewer, legal_reviewer with pattern parallel

// Review document simultaneously
document_to_review = "product_launch_proposal.md"
review_results, review_error = review_panel Review document_to_review

when review_results exists then {
    for individual_review in review_results.value {
        print individual_review.reviewer_name + " findings: " + individual_review.summary
    }
}
```

#### 5.4.3 Hierarchical Project Management

```alloy
// Define project hierarchy
project_manager = agent "claude-3.5-sonnet" with task_planning, resource_allocation
developer1 = agent "claude-3.5-sonnet" with coding_tools, testing_tools
developer2 = agent "claude-3.5-sonnet" with coding_tools, documentation_tools
qa_engineer = agent "claude-3.5-sonnet" with testing_framework, bug_tracking

// Create hierarchical development team
development_team = swarm project_manager, developer1, developer2, qa_engineer with pattern hierarchical

// Execute project with manager coordination
project_requirements = {
    feature_description: "user authentication system",
    deadline: "2024-02-01",
    quality_standards: "high"
}

project_result, project_error = development_team Implement project_requirements
```

---

## 6. Memory Primitives

### 6.1 Memory as Core Primitive

Memory is a first-class primitive in Alloy, enabling agents to maintain context, learn from interactions, and share knowledge across sessions and with other agents.

#### 6.1.1 Memory Assignment Syntax

```alloy
// Agent with session memory (temporary)
claude_assistant = agent "claude-3.5-sonnet" with memory user_preferences, conversation_history

// Agent with persistent memory (saved across executions)
research_agent = agent "claude-3.5-sonnet" with memory persistent project_findings, session current_context

// Agent with shared memory (accessible by team members)
team_leader = agent "claude-3.5-sonnet" with memory shared team_context, persistent personal_notes

// Multiple memory types with explicit naming
comprehensive_assistant = agent "claude-3.5-sonnet" with memory {
    session: ["current_conversation", "temporary_calculations"],
    persistent: ["user_profile", "learned_preferences", "project_history"],
    shared: ["team_knowledge_base", "common_procedures"]
}
```

#### 6.1.2 Memory Operations

```alloy
// Store information in memory with descriptive context
claude_assistant Store {
    insight: "User prefers detailed explanations for technical topics",
    context: "programming_help_session",
    confidence: 0.9,
    timestamp: get_current_timestamp()
} in memory

// Recall specific information with query parameters
user_preferences, recall_error = claude_assistant Recall from memory where {
    topic: "programming_preferences",
    recency: "last_30_days"
}

// Recall with keyword matching
quantum_research_findings = researcher Recall from memory where topic: "quantum computing"

// Forget outdated information
claude_assistant Forget outdated_preferences from memory where {
    age: "older_than_6_months",
    relevance: "low"
}

// Share memory among team members
research_team Share workspace_memory among [researcher, analyzer, writer]

// Transfer specific knowledge
senior_agent Share {
    knowledge_area: "best_practices",
    specific_insights: learned_optimization_techniques
} with junior_agent
```

### 6.2 Memory Types and Persistence

#### 6.2.1 Session Memory

- **Scope**: Current execution session only
- **Lifetime**: Cleared when agent stops or restarts
- **Use Cases**: Temporary calculations, current conversation context, working variables

```alloy
// Session memory for temporary context
chat_assistant = agent "claude-3.5-sonnet" with memory session conversation_flow, working_data

// Store temporary calculation results
chat_assistant Store {
    calculation_result: complex_computation_output,
    intermediate_steps: computation_breakdown,
    session_id: current_session_identifier
} in memory
```

#### 6.2.2 Persistent Memory

- **Scope**: Saved across agent executions and system restarts
- **Lifetime**: Permanent until explicitly deleted
- **Use Cases**: User preferences, learned patterns, project knowledge, accumulated expertise

```alloy
// Persistent memory for long-term learning
learning_agent = agent "claude-3.5-sonnet" with memory persistent user_interaction_patterns, domain_knowledge

// Store learned insights permanently
learning_agent Store {
    pattern: "User asks follow-up questions when explanations are too brief",
    evidence_count: 15,
    reliability_score: 0.85,
    learning_date: get_current_timestamp()
} in memory

// Recall persistent insights
learned_patterns = learning_agent Recall from memory where {
    type: "interaction_pattern",
    reliability: "above_0.8"
}
```

#### 6.2.3 Shared Memory

- **Scope**: Accessible by multiple agents in a swarm or team
- **Lifetime**: Persistent across agent sessions, shared access
- **Use Cases**: Team knowledge base, collaborative findings, common procedures

```alloy
// Shared memory for team collaboration
team_knowledge_base = memory shared with access_control: ["research_team_members"]

// Multiple agents sharing knowledge
researcher = agent "claude-3.5-sonnet" with memory shared team_knowledge_base
analyzer = agent "claude-3.5-sonnet" with memory shared team_knowledge_base
writer = agent "claude-3.5-sonnet" with memory shared team_knowledge_base

// Researcher adds findings to shared memory
researcher Store {
    research_finding: "New optimization technique reduces processing time by 40%",
    validation_status: "peer_reviewed",
    applicable_domains: ["data_processing", "machine_learning"],
    contributor: "researcher_agent"
} in memory

// Analyzer accesses shared findings
relevant_findings = analyzer Recall from memory where {
    applicable_domain: "data_processing",
    validation_status: "peer_reviewed"
}
```

### 6.3 Memory Query Language

Alloy provides a comprehensive memory query language that combines deterministic operators with AI-powered commands for sophisticated memory retrieval and analysis.

#### 6.3.1 Core Concept

Memory queries use a graduated syntax that combines deterministic operators with AI-powered commands. This architecture allows for fast deterministic filtering followed by AI-powered semantic operations.

#### 6.3.2 Query Syntax Levels

**1. Simple Key-Value Queries:**
```alloy
findings = claude Recall from memory where topic: "quantum computing"
users = claude Recall from memory where status: "active"
```

**2. Inline Logical Operations:**
```alloy
findings = claude Recall from memory where topic: "quantum computing" and confidence > 0.8
users = claude Recall from memory where status: "active" or last_login > "2024-01-01"
```

**3. Complex Block Queries:**
```alloy
results = claude Recall from memory where {
    topic contains "AI"
    and confidence_score > 0.7
    and created_date > "2024-01-01"
    and DateWithin created_date, last_30_days
    and SimilarTo query: current_research
}
```

#### 6.3.3 Execution Architecture

**Deterministic Operations (no agent needed):**
- Basic operators: `>`, `<`, `>=`, `<=`, `==`, `!=`, `contains`, `starts_with`, `ends_with`
- Logical operators: `and`, `or`, `not`
- These are executed first for fast filtering

**AI Operations (require agent execution):**
- Commands like `DateWithin`, `SimilarTo`, `SemanticMatch`
- These are AI prompts with variable interpolation
- Executed by the agent after deterministic filtering

#### 6.3.4 Command Definition for Queries

```alloy
command DateWithin means "check if the date {date} is within {range}"
command SimilarTo means "find content semantically similar to {query}"
command SemanticMatch means "determine if content matches the semantic intent of {criteria}"
```

#### 6.3.5 Extensibility

Developers can define custom query commands:

```alloy
command MyDomainFilter means "apply domain-specific filtering logic for {criteria}"
command RelevanceScore means "score content relevance to {context} on scale 0-1"

// Then use in queries:
results = claude Recall from memory where {
    basic_field == "value"
    and MyDomainFilter domain_criteria
    and RelevanceScore current_context > 0.8
}
```

#### 6.3.6 Execution Flow

1. **Fast deterministic filtering** applied first using basic operators
2. **Remaining subset** passed to agent for command evaluation
3. **Agent executes commands** as prompts with variable interpolation
4. **Final filtered results** returned

#### 6.3.7 Performance Characteristics

- **Deterministic operations**: Fast, executed by runtime
- **Command operations**: Slower, require agent inference
- **System optimizes** by applying deterministic filters first

### 6.4 Advanced Memory Operations

#### 6.4.1 Memory Querying and Filtering

```alloy
// Complex memory queries with multiple criteria
recent_insights = knowledge_agent Recall from memory where {
    topic: "artificial_intelligence",
    date_range: "last_3_months",
    confidence: "above_0.7",
    source: "peer_reviewed_papers"
}

// Pattern-based memory retrieval
similar_problems = problem_solver Recall from memory where {
    pattern_match: current_problem_description,
    similarity_threshold: 0.8,
    outcome: "successful_solution"
}

// Memory aggregation and analysis
memory_summary = data_analyst Analyze memory where {
    time_period: "last_year",
    grouping: "by_topic",
    metrics: ["frequency", "success_rate", "user_satisfaction"]
}
```

#### 6.4.2 Memory Maintenance and Optimization

```alloy
// Automated memory cleanup
memory_manager = agent "claude-3.5-sonnet" with memory_optimization_tools

// Regular memory maintenance
memory_manager Optimize memory where {
    remove_duplicates: true,
    consolidate_similar_entries: true,
    archive_old_entries: "older_than_1_year",
    maintain_performance: "high_priority"
}

// Memory backup and synchronization
memory_manager Backup persistent_memory to secure_storage
memory_manager Synchronize shared_memory across team_members
```

---

## 7. Meta-Programming Patterns

### 7.1 The Alloy Agent

The `alloy` agent is a built-in meta-agent that provides language-level operations for reflection, optimization, validation, and code generation.

#### 7.1.1 Basic Alloy Agent Operations

```alloy
// Reflection on analysis results
reflection_report = alloy Reflect on analysis_result with criteria: "accuracy, completeness, methodology"

// Workflow optimization
optimized_workflow = alloy Optimize workflow_definition for performance

// Code validation against specifications
validation_result = alloy Validate generated_code against {
    specification: coding_standards,
    requirements: functional_requirements,
    quality_metrics: ["readability", "maintainability", "performance"]
}

// Code review and improvement suggestions
code_review = alloy Review code_block for {
    focus_areas: ["readability_improvements", "performance_optimization", "error_handling"],
    standards: team_coding_standards,
    suggestions_format: "detailed_with_examples"
}
```

#### 7.1.2 Runtime Tool Generation

Agents can generate and execute tools dynamically based on requirements:

```alloy
// Generate tool from natural language requirement
sort_requirement = "sort users by last login date, then by name alphabetically"
sorting_tool, generation_error = alloy Generate tool for requirement: sort_requirement

when generation_error exists then {
    print "Tool generation failed: " + generation_error.message
} otherwise {
    // Use the generated tool immediately
    sorted_users, sorting_error = sorting_tool(user_list)
    print "Users sorted successfully: " + sorted_users.length + " users processed"
}

// Generate complex processing tool with specifications
data_processing_requirements = {
    input_format: "CSV with headers",
    required_columns: ["user_id", "timestamp", "event_type"],
    output_format: "JSON with aggregated metrics",
    validation_rules: ["no_duplicate_user_ids", "valid_timestamps"],
    performance_target: "process_1000_records_per_second"
}

data_processor_tool = alloy Generate tool for specifications: data_processing_requirements
processed_data = data_processor_tool Execute with customer_event_data
```

#### 7.1.3 Workflow Generation and Optimization

```alloy
// Generate complete workflow from high-level description
workflow_specification = "process customer data, analyze sentiment, generate personalized recommendations, create summary report"
customer_workflow, workflow_error = alloy Generate workflow for specification: workflow_specification

when customer_workflow exists then {
    // Execute generated workflow
    workflow_results = customer_workflow Execute with {
        input_data: customer_interaction_data,
        configuration: {
            sentiment_model: "advanced_nlp",
            recommendation_count: 10,
            report_format: "executive_summary"
        }
    }
    
    print "Customer analysis complete: " + workflow_results.summary
}

// Self-improving workflows
improved_workflow = alloy Optimize existing_workflow for {
    performance_goals: ["reduce_processing_time", "improve_accuracy"],
    resource_constraints: ["memory_limit_4gb", "cpu_cores_8"],
    quality_requirements: ["maintain_95_percent_accuracy"]
}

// Workflow refactoring for clarity
cleaner_workflow = alloy Refactor complex_workflow_definition for {
    improvements: ["better_readability", "clearer_error_handling", "modular_structure"],
    maintain_functionality: true,
    add_documentation: true
}
```

### 7.2 Dynamic Code Generation

#### 7.2.1 Tool Generation from Requirements

```alloy
// Generate specific tool implementations
validation_requirements = {
    tool_name: "validate_email_address",
    input_parameters: ["email_string"],
    validation_criteria: ["valid_format", "domain_exists", "no_suspicious_patterns"],
    return_format: "success_boolean_with_detailed_errors",
    performance_requirement: "sub_100ms_response"
}

email_validator = alloy Generate tool for requirements: validation_requirements

// Test generated tool
test_email = "user@example.com"
validation_result, validation_error = email_validator(test_email)
print "Email validation result: " + validation_result.is_valid + " - " + validation_result.details

// Generate data transformation tools
transformation_spec = "convert JSON user data to standardized internal format with field validation"
data_transformer = alloy Generate transformer for specification: transformation_spec
standardized_data = data_transformer(raw_user_json)
```

#### 7.2.2 Agent-Generated Agent Configurations

```alloy
// Generate specialized agent configurations for specific tasks
agent_requirements = {
    domain: "financial_analysis",
    expertise_level: "expert",
    required_tools: ["financial_calculator", "market_data_fetcher", "risk_assessor"],
    communication_style: "professional_detailed",
    safety_constraints: ["no_investment_advice", "cite_sources", "express_uncertainty"]
}

financial_analyst_config = alloy Generate agent_configuration for requirements: agent_requirements
financial_analyst = agent "claude-3.5-sonnet" with financial_analyst_config

// Generated agent automatically includes appropriate tools and memory
market_analysis = financial_analyst Analyze market_data with focus: "risk_assessment"
```

### 7.3 Self-Optimization Patterns

#### 7.3.1 Performance Optimization

```alloy
// Optimize existing tools for better performance
slow_tool_definition = {
    name: "process_large_dataset",
    current_implementation: existing_implementation_code,
    performance_metrics: current_performance_data,
    optimization_targets: ["reduce_memory_usage", "improve_processing_speed"]
}

optimized_tool = alloy Optimize tool: slow_tool_definition
performance_improvement = alloy Measure improvement between {
    original: slow_tool_definition,
    optimized: optimized_tool
}

print "Performance improvement: " + performance_improvement.speed_increase + "% faster"

// Optimize entire workflows based on execution patterns
workflow_optimization_data = {
    workflow: customer_processing_pipeline,
    execution_history: past_30_days_performance,
    bottlenecks: identified_slow_points,
    resource_usage: memory_and_cpu_analysis
}

improved_pipeline = alloy Optimize workflow: workflow_optimization_data
```

#### 7.3.2 Code Quality Enhancement

```alloy
// Improve code readability and maintainability
code_improvement_request = {
    target_code: existing_code_block,
    improvement_goals: ["better_variable_names", "clearer_logic_flow", "comprehensive_error_handling"],
    coding_standards: team_standards,
    maintain_functionality: true
}

improved_code = alloy Refactor code: code_improvement_request
quality_metrics = alloy Assess code_quality for {
    original: existing_code_block,
    improved: improved_code,
    metrics: ["readability_score", "complexity_rating", "maintainability_index"]
}

// Automated documentation generation
code_documentation = alloy Generate documentation for {
    code: improved_code,
    documentation_style: "comprehensive_with_examples",
    target_audience: "team_developers",
    include_usage_examples: true
}
```

### 7.4 Practical Meta-Programming Examples

#### 7.4.1 Dynamic API Integration Generator

```alloy
// Generate API integration code from API documentation
api_specification = {
    api_name: "weather_service_api",
    base_url: "https://api.weather.com/v1",
    authentication: "api_key_header",
    endpoints: [
        {name: "current_weather", method: "GET", path: "/current/{location}"},
        {name: "forecast", method: "GET", path: "/forecast/{location}/{days}"}
    ],
    rate_limits: "100_requests_per_hour",
    error_handling: "standard_http_codes"
}

weather_api_client = alloy Generate api_client for specification: api_specification

// Use generated API client
current_weather = weather_api_client.current_weather("New York")
weekly_forecast = weather_api_client.forecast("New York", 7)
```

#### 7.4.2 Test Generation and Validation

```alloy
// Generate comprehensive tests for existing code
test_generation_request = {
    target_tool: user_authentication_tool,
    test_types: ["unit_tests", "integration_tests", "edge_case_tests"],
    coverage_goal: "95_percent",
    test_framework: "alloy_testing_framework",
    include_performance_tests: true
}

generated_tests = alloy Generate tests for: test_generation_request
test_execution_results = alloy Execute tests: generated_tests

print "Test coverage achieved: " + test_execution_results.coverage_percentage + "%"
print "Tests passed: " + test_execution_results.passed + "/" + test_execution_results.total
```

---

## 8. Error Handling

### 8.1 Result Pattern

All potentially-failing operations return Result types. This includes:
- AI agent commands
- Tool calls that may fail
- External API calls
- File operations

#### 8.1.1 Result Destructuring

```alloy
// Single result with explicit variable names
analysis_result, analysis_error = claude_general_assistant AnalyzeDataPatterns input_data
when analysis_error exists then {
    print "Data analysis operation failed: " + analysis_error.message
    return
}
print analysis_result.value

// Multiple assignment with explicit error propagation
summary_result, analysis_result, processing_error = claude_general_assistant GenerateExecutiveSummary input_data then claude_general_assistant AnalyzeDataPatterns
```

#### 8.1.2 Error Propagation

```alloy
// Errors automatically propagate through chains with descriptive names
final_result, processing_error = fetch_input_data() then claude_general_assistant AnalyzeDataPatterns then format_analysis_output()

// Equivalent explicit form that agents naturally write:
input_data, data_fetch_error = fetch_input_data()
when data_fetch_error exists then { return null, data_fetch_error }

analysis_result, analysis_error = claude_general_assistant AnalyzeDataPatterns input_data
when analysis_error exists then { return null, analysis_error }

formatted_output, formatting_error = format_analysis_output(analysis_result)
```

### 8.2 Error Types

#### 8.2.1 AI Errors

```alloy
AIError {
    message: String
    code: "model_unavailable" | "rate_limited" | "context_too_long" | "safety_filter"
    model: String
    retry_after?: Number
}
```

#### 8.2.2 Tool Errors

```alloy
ToolError {
    message: String
    code: "invalid_parameter" | "execution_failed" | "timeout"
    tool: String
    parameters?: Dict
}
```

#### 8.2.3 System Errors

```alloy
SystemError {
    message: String
    code: "network_error" | "file_not_found" | "permission_denied"
    details?: Dict
}
```

---

## 9. Control Flow and Composition

### 9.1 Sequential Composition (then)

The `then` operator chains operations, automatically handling error propagation. Agent blocks integrate seamlessly with then chaining:

```alloy
// Basic chaining
result, error = fetch_user_data() then claude Analyze then generate_report()

// Agent blocks in then chains
result = fetch_data then claude {
    must Analyze
} then format_output

// Short form for single commands
result = fetch_data then claude Analyze then format_output

// Chaining with intermediate variables
user_data, error = fetch_user_data()
analysis, error = user_data then claude Analyze
report, error = analysis then generate_report()
```

**Then Chaining with Agent Blocks:**
- Result from previous operation passed as context to agent block
- Agent block output passed to next operation in chain
- Error propagation works the same as single commands

### 9.2 Conditional Execution

```alloy
// Basic conditional using natural language keywords - single statements are inline
when user_authentication_successful then proceed_to_dashboard() otherwise redirect_to_login_page()

// Conditional with results using explicit variable names - single statements are inline
when analysis_result.confidence_score > 0.8 then accept_analysis_result(analysis_result.value) otherwise request_human_review_for_analysis(analysis_result)

// Example with multiple statements - brackets required
when user_authentication_successful then {
    log_successful_login()
    proceed_to_dashboard()
    update_last_login_time()
} otherwise {
    log_failed_attempt()
    redirect_to_login_page()
    increment_failure_count()
}
```

### 9.3 Loops

```alloy
// For-in loop with single statement - inline
for individual_item in item_collection process_individual_item(individual_item)

// While loop with single statement - inline
while processing_should_continue perform_processing_step()

// For-in loop with multiple statements - brackets required
for individual_item in item_collection {
    validate_individual_item(individual_item)
    process_individual_item(individual_item)
    log_processing_result(individual_item)
}

// While loop with multiple statements - brackets required
while processing_should_continue {
    perform_processing_step()
    update_processing_status()
    check_completion_criteria()
}

// Loop with comprehensive result handling
for individual_document in document_collection {
    document_summary, summarization_error = claude_general_assistant GenerateExecutiveSummary individual_document
    when summarization_error exists then {
        log_processing_error(summarization_error)
        continue
    }
    document_summaries.append(document_summary.value)
}
```

### 9.4 Parallel Execution

```alloy
// Async operations
async {
    result1 = claude Analyze data1
    result2 = claude Analyze data2
    result3 = claude Analyze data3
}

// Await results
final_result, error = await [result1, result2, result3] then claude Synthesize
```

---

## 10. Examples

### 10.1 Agent Definition and Block Syntax Examples

#### 10.1.1 Agent Definition with System Prompts

```alloy
// Agent with system prompt requirements and preferences
claude = agent "gpt-4o-mini" with {
    must "Act as a helpful programming assistant"
    must "Always provide working code examples"
    should "Explain complex concepts clearly"
    should "Include error handling in examples"
}

// Specialized agents with domain-specific system prompts
data_analyst = agent "claude-3.5-sonnet" with {
    must "Provide accurate statistical analysis"
    must "Validate data integrity before processing"
    should "Include visualization recommendations"
    should "Explain statistical significance"
    should "Suggest further analysis when appropriate"
}

// Research agent with comprehensive behavior definition
research_agent = agent "claude-3.5-sonnet" with web_search, pdf_reader with {
    must "Cite all sources accurately"
    must "Distinguish between facts and opinions"
    should "Provide multiple perspectives on controversial topics"
    should "Suggest additional research directions"
    should "Rate source credibility when relevant"
}
```

#### 10.1.2 Agent Block Execution Examples

The following examples demonstrate agent block syntax with must/should semantics:

```alloy
// Single agent command - inline syntax
basic_analysis, error = claude Analyze user_feedback

// Agent blocks with implicit variable access
user_data = "Customer complained about slow response times"
result, error = claude {
    must Analyze user_data
    should Include confidence_scores
    should Provide reasoning
}

// Complex workflow with then chaining
processed_result = fetch_data then claude {
    must Analyze
    should Include sentiment_analysis
} then format_output

// Short form for single commands in chains
final_result = fetch_data then claude Analyze then generate_report

// Agent block with data processing context
data_processor = agent "claude-3.5-sonnet" with statistical_tools, visualization_tools

input_dataset = load_customer_data()
processed_data, error = data_processor {
    must ValidateDataQuality input_dataset
    should IdentifyOutliers threshold: 2.5
    must GenerateStatistics distribution_statistics
    should CreateVisualization chart_type: "scatter"
    must SummarizeFindings findings_with_recommendations
}

// Real-world usage with comprehensive context
analysis_context = {
    data_source: "customer_surveys",
    time_period: "Q4_2024",
    focus_areas: ["satisfaction", "retention", "feature_requests"]
}

comprehensive_analysis, error = research_agent {
    must AnalyzeCustomerFeedback analysis_context
    should IdentifyTrendPatterns temporal_analysis
    must GenerateActionableInsights priority_ranking
    should PredictFutureOutcomes confidence_intervals
    must CreateExecutiveSummary stakeholder_format
}

// The agent decides whether to execute "should" commands based on:
// - Input data characteristics and complexity
// - Processing context and available resources  
// - Quality requirements and confidence levels
// - Relevance to the specific use case
```

### 10.2 Document Analysis Pipeline

```alloy
// Define tools
tool extract_text takes file_path: String returns String {
    // Implementation for text extraction
}

tool save_report takes content: String, path: String returns Boolean {
    // Implementation for saving files
}

// Define commands
command Analyze means "Analyze the document for key themes, sentiment, and important facts"
command Summarize means "Create a concise executive summary of the analysis"

// Define agents
claude = agent "claude-3.5-sonnet"
analyzer = agent "claude-3.5-sonnet" with extract_text, save_report

// Main processing pipeline
documents = ["report1.pdf", "report2.pdf", "report3.pdf"]
summaries = []

for doc_path in documents {
    // Extract and analyze
    text, error = extract_text(doc_path)
    when error exists then {
        print "Failed to extract text from " + doc_path
        continue
    }
    
    analysis, error = analyzer Analyze text
    when error exists then {
        print "Analysis failed for " + doc_path + ": " + error.message
        continue
    }
    
    summary, error = analyzer Summarize analysis.value
    when error exists then {
        print "Summarization failed for " + doc_path
        continue
    }
    
    summaries.append({
        document: doc_path,
        analysis: analysis.value,
        summary: summary.value,
        confidence: summary.confidence
    })
}

// Generate final report
final_report, error = analyzer Synthesize summaries
when error exists then {
    print "Failed to generate final report: " + error.message
} otherwise {
    save_report(final_report.value, "final_analysis.md")
    print "Analysis complete. Report saved to final_analysis.md"
}
```

### 10.3 E-commerce Recommendation System

```alloy
// Define data structures with explicit, agent-friendly naming
user_profile_with_preferences = thing with {
    unique_user_identifier: "user123",
    user_preference_settings: [],
    complete_purchase_history: []
} with agent recommendation_generation_agent

comprehensive_product_catalog = thing with {
    available_products_collection: [],
    product_categories_hierarchy: [],
    catalog_last_updated: get_current_timestamp()
} with agent "claude-3.5-sonnet", tool search_products_by_criteria

// Define tools with comprehensive, descriptive names
tool search_products_by_criteria takes search_query: String, filtering_criteria: Dict returns List {
    // Implementation for searching products based on specific criteria
}

tool fetch_complete_user_purchase_history takes user_identifier: String returns List {
    // Implementation for fetching comprehensive user purchase history
}

tool calculate_product_similarity_score takes first_product: Dict, second_product: Dict returns Number {
    // Implementation for calculating similarity score between two products
}

tool analyze_user_behavior_patterns takes user_activity_data: List returns Dict {
    // Implementation for analyzing user behavior patterns and preferences
}

// Define commands with explicit, comprehensive descriptions
command GeneratePersonalizedProductRecommendations means "Based on detailed user preferences, purchase history, and behavior patterns, generate highly relevant product recommendations"
command ExplainRecommendationReasoning means "Provide detailed explanation of why specific products were recommended to the user, including similarity factors and preference matching"
command AnalyzeUserPurchasePatterns means "Analyze user's historical purchase data to identify patterns, preferences, and buying behavior trends"

// Comprehensive recommendation pipeline with explicit agent configuration
recommendation_agent = agent "claude-3.5-sonnet" with product_search, user_history, similarity_calc, behavior_analysis

// Get comprehensive user context with detailed error handling
user_purchase_history, history_fetch_error = fetch_complete_user_purchase_history(user_profile_with_preferences.unique_user_identifier)
when history_fetch_error exists then {
    print "Could not fetch user purchase history: " + history_fetch_error.message
    return
}

user_behavior_analysis, behavior_analysis_error = analyze_user_behavior_patterns(user_purchase_history)
when behavior_analysis_error exists then {
    print "Could not analyze user behavior patterns: " + behavior_analysis_error.message
    // Continue with basic recommendations using available data
}

// Generate personalized recommendations with comprehensive input
generated_product_recommendations, recommendation_error = recommendation_agent GeneratePersonalizedProductRecommendations {
    user_preference_settings: user_profile_with_preferences.user_preference_settings,
    complete_purchase_history: user_purchase_history,
    user_behavior_patterns: user_behavior_analysis,
    available_products_collection: comprehensive_product_catalog.available_products_collection
}

when recommendation_error exists then {
    print "Product recommendation generation failed: " + recommendation_error.message
    return
}

// Generate detailed explanations for each recommendation
for individual_recommended_product in generated_product_recommendations.value {
    recommendation_explanation, explanation_error = recommendation_agent ExplainRecommendationReasoning {
        recommended_product: individual_recommended_product,
        user_context_information: user_profile_with_preferences.user_preference_settings,
        user_purchase_history: user_purchase_history,
        behavior_analysis_results: user_behavior_analysis
    }
    
    when recommendation_explanation exists then {
        individual_recommended_product.detailed_explanation = recommendation_explanation.value
        individual_recommended_product.explanation_confidence = recommendation_explanation.confidence
    } otherwise {
        individual_recommended_product.detailed_explanation = "Explanation generation failed"
    }
}

print "Successfully generated " + generated_product_recommendations.value.length + " personalized product recommendations with detailed explanations"
```

### 10.4 Research Assistant

```alloy
// Define research capabilities
tool web_search takes query: String returns List {
    // Web search implementation
}

tool read_pdf takes url: String returns String {
    // PDF reading implementation
}

tool save_notes takes content: String, filename: String returns Boolean {
    // Save notes to file
}

// Define research commands
command Research means "Search for academic papers and credible sources on the given topic"
command Synthesize means "Combine information from multiple sources into a coherent analysis"
command CriticallyAnalyze means "Evaluate the quality, reliability, and limitations of the sources"

// Create research agent
researcher = agent "claude-3.5-sonnet" with web_search, read_pdf, save_notes

// Research project
research_topic = "impact of AI on software development"

// Gather sources
sources, error = researcher Research research_topic
when error exists then {
    print "Research failed: " + error.message
    return
}

// Process each source
processed_sources = []
for source in sources.value {
    when source.type == "pdf" then {
        content, error = read_pdf(source.url)
        when error exists then {
            print "Failed to read PDF: " + source.url
            continue
        }
        source.content = content
    }
    
    // Analyze source quality
    analysis, error = researcher CriticallyAnalyze source
    when analysis exists then {
        source.quality_score = analysis.value.score
        source.limitations = analysis.value.limitations
    }
    
    processed_sources.append(source)
}

// Synthesize findings
synthesis, error = researcher Synthesize processed_sources
when error exists then {
    print "Synthesis failed: " + error.message
    return
}

// Save research notes
timestamp = current_time()
filename = "research_" + research_topic.replace(" ", "_") + "_" + timestamp + ".md"
save_notes(synthesis.value, filename)

print "Research complete. Notes saved to " + filename
print "Quality scores: " + processed_sources.map(s => s.quality_score).average()
```

### 10.5 Multi-Agent Collaboration Examples

#### 10.5.1 Comprehensive Research Project with Swarm Collaboration

```alloy
// Define specialized research agents with memory
data_collector = agent "claude-3.5-sonnet" with web_search, pdf_reader, database_query with memory persistent research_sources, shared team_workspace

data_analyzer = agent "claude-3.5-sonnet" with statistical_analysis, visualization, pattern_recognition with memory persistent analysis_methods, shared team_workspace

report_synthesizer = agent "claude-3.5-sonnet" with document_generation, citation_formatter, quality_checker with memory persistent writing_style_preferences, shared team_workspace

quality_reviewer = agent "claude-3.5-sonnet" with fact_checker, peer_review_guidelines, publication_standards with memory persistent review_criteria, shared team_workspace

// Create research swarm with custom pattern
research_collaboration_pattern = pattern where
  data_collector gathers comprehensive_sources
  when data_collector completes then data_analyzer begins statistical_analysis
  when data_analyzer completes then report_synthesizer creates preliminary_report
  quality_reviewer validates preliminary_report
  when quality_reviewer identifies issues then cycle_back_to_appropriate_agent
  all_agents share findings_workspace throughout_process

research_swarm = swarm data_collector, data_analyzer, report_synthesizer, quality_reviewer with pattern research_collaboration_pattern

// Execute comprehensive research project
research_topic = {
    subject: "impact of remote work on team productivity and innovation",
    scope: "technology companies 2020-2024",
    methodology: "mixed methods with quantitative and qualitative analysis",
    deliverable: "peer-review ready research paper"
}

// Store initial project context in shared memory
research_swarm Share {
    project_context: research_topic,
    quality_standards: "academic_publication_ready",
    collaboration_guidelines: "share_all_intermediate_findings",
    timeline: "comprehensive_analysis_no_rush"
} among all_team_members

// Execute research with automatic coordination
final_research_output, research_error = research_swarm Execute research_topic

when research_error exists then {
    print "Research project encountered issues: " + research_error.message
    
    // Analyze what went wrong and retry with improvements
    issue_analysis = alloy Analyze research_error for {
        failure_points: "identify_specific_breakdown",
        improvement_suggestions: "actionable_next_steps",
        resource_needs: "additional_tools_or_data"
    }
    
    print "Issue analysis: " + issue_analysis.summary
} otherwise {
    print "Research completed successfully!"
    print "Final paper length: " + final_research_output.word_count + " words"
    print "Sources analyzed: " + final_research_output.source_count
    print "Quality score: " + final_research_output.quality_assessment.overall_score
}
```

#### 10.5.2 Dynamic Tool Generation in Multi-Agent Context

```alloy
// Team that generates and uses custom tools collaboratively
tool_architect = agent "claude-3.5-sonnet" with memory persistent tool_design_patterns
code_generator = agent "claude-3.5-sonnet" with memory persistent implementation_best_practices
tool_tester = agent "claude-3.5-sonnet" with memory persistent testing_strategies
optimization_specialist = agent "claude-3.5-sonnet" with memory persistent performance_patterns

// Create tool development swarm
tool_dev_team = swarm tool_architect, code_generator, tool_tester, optimization_specialist with pattern sequential

// Business requirement for new tool
business_requirement = {
    description: "automated customer sentiment analysis from support tickets",
    input_format: "support ticket text and metadata",
    output_requirements: "sentiment score, emotional indicators, priority classification",
    performance_needs: "process 1000 tickets per minute",
    accuracy_target: "95% agreement with human reviewers",
    integration_requirements: "API endpoint with standard HTTP responses"
}

// Collaborative tool development
custom_sentiment_tool, development_error = tool_dev_team Develop tool: business_requirement

when custom_sentiment_tool exists then {
    // Test the generated tool
    test_tickets = load_sample_support_tickets()
    tool_performance = custom_sentiment_tool Test with test_tickets
    
    print "Generated tool performance:"
    print "Accuracy: " + tool_performance.accuracy_percentage + "%"
    print "Processing speed: " + tool_performance.tickets_per_minute + " tickets/min"
    print "API response time: " + tool_performance.average_response_time + "ms"
    
    // Use tool in production workflow
    production_tickets = fetch_pending_support_tickets()
    sentiment_analysis_results = custom_sentiment_tool(production_tickets)
    
    print "Analyzed " + sentiment_analysis_results.processed_count + " support tickets"
}
```

#### 10.5.3 Memory-Enabled Learning Collaboration

```alloy
// Learning-focused agents that improve over time
pattern_learner = agent "claude-3.5-sonnet" with memory persistent discovered_patterns, shared team_knowledge
knowledge_synthesizer = agent "claude-3.5-sonnet" with memory persistent synthesis_techniques, shared team_knowledge
performance_optimizer = agent "claude-3.5-sonnet" with memory persistent optimization_strategies, shared team_knowledge

// Create learning swarm with continuous improvement
learning_team = swarm pattern_learner, knowledge_synthesizer, performance_optimizer with pattern parallel

// Continuous learning loop
for learning_iteration in 1..10 {
    print "Learning iteration " + learning_iteration + " beginning"
    
    // Each agent learns from new data
    new_data_batch = fetch_latest_data_batch()
    
    // Parallel learning with memory updates
    async {
        patterns = pattern_learner AnalyzePatterns new_data_batch
        synthesis = knowledge_synthesizer SynthesizeKnowledge new_data_batch
        optimizations = performance_optimizer FindOptimizations new_data_batch
    }
    
    // Share learnings in team memory
    learning_team Share {
        iteration: learning_iteration,
        new_patterns: patterns.value,
        synthesis_insights: synthesis.value,
        optimization_opportunities: optimizations.value,
        combined_confidence: (patterns.confidence + synthesis.confidence + optimizations.confidence) / 3
    } among all_team_members
    
    // Reflect on learning progress
    learning_progress = alloy Reflect on team_learning_progress for iteration: learning_iteration
    print "Learning progress: " + learning_progress.summary
    
    // Optimize team collaboration based on learnings
    when learning_progress.suggests_team_optimization then {
        improved_collaboration = alloy Optimize learning_team based_on: learning_progress.insights
        learning_team = improved_collaboration
    }
}

// Generate comprehensive knowledge report
final_knowledge_synthesis = learning_team GenerateKnowledgeReport for {
    time_period: "all_learning_iterations",
    include_confidence_metrics: true,
    format: "comprehensive_with_examples"
}

print "Learning complete. Knowledge synthesis: " + final_knowledge_synthesis.summary
```

---

## 11. Standard Library

### 11.1 Agent-First Standard Library Design

The Alloy standard library is designed to maximize agent productivity through:
- **Descriptive Tool Names**: Every tool name clearly describes its purpose
- **Explicit Parameter Names**: Parameter names are self-documenting
- **Comprehensive Error Handling**: Built-in error cases that agents naturally handle
- **Natural Language Patterns**: Tool signatures read like English sentences

### 11.2 Core Modules

#### 11.2.1 IO Module

```alloy
// File operations with explicit, descriptive names
tool read_file_contents takes file_path: String returns String
tool write_content_to_file takes file_path: String, file_content: String returns Boolean
tool list_all_files_in_directory takes directory_path: String returns List[String]
tool check_if_file_exists takes file_path: String returns Boolean
tool create_directory_if_not_exists takes directory_path: String returns Boolean

// Network operations with clear purpose indicators
tool perform_http_get_request takes request_url: String returns Dict
tool perform_http_post_request takes request_url: String, request_data: Dict returns Dict
tool download_file_from_url takes source_url: String, destination_path: String returns Boolean
```

#### 11.2.2 Data Module

```alloy
// List operations with comprehensive, descriptive names
tool apply_tool_to_list_items takes input_list: List, transformation_tool: Tool returns List
tool filter_list_items_by_condition takes input_list: List, filtering_predicate: Tool returns List
tool reduce_list_to_single_value takes input_list: List, reduction_tool: Tool, initial_value: Any returns Any
tool sort_list_items_by_criteria takes input_list: List, sorting_tool: Tool returns List
tool get_unique_items_from_list takes input_list: List returns List

// String operations with explicit purpose indicators
tool split_string_by_delimiter takes input_text: String, splitting_delimiter: String returns List[String]
tool join_string_parts_with_delimiter takes string_parts: List[String], joining_delimiter: String returns String
tool check_string_matches_pattern takes input_text: String, matching_pattern: String returns Boolean
tool convert_string_to_lowercase takes input_text: String returns String
tool convert_string_to_uppercase takes input_text: String returns String
tool trim_whitespace_from_string takes input_text: String returns String
```

#### 11.2.3 Time Module

```alloy
tool get_current_timestamp returns String
tool parse_date_from_string takes date_string: String returns Dict
tool format_date_with_pattern takes date_object: Dict, format_pattern: String returns String
tool calculate_time_difference takes start_time: Dict, end_time: Dict returns Number
tool add_duration_to_date takes base_date: Dict, duration_amount: Number, duration_unit: String returns Dict
```

### 11.3 AI Utilities

#### 11.3.1 Model Management

```alloy
tool list_all_available_ai_models returns List[String]
tool get_detailed_model_information takes model_name: String returns Dict
tool estimate_token_count_for_text takes input_text: String, target_model: String returns Number
tool check_model_availability takes model_name: String returns Boolean
tool get_model_rate_limits takes model_name: String returns Dict
```

#### 11.3.2 Prompt Engineering

```alloy
command FillTemplateWithVariables means "Fill in the template with the provided variables and context"
command ChainOperationResults means "Use the output of the previous step as input to this step in the processing chain"
command ValidateResponseQuality means "Check whether the response meets the specified quality criteria and requirements"
command OptimizePromptForClarity means "Improve the prompt structure for better agent understanding and response quality"
```

### 11.4 Error Utilities

```alloy
tool retry_operation_with_limit takes target_operation: Tool, maximum_retry_attempts: Number returns Result
tool execute_operation_with_timeout takes target_operation: Tool, timeout_duration_seconds: Number returns Result
tool execute_with_fallback_strategy takes primary_operation: Tool, backup_operation: Tool returns Result
tool log_error_with_context takes error_information: Dict, operation_context: String returns Boolean
tool send_error_notification takes error_details: Dict, notification_recipients: List[String] returns Boolean
```

### 11.5 Multi-Agent Collaboration Utilities

```alloy
// Swarm management and coordination tools
tool create_swarm_with_pattern takes agent_list: List[Agent], pattern_name: String returns Swarm
tool execute_swarm_operation takes target_swarm: Swarm, operation_description: String, input_data: Any returns Result
tool monitor_swarm_performance takes target_swarm: Swarm returns Dict
tool optimize_swarm_configuration takes target_swarm: Swarm, performance_metrics: Dict returns Swarm

// Agent communication utilities
tool send_message_between_agents takes sender_agent: Agent, receiver_agent: Agent, message_content: Any returns Boolean
tool broadcast_to_swarm takes sender_agent: Agent, target_swarm: Swarm, broadcast_content: Any returns Boolean
tool request_information_from_agent takes requesting_agent: Agent, target_agent: Agent, information_request: String returns Result

// Pattern management
tool define_custom_collaboration_pattern takes pattern_name: String, pattern_definition: Dict returns Pattern
tool apply_pattern_to_swarm takes target_swarm: Swarm, collaboration_pattern: Pattern returns Swarm
tool analyze_pattern_effectiveness takes collaboration_pattern: Pattern, execution_history: List returns Dict
```

### 11.6 Memory Management Utilities

```alloy
// Memory operations and management
tool create_memory_store takes memory_type: String, access_permissions: List[String] returns Memory
tool query_memory_with_criteria takes target_memory: Memory, query_parameters: Dict returns List
tool optimize_memory_performance takes target_memory: Memory returns Memory
tool backup_memory_contents takes source_memory: Memory, backup_location: String returns Boolean
tool synchronize_shared_memory takes memory_stores: List[Memory] returns Boolean

// Memory analysis and insights
tool analyze_memory_usage_patterns takes target_memory: Memory, time_period: String returns Dict
tool identify_memory_optimization_opportunities takes target_memory: Memory returns List
tool generate_memory_usage_report takes agent_or_swarm: Any, report_format: String returns String
```

### 11.7 Meta-Programming Utilities

```alloy
// Code generation and optimization tools
tool generate_tool_from_specification takes requirement_specification: String, quality_criteria: Dict returns Tool
tool optimize_existing_tool takes target_tool: Tool, optimization_goals: List[String] returns Tool
tool validate_generated_code takes target_code: String, validation_criteria: Dict returns Dict
tool refactor_code_for_clarity takes source_code: String, refactoring_goals: List[String] returns String

// Workflow generation and management
tool create_workflow_from_description takes workflow_description: String, constraints: Dict returns Workflow
tool optimize_workflow_performance takes target_workflow: Workflow, performance_metrics: Dict returns Workflow
tool analyze_workflow_bottlenecks takes target_workflow: Workflow, execution_data: List returns Dict

// Self-improvement and reflection utilities
command ReflectOnPerformance means "Analyze recent performance data and identify improvement opportunities"
command OptimizeForEfficiency means "Improve the target system for better performance and resource usage"
command ValidateAgainstStandards means "Check the target against specified quality and compliance standards"
command GenerateImprovementPlan means "Create actionable plan for enhancing the target system or process"
```

---

## 12. Runtime Semantics

### 12.1 Execution Model

#### 12.1.1 Evaluation Order

1. **Eager Evaluation**: Most expressions are evaluated immediately
2. **Lazy Agent Calls**: Agent commands are only executed when their results are needed
3. **Async by Default**: All AI operations are asynchronous

#### 12.1.2 Memory Management

- **Garbage Collection**: Automatic memory management
- **Context Retention**: Agent conversation history is managed automatically
- **Resource Cleanup**: Tools and agents clean up resources when dereferenced

### 12.2 Scoping Rules

#### 12.2.1 Variable Scope

- **Global Scope**: Top-level definitions
- **Tool Scope**: Tool and command definitions create new scopes
- **Block Scope**: Control flow blocks create new scopes

#### 12.2.2 Agent Context Scope

- **Agent-Local**: Each agent maintains its own conversation context
- **Shared Tools**: Tools can be shared between agents
- **Context Isolation**: Agents cannot access each other's conversation history

### 12.3 Concurrency Model

#### 12.3.1 Async Operations

All AI operations are inherently async:

```alloy
// These run concurrently
async {
    result1 = claude Analyze data1
    result2 = claude Analyze data2
}

// Wait for completion
results = await [result1, result2]
```

#### 12.3.2 Thread Safety

- **Immutable Data**: Primitive values are immutable
- **Thing Isolation**: Each thing instance is isolated
- **Agent Safety**: Agents handle concurrent requests safely
- **Memory Synchronization**: Shared memory access is synchronized across agents
- **Swarm Coordination**: Swarm patterns handle agent coordination and resource contention

### 12.4 Multi-Agent Execution Semantics

#### 12.4.1 Swarm Execution Models

**Sequential Pattern Execution**:
1. Agent A executes with provided input
2. Upon completion, Agent A's output becomes Agent B's input
3. Process continues until all agents complete or error occurs
4. Early termination on any agent failure with error propagation

**Parallel Pattern Execution**:
1. All agents begin execution simultaneously with same or distributed input
2. Results collected as agents complete
3. Final result available when all agents finish
4. Failure handling: continue with partial results or fail-fast based on configuration

**Hierarchical Pattern Execution**:
1. Manager agent analyzes input and creates work distribution plan
2. Manager delegates tasks to worker agents
3. Worker agents execute in parallel
4. Manager synthesizes worker results into final output

#### 12.4.2 Memory Consistency Model

- **Session Memory**: Thread-local, no synchronization needed
- **Persistent Memory**: Write-through caching with eventual consistency
- **Shared Memory**: Strong consistency with optimistic locking
- **Memory Operations**: Atomic at the individual operation level
- **Cross-Agent Access**: Synchronized through memory access controls

#### 12.4.3 Communication Semantics

- **Message Passing**: Asynchronous by default with optional synchronous modes
- **Broadcast Operations**: Fan-out to all swarm members with delivery confirmation
- **Request-Response**: Timeout-based with configurable retry behavior
- **Communication Queues**: Per-agent message queues with priority handling

---

## 13. Implementation Notes

### 13.1 Parser Implementation

#### 13.1.1 Lexer Considerations

- **Context-Sensitive Keywords**: `with`, `from`, `then` behavior depends on context
- **Identifier Classification**: Capitalization determines command vs. variable
- **String Interpolation**: Support for variable substitution in strings

#### 13.1.2 Parser Architecture

```
Source Code
    ↓
Lexer → Token Stream
    ↓
Parser → Abstract Syntax Tree (AST)
    ↓
Semantic Analyzer → Annotated AST
    ↓
Code Generator → Bytecode/Runtime Calls
```

### 13.2 Runtime Implementation

#### 13.2.1 Core Components

- **Agent Manager**: Handles AI model connections and context
- **Tool Registry**: Manages available tools and their signatures
- **Result System**: Implements the Result[T] type and error propagation
- **Async Runtime**: Manages concurrent AI operations

#### 13.2.2 AI Integration

- **Model Abstraction**: Plugin system for different AI providers
- **Context Management**: Automatic conversation history tracking
- **Rate Limiting**: Built-in handling of API rate limits
- **Caching**: Intelligent caching of AI responses

### 13.3 Type System Implementation

#### 13.3.1 Dynamic Typing

- **Runtime Type Checking**: Validate types at operation time
- **Type Inference**: Infer types from usage patterns
- **Gradual Typing**: Optional type annotations for better tooling

#### 13.3.2 Result Type Implementation

```python
# Pseudo-implementation in Python
class Result:
    def __init__(self, value=None, error=None, confidence=None):
        self.value = value
        self.error = error
        self.confidence = confidence
    
    def is_success(self):
        return self.error is None
    
    def then(self, operation):
        if self.error is not None:
            return Result(error=self.error)
        return operation(self.value)
```

### 13.4 Standard Library Implementation

#### 13.4.1 Built-in Tools

Core tools should be implemented in the runtime's native language for performance:

- File I/O operations
- HTTP requests
- String manipulation
- Mathematical operations

#### 13.4.2 Extensibility

- **Plugin System**: Allow third-party tools and agents
- **Foreign Tool Interface**: Call native code from tools
- **Package Manager**: Distribute and install tool packages
- **Swarm Patterns**: Extensible collaboration pattern library
- **Memory Backends**: Pluggable memory storage systems
- **Communication Protocols**: Extensible agent communication mechanisms

---

## Appendix A: Grammar Reference

```ebnf
program ::= statement*

statement ::= 
    | agent_definition
    | thing_definition
    | tool_definition
    | command_definition
    | swarm_definition
    | pattern_definition
    | memory_definition
    | assignment
    | expression_statement
    | when_statement
    | while_statement
    | for_statement
    | async_block

agent_definition ::= identifier '=' 'agent' string_literal composition?
thing_definition ::= identifier '=' 'thing' property_list? composition?
tool_definition ::= 'tool' identifier parameter_list? return_clause? block
command_definition ::= 'command' command_identifier 'means' string_literal
swarm_definition ::= identifier '=' 'swarm' agent_list 'with' 'pattern' pattern_identifier
pattern_definition ::= identifier '=' 'pattern' 'where' pattern_body
memory_definition ::= identifier '=' 'memory' memory_type memory_properties?

assignment ::= identifier '=' expression
expression_statement ::= expression

when_statement ::= 'when' expression 'then' (block | statement) ('otherwise' (block | statement))?
while_statement ::= 'while' expression (block | statement)
for_statement ::= 'for' identifier 'in' expression (block | statement)
async_block ::= 'async' block

expression ::=
    | chain_expression
    | binary_expression
    | unary_expression
    | existence_check
    | communication_expression
    | memory_expression
    | meta_expression
    | primary_expression

existence_check ::= identifier 'exists' | identifier 'is_empty'

chain_expression ::= expression 'then' expression
binary_expression ::= expression binary_operator expression
unary_expression ::= unary_operator expression

primary_expression ::=
    | command_expression
    | meta_command_expression
    | dot_access
    | tool_call
    | data_extraction
    | identifier
    | literal
    | '(' expression ')' 

communication_expression ::= agent_ref communication_verb expression communication_target?
memory_expression ::= memory_operation
meta_expression ::= 'alloy' meta_command expression*

meta_command ::= 'Reflect' | 'Optimize' | 'Validate' | 'Review' | 'Generate'
communication_verb ::= 'Send' | 'Broadcast' | 'Request'
communication_target ::= 'to' agent_ref | 'from' agent_ref

memory_operation ::= agent_ref memory_verb memory_content memory_location?
memory_verb ::= 'Store' | 'Recall' | 'Forget' | 'Share'
memory_content ::= expression
memory_location ::= 'in' 'memory' | 'from' 'memory' | 'among' agent_list

pattern_body ::= pattern_statement*
pattern_statement ::= agent_action | condition_statement | workspace_statement
agent_action ::= identifier action_verb ('results' | expression) action_target
action_verb ::= 'sends' | 'receives' | 'broadcasts' | 'requests'
action_target ::= 'to' | 'from' | 'among'

memory_type ::= 'session' | 'persistent' | 'shared'
memory_properties ::= 'with' property_list
agent_list ::= identifier (',' identifier)*

command_expression ::= agent_ref (command_identifier expression* | agent_block)
agent_block ::= '{' agent_command_list '}'
agent_command_list ::= agent_command (',' agent_command)*
agent_command ::= ('must' | 'should') command_identifier expression*

dot_access ::= expression '.' identifier
tool_call ::= identifier '(' argument_list? ')'
data_extraction ::= identifier 'from' expression

composition ::= 'with' composition_list
composition_list ::= composition_item (',' composition_item)*
composition_item ::= identifier | property_assignment | memory_clause | block

memory_clause ::= 'memory' memory_list
memory_list ::= memory_item (',' memory_item)*
memory_item ::= identifier | memory_type_assignment
memory_type_assignment ::= memory_type identifier

property_list ::= 'with' property (',' property)*
property ::= identifier | property_assignment
property_assignment ::= identifier expression

parameter_list ::= 'takes' parameter (',' parameter)*
parameter ::= identifier type_hint?
type_hint ::= ':' type_name

return_clause ::= 'returns' type_name

argument_list ::= expression (',' expression)*

block ::= '{' statement* '}'

literal ::= string_literal | number_literal | boolean_literal | null_literal | list_literal | dict_literal

list_literal ::= '[' (expression (',' expression)*)? ']'
dict_literal ::= '{' (dict_entry (',' dict_entry)*)? '}'
dict_entry ::= (identifier | string_literal) ':' expression

binary_operator ::= '+' | '-' | '*' | '/' | '==' | '!=' | '<' | '>' | '<=' | '>=' | 'and' | 'or' | 'contains'
unary_operator ::= '!' | '-' | 'not'

memory_query ::= "where" (simple_condition | complex_condition)
simple_condition ::= field_condition ("and" | "or" field_condition)*
complex_condition ::= "{" condition_list "}"
condition_list ::= condition ("and" | "or" condition)*
condition ::= field_condition | command_condition
field_condition ::= IDENTIFIER operator value
command_condition ::= COMMAND_IDENTIFIER parameter_list
operator ::= "==" | "!=" | ">" | "<" | ">=" | "<=" | "contains" | "starts_with" | "ends_with"
```

---

## Appendix B: Agent-Generated Code Examples

These examples demonstrate how AI agents naturally generate Alloy code with verbose, self-documenting patterns:

### B.1 Agent-Generated Data Processing Pipeline

```alloy
// Agent naturally generates descriptive variable names and comprehensive error handling
data_processor = agent "claude-3.5-sonnet" with {
    temperature_setting: 0.1,
    maximum_tokens_per_response: 2000
}

tool validate_input_data_structure takes input_data: Dict returns validation_result {
    when input_data is_empty then {
        validation_result = (null, "Input data structure cannot be empty for processing")
    } otherwise {
        required_fields = ["user_id", "timestamp", "event_data"]
        for required_field_name in required_fields {
            when not input_data.contains(required_field_name) then {
                validation_result = (null, "Missing required field in input data: " + required_field_name)
            }
        }
        validation_result = true
    }
}

command ProcessUserEventData means "Analyze user event data for patterns, anomalies, and actionable insights"
command GenerateDataQualityReport means "Create comprehensive report on data quality, completeness, and reliability"

// Main processing tool with agent-friendly explicit naming
tool process_user_events_comprehensively takes raw_event_data: List[Dict] returns Dict {
    processed_events_collection = []
    data_quality_issues = []
    processing_statistics = {
        total_events_processed: 0,
        successful_validations: 0,
        failed_validations: 0,
        processing_errors: 0
    }
    
    for individual_event_record in raw_event_data {
        // Validate each event with comprehensive error tracking
        validation_result, validation_error = validate_input_data_structure(individual_event_record)
        processing_statistics.total_events_processed = processing_statistics.total_events_processed + 1
        
        when validation_error exists then {
            processing_statistics.failed_validations = processing_statistics.failed_validations + 1
            data_quality_issues.append({
                event_index: processing_statistics.total_events_processed,
                error_type: "validation_failure",
                error_message: validation_error.message,
                problematic_data: individual_event_record
            })
            continue
        }
        
        processing_statistics.successful_validations = processing_statistics.successful_validations + 1
        
        // Process valid events with agent analysis
        event_analysis_result, analysis_error = data_processor ProcessUserEventData individual_event_record
        when analysis_error exists then {
            processing_statistics.processing_errors = processing_statistics.processing_errors + 1
            data_quality_issues.append({
                event_index: processing_statistics.total_events_processed,
                error_type: "analysis_failure",
                error_message: analysis_error.message,
                event_data: individual_event_record
            })
            continue
        }
        
        processed_event_with_insights = {
            original_event_data: individual_event_record,
            ai_generated_insights: event_analysis_result.value,
            analysis_confidence_score: event_analysis_result.confidence,
            processing_timestamp: get_current_timestamp()
        }
        
        processed_events_collection.append(processed_event_with_insights)
    }
    
    // Generate comprehensive quality report
    quality_report_result, quality_report_error = data_processor GenerateDataQualityReport {
        processing_statistics: processing_statistics,
        data_quality_issues: data_quality_issues,
        total_processed_events: processed_events_collection.length
    }
    
    return {
        successfully_processed_events: processed_events_collection,
        data_quality_issues_encountered: data_quality_issues,
        processing_statistics_summary: processing_statistics,
        comprehensive_quality_report: quality_report_result.value,
        pipeline_execution_status: "completed_successfully"
    }
}
```

### B.2 Agent-Generated API Integration

```alloy
// Agents naturally create comprehensive API integration with full error handling
api_integration_service = thing with {
    base_api_url: "https://api.example.com",
    api_authentication_token: "",
    request_timeout_seconds: 30,
    maximum_retry_attempts: 3
} with agent "claude-3.5-sonnet"

tool authenticate_with_external_api takes api_credentials: Dict returns access_token {
    authentication_request_payload = {
        username: api_credentials.username,
        password: api_credentials.password,
        grant_type: "client_credentials"
    }
    
    authentication_response, request_error = perform_http_post_request(
        api_integration_service.base_api_url + "/oauth/token",
        authentication_request_payload
    )
    
    when request_error exists then {
        access_token = (null, "Failed to authenticate with external API: " + request_error.message)
    } otherwise when not authentication_response.contains("access_token") then {
        access_token = (null, "Authentication response missing required access token")
    } otherwise {
        access_token = authentication_response.access_token
    }
}

tool fetch_user_profile_data takes user_identifier: String, access_token: String returns profile_data {
    request_headers = {
        "Authorization": "Bearer " + access_token,
        "Content-Type": "application/json",
        "User-Agent": "Alloy-Agent/1.0"
    }
    
    profile_request_url = api_integration_service.base_api_url + "/users/" + user_identifier + "/profile"
    
    user_profile_response, fetch_error = retry_operation_with_limit(
        perform_http_get_request(profile_request_url, request_headers),
        api_integration_service.maximum_retry_attempts
    )
    
    when fetch_error exists then {
        profile_data = (null, "Failed to fetch user profile data after maximum retry attempts: " + fetch_error.message)
    } otherwise {
        profile_data = user_profile_response
    }
}
```

### B.3 Agent vs Human Code Comparison

**Traditional Human-Optimized Code:**
```alloy
// Terse, assumes context
user = get_user(id)
when not user exists then { return err }
prefs = user.prefs || []
recs = ai.recommend(prefs)
return recs
```

**Agent-Optimized Alloy Code:**
```alloy
// Explicit, self-documenting, comprehensive
user_profile_data, user_fetch_error = fetch_complete_user_profile(user_identifier)
when user_fetch_error exists then {
    log_error_with_context(user_fetch_error, "user_profile_retrieval")
    return error "Cannot generate recommendations without user profile data: " + user_fetch_error.message
}

user_preference_settings = user_profile_data.preference_settings
when user_preference_settings is_empty then {
    user_preference_settings = generate_default_preferences_for_user(user_profile_data)
}

personalized_recommendations, recommendation_error = recommendation_agent GeneratePersonalizedProductRecommendations {
    user_preferences: user_preference_settings,
    user_profile: user_profile_data,
    recommendation_context: "product_discovery"
}

when recommendation_error exists then {
    return error "Recommendation generation failed: " + recommendation_error.message
}

return personalized_recommendations
```

**Key Differences:**
- **39 vs 6 lines**: Agent code is verbose but completely self-explanatory
- **Zero ambiguity**: Every operation's purpose is immediately clear
- **Complete error handling**: All failure modes are explicitly managed
- **Self-documenting**: No external documentation needed to understand code
- **Maintenance ready**: Changes are safe because intent is explicit

See Section 7 for additional comprehensive examples demonstrating real-world usage patterns.

---

---

## Implementation Philosophy

### Start Simple, Evolve Approach

Alloy adopts a "start simple, evolve" implementation philosophy that allows for progressive enhancement while maintaining clean, usable foundations:

**Phase 1: Direct API Calls with Must/Should Semantics (Current Focus)**
- Direct API calls with must/should semantics for agent blocks
- System prompt synthesis for agent definitions
- Clean provider abstraction (OpenAI, Anthropic, Groq, etc.)
- Implicit variable access in agent blocks
- Then chaining integration

**Phase 2: Tool Calling Support**
- Native tool calling for supported providers
- Automatic tool registration and parameter binding
- Tool result integration with agent outputs

**Phase 3: Iteration/Loops within Agent Blocks**
- For loops and conditional execution within agent blocks
- Complex multi-step reasoning patterns
- State management across iterations

**Phase 4: MCP Integration**
- Model Context Protocol support for advanced tool ecosystems
- Standardized tool discovery and integration
- Cross-provider tool compatibility

**Phase 5: Advanced Agent Patterns**
- Self-modification and learning capabilities
- Dynamic agent generation and optimization
- Advanced swarm intelligence patterns

**Provider Abstraction Benefits:**
- Clean interface allows switching between AI providers seamlessly
- Consistent behavior regardless of underlying model architecture
- Future-proof design accommodating new providers and capabilities
- Standardized error handling and result patterns across all providers

---

## Version 3.3 Changelog

### Major Updates

**Agent Definition with System Prompts:**
- Added support for agent definitions with system prompt blocks using `must` and `should` statements
- `must` statements become core system prompt requirements
- `should` statements become contextual system prompt preferences
- System prompt synthesis for all agent interactions

**Agent Block Execution Semantics:**
- Clarified agent block execution model: implicit variable access, single combined input, one API call
- Enhanced must/should distinction in execution context vs system prompt context
- Added comprehensive examples of agent blocks with then chaining integration
- Detailed data flow documentation for agent block operations

**Implementation Philosophy Documentation:**
- Added "start simple, evolve" approach with 5-phase roadmap
- Phase 1: Direct API calls with must/should semantics (current focus)
- Provider abstraction design for clean switching between AI providers
- Future-proofing for tool calling, MCP integration, and advanced patterns

**Grammar and Syntax Updates:**
- Extended agent definition grammar to support system prompt blocks
- Added system_prompt_block and system_prompt_statement production rules
- Enhanced agent_command grammar for both execution and definition contexts
- Updated composition rules to include system prompt blocks

**Comprehensive Examples:**
- Added agent definition examples with system prompts
- Enhanced agent block execution examples with real-world contexts
- Demonstrated then chaining integration with agent blocks
- Real-world usage patterns with implicit variable access

### Design Philosophy Enhancement

**Agent Block Clarity:**
- Distinguished between system prompt context (agent definition) and execution context (agent blocks)
- Clarified single API call model with combined prompt synthesis
- Enhanced documentation of implicit variable access patterns

**Evolution Strategy:**
- Documented progressive enhancement approach from simple API calls to advanced patterns
- Provider abstraction enables future scalability and flexibility
- Clean foundations support incremental feature addition

---

*This specification is version 3.3 of the Alloy language, featuring comprehensive agent block semantics with system prompt support, clear execution models, and a progressive implementation philosophy. The language maintains its Agent-First Design principles while establishing foundations for scalable AI integration patterns. Agent definitions now support system prompts with must/should semantics, and agent blocks provide implicit variable access with single API call execution. For updates and community contributions, visit the official repository.*