# Alloy MVP Specification

## MVP Philosophy

This MVP specification defines the minimum viable product for Alloy that validates our core thesis: **agent-first verbosity enables reliable AI/deterministic code integration**. The MVP focuses on implementability over completeness, targeting a working prototype that can be built in weeks rather than months.

### What the MVP Validates
- Agent-first verbosity makes code more readable and maintainable
- AI agents can be seamlessly integrated with deterministic code
- The syntax decisions (brackets, naming conventions, error handling) work in practice
- The language provides a foundation for future expansion

### What Success Looks Like
- Complete programs can be written and executed
- AI agents work reliably within deterministic control flow
- Error handling is consistent and predictable
- The syntax feels natural for both AI and human developers

## Core Language Features

### Primitive Types
```alloy
// Strings
message = "Hello, world!"
multiline_text = """
This is a multi-line string
that can span multiple lines
"""

// Numbers
count = 42
price = 19.99
negative = -10

// Booleans
is_ready = true
is_complete = false

// Arrays
numbers = [1, 2, 3, 4, 5]
mixed_items = ["hello", 42, true]
empty_list = []

// Objects
person = {
    name: "Alice",
    age: 30,
    active: true
}
```

### Variables and Assignment
```alloy
// Basic assignment
user_name = "Alice"
user_age = 30

// Reassignment
user_age = 31

// Computed values
full_name = user_name + " Smith"
is_adult = user_age >= 18
```

### Tools
```alloy
// Basic tool definition
tool calculate_tax takes amount, rate returns tax_result {
    tax_result = amount * rate
    return tax_result
}

// Tool with multiple statements
tool process_order takes order returns order_result {
    tax_amount = calculate_tax(order.subtotal, 0.08)
    total = order.subtotal + tax_amount
    order_result = {
        subtotal: order.subtotal,
        tax: tax_amount,
        total: total
    }
    return order_result
}

// Tool calls
tax = calculate_tax(100, 0.08)
final_order = process_order({subtotal: 100, items: ["book"]})
```

### Control Flow

#### Conditionals
```alloy
// Single statement (inline)
status = when user_age >= 18 then "adult" otherwise "minor"

// Multiple statements (brackets required)
user_status = when user_age >= 18 then {
    access_level = "full"
    can_vote = true
    return "adult"
} otherwise {
    access_level = "limited"
    can_vote = false
    return "minor"
}
```

#### Loops
```alloy
// For loop (single statement)
for item in items do process_item(item)

// For loop (multiple statements)
for item in items do {
    processed = process_item(item)
    results.push(processed)
}

// While loop
while count < 10 do {
    count = count + 1
    process_count(count)
}
```

### Error Handling (Result Pattern)
```alloy
// Tools return (result, error) tuples
tool parse_number takes text returns number_result {
    when is_numeric(text) then {
        number_result = (parse_float(text), null)
        return number_result
    } otherwise {
        number_result = (null, "Invalid number format")
        return number_result
    }
}

// Error handling in calls
(number, error) = parse_number("42")
when error != null then {
    return ("Error: " + error, null)
}
```

### Basic Chaining
```alloy
// Chain operations with then
result = get_data() 
    then process_data()
    then format_output()

// Chain with error handling
(final_result, error) = get_data()
    then process_data()
    then validate_result()
    
when error != null then {
    log_error(error)
    return default_result()
}
```

## AI Integration

### Must/Should Semantics

Agent blocks use explicit semantic keywords to define execution requirements:

- **must** = this command must always execute (required execution)
- **should** = this command should execute if appropriate for the input/context (conditional execution based on agent's judgment)

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

```alloy
analysis = analyst {
    must Load data        // Always execute regardless of input
    must Calculate statistics        // Always execute regardless of input
    should Identify trends       // Execute if appropriate for the input/context
    should Suggest recommendations         // Execute if appropriate for the input/context
}
```

### Built-in Alloy Agent

The `alloy` agent provides meta-programming capabilities for self-improving code:

```alloy
// Built-in alloy agent for meta-programming
code_review = alloy Review tool_code for improvements
optimized_tool = alloy Generate tool for requirement: "sort users efficiently"
reflection = alloy Reflect on analysis_result with criteria: "accuracy, completeness"

// Alloy agent blocks
improvement = alloy {
    must Analyze current_code
    must Generate optimized_version
    should Provide change_explanation
    should Include test_cases
    data: current_implementation
}
```

### Agent Definition
```alloy
// Create agents with clean syntax
data_analyst = agent "gpt-4"
text_processor = agent "claude-3-sonnet"
researcher = agent "claude-3.5-sonnet" with tools web_search, read_files

// Built-in alloy agent for meta-programming
code_reviewer = alloy
```

### Agent Commands
```alloy
// Single command execution
summary = data_analyst Analyze this data and provide insights: {data_string}

// Command with error handling
(analysis, error) = data_analyst Summarize these sales figures: {sales_data}
when error != null then {
    return ("Analysis failed: " + error, null)
}

// Alloy agent meta-programming
code_review = alloy Review tool_code for improvements
optimized_tool = alloy Generate tool for requirement: "sort users efficiently"
```

### Agent Blocks
```alloy
// Multi-command blocks with execution requirement semantics
analysis_result = data_analyst {
    must Load provided_data
    must Calculate basic_statistics
    must Identify patterns_anomalies
    should Provide trend_insights
    should Suggest investigation_areas
    data: sales_data
}

// Block with error handling
(report, error) = text_processor {
    must Clean text_data
    must Normalize text
    must Split sentences
    should Identify data_quality_issues
    data: raw_text
}

// Alloy agent for reflection and optimization
reflection = alloy {
    must Reflect analysis_result
    should Suggest analysis_improvements
    data: analysis_result
}
```

### Tool/Command Distinction
```alloy
// Lowercase = deterministic tools
cleaned_data = clean_text(raw_data)
count = calculate_length(text)

// Clean agent syntax for AI commands
summary = analyst Summarize this data
insights = researcher {
    must Analyze trends
    should Identify patterns
}

// Alloy agent commands
optimized_code = alloy Optimize tool for performance: {tool_code}
```

## Complete MVP Examples

### Data Processing Pipeline
```alloy
// Define tools
tool clean_csv_data takes raw_data returns cleaned_result {
    lines = raw_data.split("\n")
    cleaned_lines = []
    for line in lines do {
        trimmed = line.trim()
        when trimmed.length > 0 then {
            cleaned_lines.push(trimmed)
        }
    }
    cleaned_result = cleaned_lines
    return cleaned_result
}

// Define agent
data_analyst = agent "gpt-4"

// Main pipeline
tool process_sales_data takes raw_csv returns pipeline_result {
    // Clean data deterministically
    (cleaned_data, clean_error) = clean_csv_data(raw_csv)
    when clean_error != null then {
        pipeline_result = (null, "Data cleaning failed: " + clean_error)
        return pipeline_result
    }
    
    // Analyze with AI
    (analysis, analysis_error) = data_analyst {
        must Parse csv_data
        must Calculate monthly_sales
        must Identify performance_months
        should Provide seasonal_insights
        should Suggest improvements
        data: cleaned_data
    }
    
    when analysis_error != null then {
        pipeline_result = (null, "Analysis failed: " + analysis_error)
        return pipeline_result
    }
    
    pipeline_result = (analysis, null)
    return pipeline_result
}

// Usage
raw_sales_data = load_file("sales.csv")
(report, error) = process_sales_data(raw_sales_data)
when error != null then {
    log_error(error)
    return "Processing failed"
}
output_report(report)
```

### Simple Research Assistant
```alloy
// Define research agent
researcher = agent "claude-3-sonnet" with tools web_search, read_files

// Research tool
tool research_topic takes topic, sources returns research_result {
    // Validate inputs
    when topic.length == 0 then {
        research_result = (null, "Topic cannot be empty")
        return research_result
    }
    
    // Gather information
    (research_results, research_error) = researcher {
        must Research topic
        must Summarize findings
        must Identify main_points
        should Include examples
        should Note conflicting_info
        should Suggest investigation_areas
        data: {
            topic: topic,
            sources: sources
        }
    }
    
    when research_error != null then {
        research_result = (null, "Research failed: " + research_error)
        return research_result
    }
    
    // Format output
    formatted_report = format_research_report(research_results)
    research_result = (formatted_report, null)
    return research_result
}

// Usage
available_sources = ["academic papers", "news articles", "documentation"]
(report, error) = research_topic("machine learning trends 2024", available_sources)
when error != null then {
    return "Research failed: " + error
}
save_report(report)
```

### Self-Improving Analysis Pipeline
```alloy
// Define agents
analyzer = agent "claude-3.5-sonnet"
optimizer = alloy

// Self-improving analysis tool
tool analyze_with_improvement takes data, analysis_method returns analysis_result {
    // Initial analysis
    (initial_result, error) = analyzer {
        must Analyze provided_data
        must Generate insights
        should Include confidence_scores
        data: {
            raw_data: data,
            method: analysis_method
        }
    }
    
    when error != null then {
        analysis_result = (null, "Initial analysis failed: " + error)
        return analysis_result
    }
    
    // Meta-analysis for improvement
    (improvement_suggestions, improvement_error) = optimizer {
        must Review analysis_results
        must Identify improvement_gaps
        should Generate analysis_strategy
        should Provide insight_recommendations
        data: {
            original_analysis: initial_result,
            method_used: analysis_method
        }
    }
    
    when improvement_error != null then {
        // Return initial result if improvement fails
        analysis_result = (initial_result, null)
        return analysis_result
    }
    
    // Apply improvements if suggested
    when improvement_suggestions.has_improvements then {
        (improved_result, final_error) = analyzer {
            must Re-analyze data
            must Incorporate previous_findings
            should Compare initial_analysis
            data: {
                raw_data: data,
                improved_method: improvement_suggestions.new_method,
                previous_result: initial_result
            }
        }
        
        when final_error != null then {
            analysis_result = (initial_result, null)  // Fallback to initial
            return analysis_result
        }
        
        analysis_result = (improved_result, null)
        return analysis_result
    }
    
    analysis_result = (initial_result, null)
    return analysis_result
}

// Usage
market_data = load_market_data("2024-q1")
(analysis, error) = analyze_with_improvement(market_data, "trend_analysis")
when error != null then {
    log_error(error)
    return "Analysis failed"
}
generate_report(analysis)
```

## Simplified Grammar

### Core Syntax
```
program = statement*

statement = assignment | tool_def | control_flow | expression

assignment = IDENTIFIER "=" expression

tool_def = "tool" IDENTIFIER "takes" param_list "returns" IDENTIFIER block

control_flow = when_statement | for_statement | while_statement

when_statement = "when" expression "then" statement_or_block "otherwise" statement_or_block

for_statement = "for" IDENTIFIER "in" expression "do" statement_or_block

while_statement = "while" expression "do" statement_or_block

statement_or_block = statement | "{" statement* "}"

expression = literal | identifier | tool_call | agent_command | agent_block | binary_op | chain_op

agent_command = agent_ref command_text

agent_block = agent_ref "{" agent_statement* "}"

agent_ref = "agent" STRING | "agent" STRING "with" "tools" tool_list | "alloy"

agent_statement = ("must" | "should") command_text | "data" ":" expression

chain_op = expression "then" expression

binary_op = expression OPERATOR expression

literal = STRING | NUMBER | BOOLEAN | array | object

array = "[" (expression ("," expression)*)? "]"

object = "{" (IDENTIFIER ":" expression ("," IDENTIFIER ":" expression)*)? "}"
```

### Agent-Specific Syntax
```
agent_def = "agent" STRING ("with" "tools" tool_list)?

alloy_agent = "alloy"

agent_block = agent_ref "{" agent_statement* "}"

agent_statement = must_statement | should_statement | data_statement

must_statement = "must" command_text

should_statement = "should" command_text

data_statement = "data" ":" expression

tool_list = IDENTIFIER ("," IDENTIFIER)*

command_text = STRING | interpolated_string | raw_text
```

## Implementation Notes

### Phase 1: Core Language (Week 1-2)
- Lexer and parser for clean syntax
- Variable assignment and scoping
- Primitive types and basic operations
- Tool definition and calling
- Control flow (when/then/otherwise, for, while)
- Clean agent syntax parsing

### Phase 2: Error Handling (Week 3)
- Result pattern implementation
- Error tuple returns from tools
- Error propagation through chains
- Basic error handling in control flow

### Phase 3: AI Integration (Week 4-5)
- Clean agent creation syntax
- Command execution with LLM API calls
- Block execution with must/should execution requirements
- Built-in alloy agent for meta-programming
- Error handling for AI operations

### Phase 4: Integration & Testing (Week 6)
- End-to-end pipeline testing
- Real-world example validation
- Performance and reliability testing
- Documentation and examples

### Required Infrastructure
- LLM API integration (OpenAI, Anthropic)
- Built-in alloy agent system
- Basic runtime environment
- Error handling system
- Simple standard library (file I/O, string manipulation)
- Clean syntax parser and interpreter

## Success Criteria

### Technical Validation
- [ ] Complete programs can be written and executed
- [ ] AI agents integrate seamlessly with deterministic code
- [ ] Error handling works consistently across AI and deterministic operations
- [ ] Chaining operations work reliably
- [ ] Performance is acceptable for prototype validation

### Language Design Validation
- [ ] Agent-first verbosity makes code more readable
- [ ] Syntax decisions feel natural in practice
- [ ] Error patterns are intuitive and helpful
- [ ] The language provides good foundation for expansion

### Practical Validation
- [ ] Real data processing pipelines work end-to-end
- [ ] AI analysis integrates smoothly with data preparation
- [ ] Error handling prevents cascading failures
- [ ] Code is maintainable and debuggable

## What's Explicitly Deferred

### Advanced Features (Post-MVP)
- Multi-agent collaboration and swarms
- Memory primitives and state management
- Advanced agent composition beyond alloy agent
- Complex concurrency patterns
- Module system and imports
- Static type system
- Performance optimizations

### Complex AI Integration
- Agent training and fine-tuning
- Multi-modal agent support
- Advanced prompt engineering features
- Agent capability negotiation
- Dynamic agent selection

### Enterprise Features
- Security and sandboxing
- Monitoring and observability
- Distributed execution
- Package management
- IDE integration

The MVP focuses on proving the core language concepts work in practice. These advanced features will be added in subsequent versions once the foundation is validated.