### Execute Workflows via CLI Source: https://github.com/shopify/roast/blob/main/tutorial/01_your_first_workflow/README.md Run defined Roast workflow files from the terminal using the bin/roast utility. ```bash bin/roast execute tutorial/01_your_first_workflow/hello.rb bin/roast execute tutorial/01_your_first_workflow/configured_chat.rb ``` -------------------------------- ### Execute Example Workflows (Bash) Source: https://github.com/shopify/roast/blob/main/tutorial/03_targets_and_params/README.md Provides example bash commands to run the single target and multiple targets with arguments workflows discussed in the chapter. ```bash # Single target workflow (with a URL) bin/roast execute tutorial/03_targets_and_params/single_target.rb https://example.com ``` ```bash # Multiple targets with arguments bin/roast execute tutorial/03_targets_and_params/multiple_targets.rb \ Gemfile Gemfile.lock -- save_data format=summary ``` -------------------------------- ### Execute Roast Workflow Example Source: https://github.com/shopify/roast/blob/main/tutorial/04_configuration_options/README.md Command to run a Roast workflow script from the terminal. This example shows how to execute a specific Ruby file located within the tutorial directory. ```bash bin/roast execute tutorial/04_configuration_options/simple_config.rb ``` -------------------------------- ### Bash: Run Shopify Roast iterative workflow examples Source: https://github.com/shopify/roast/blob/main/tutorial/08_iterative_workflows/README.md Provides bash commands to execute example iterative workflows using the Shopify Roast CLI. These examples demonstrate basic iterative transformations and conditional termination using `break!`. ```bash # Basic iterative transformation bin/roast execute tutorial/08_iterative_workflows/basic_repeat.rb ``` ```bash # Using break! to terminate based on conditions bin/roast execute tutorial/08_iterative_workflows/conditional_break.rb ``` -------------------------------- ### Execute Workflow Tutorials Source: https://github.com/shopify/roast/blob/main/tutorial/06_reusable_scopes/README.md Command-line examples for running the tutorial workflows associated with reusable scopes. ```bash bin/roast execute tutorial/06_reusable_scopes/basic_scope.rb bin/roast execute tutorial/06_reusable_scopes/parameterized_scope.rb bin/roast execute tutorial/06_reusable_scopes/accessing_scope_outputs.rb ``` -------------------------------- ### Configure LLM Settings Source: https://github.com/shopify/roast/blob/main/tutorial/01_your_first_workflow/README.md Use the config block to specify the model, provider, and display settings for the chat cog. ```ruby config do chat do model "gpt-4o-mini" provider :openai show_prompt! end end execute do chat do <<~PROMPT Explain what an AI workflow is in simple terms. PROMPT end end ``` -------------------------------- ### WriteFile Tool Usage Example Source: https://github.com/shopify/roast/blob/main/docs/INSTRUMENTATION.md An example of how to use the WriteFile tool within a Roast prompt to write content to a specified file. The tool will create the file if it doesn't exist or overwrite it if it does. ```ruby # Example usage in a prompt write_file(path: "output.txt", content: "This is the file content") ``` -------------------------------- ### UpdateFiles Tool Usage Example with Diff Source: https://github.com/shopify/roast/blob/main/docs/INSTRUMENTATION.md Demonstrates the usage of the UpdateFiles tool to apply a unified diff/patch to one or more files. This example shows how to provide a multi-line diff string and specifies creating new files if they don't exist. ```ruby # Example usage in a prompt update_files(diff: <<~DIFF, base_path: "/path/to/project", create_files: true) ---\n a/file1.txt +++\n a/file1.txt @@ -1,3 +1,4 @@\n line1 +new line line2 line3 \n ---\n a/file2.txt +++\n a/file2.txt @@ -5,7 +5,7 @@\n line5 line6 -old line7 +updated line7 line8 DIFF ``` -------------------------------- ### Multi-Line Description Example in Ruby Source: https://github.com/shopify/roast/blob/main/internal/documentation/doc-comments-external.md Shows how to provide more detailed explanations for a Ruby method using multiple comment lines. Paragraphs are separated by blank lines, and each line after the first should be a complete sentence. ```ruby # Get the validated provider name that the cog is configured to use when invoking an agent # # Note: this method will return the name of a valid provider or raise an `InvalidConfigError`. # It will not, however, validate that the agent is properly installed on your system. # If the agent is not properly installed, you will likely experience a failure when Roast attempts to # run your workflow. # #: () -> Symbol def valid_provider! # implementation end ``` -------------------------------- ### Documenting Ruby Configuration Methods Source: https://github.com/shopify/roast/blob/main/internal/documentation/doc-comments.md An example of how to document configuration methods in Ruby, specifically for cog providers. It includes a description of the method's purpose, default behavior, prerequisites, and cross-references. ```ruby # Configure the cog to use a specified provider when invoking an agent # # The provider is the source of the agent tool itself. # If no provider is specified, Anthropic Claude Code (`:claude`) will be used as the default provider. # # A provider must be properly installed on your system in order for Roast to be able to use it. # # #### See Also # - `use_default_provider!` # #: (Symbol) -> void def provider(provider) @values[:provider] = provider end ``` -------------------------------- ### Configure Cogs Using Pattern Matching Source: https://github.com/shopify/roast/blob/main/tutorial/04_configuration_options/README.md Apply configuration to multiple cogs simultaneously using a regular expression pattern. This example configures all chat cogs whose names start with 'analyze_' to use the 'gpt-4o' model. ```ruby config do chat do model "gpt-4o-mini" provider :openai end # All cogs with names matching this pattern use gpt-4o chat(/analyze_/) do model "gpt-4o" end end execute do chat(:extract_data) { "..." } # Uses gpt-4o-mini chat(:analyze_deep) { "..." } # Uses gpt-4o (matches pattern) chat(:analyze_trends) { "..." } # Uses gpt-4o (matches pattern) end ``` -------------------------------- ### One-Line Description Example in Ruby Source: https://github.com/shopify/roast/blob/main/internal/documentation/doc-comments-external.md Illustrates a concise, action-oriented one-line description for a Ruby method. This description should be imperative and not end with a period, providing a quick understanding of the method's purpose. ```ruby # Configure the cog to write STDOUT to the console #: () -> void def show_stdout! @values[:show_stdout] = true end ``` -------------------------------- ### Define configuration context interface Source: https://github.com/shopify/roast/blob/main/internal/documentation/doc-comments-external.md Provides the structure for documenting user-facing configuration methods in .rbi shims. This includes usage examples and categorized options for cog configuration. ```ruby def agent(name = nil, &block); end ``` -------------------------------- ### Ruby Validation Getter Method Example Source: https://github.com/shopify/roast/blob/main/internal/documentation/doc-comments-external.md Provides an example of a validation getter method in Ruby, following the `valid_*!` pattern. This method retrieves and validates the working directory path, raising an `InvalidConfigError` if the path is invalid or does not exist. ```ruby # Get the validated, configured value for the working directory path in which the cog should run the agent # # This method will raise an `InvalidConfigError` if the path does not exist or is not a directory. # # #### See Also ``` -------------------------------- ### Interact with LLMs using the Chat Cog Source: https://github.com/shopify/roast/blob/main/tutorial/01_your_first_workflow/README.md The chat cog allows sending prompts to LLMs. Examples include simple strings, multi-line heredocs, and template-based prompts. ```ruby execute do chat { "Say hello!" } end execute do chat do <<~PROMPT You are a helpful AI assistant. Please introduce yourself and explain what Roast is in 2-3 sentences. Keep your response friendly and concise. PROMPT end end execute do chat { template("path_to_prompt_file.md.erb", { context: }) } end ``` -------------------------------- ### Documenting Default Behavior in Ruby Source: https://github.com/shopify/roast/blob/main/internal/documentation/doc-comments-external.md Illustrates how to document default behavior for methods in Ruby. The example shows a method that configures the cog to strip whitespace, with the default behavior clearly stated as `true` in the documentation. ```ruby # Configure the cog to strip surrounding whitespace from the values in its output object # # Default: `true` # #: () -> void def clean_output! @values[:raw_output] = false end ``` -------------------------------- ### Define and Execute Roast Workflow Source: https://github.com/shopify/roast/blob/main/tutorial/01_your_first_workflow/README.md A standard Roast workflow structure using a configuration block to define behavior and an execute block to contain the primary workflow logic. It utilizes the chat cog for LLM interaction and supports multi-line prompts using heredoc syntax. ```ruby config do # Cog configuration goes here end execute do chat <<~PROMPT Your prompt text here PROMPT end ``` -------------------------------- ### Install Roast via RubyGems Source: https://github.com/shopify/roast/blob/main/README.md Provides instructions for installing the Roast gem directly or adding it to a project's Gemfile. ```bash gem install roast-ai ``` ```ruby gem 'roast-ai' ``` -------------------------------- ### Documenting Nil Handling for Parameters in Ruby Source: https://github.com/shopify/roast/blob/main/internal/documentation/doc-comments-external.md Explains how to document the meaning of `nil` values when used as parameters or configuration states in Ruby. This example shows a method for configuring the agent model, where passing `nil` signifies using the provider's default model. ```ruby # Configure the cog to use a specific model when invoking the agent # # Pass `nil` to use the provider's default model configuration. # #: (String?) -> void def model(model) @values[:model] = model end ``` -------------------------------- ### Define Agent Step Best Practices Source: https://github.com/shopify/roast/blob/main/docs/AGENT_STEPS.md Examples of how to structure agent instructions for code modification, including explicit tool usage, line-number targeting, and formatting constraints. ```markdown # Good agent step Use MultiEdit tool to update the following files: - app/models/user.rb: Add validation - test/models/user_test.rb: Add test case ``` ```markdown # Good agent step In app/controllers/application_controller.rb: - Find method `authenticate_user!` (around line 45) - Add the following before the redirect_to call: session[:return_to] = request.fullpath ``` ```markdown # Good agent step Create method with exactly this signature: def calculate_tax(amount, rate = 0.08) Ensure: - Two-space indentation - No trailing whitespace - Blank line before method definition ``` -------------------------------- ### Retrieve RubyLLM Context Source: https://github.com/shopify/roast/blob/main/internal/documentation/doc-comments-internal.md Example of documenting a method that requires additional context regarding its lifecycle, such as lazy initialization and caching, while maintaining a clean interface definition. ```ruby # Get the RubyLLM context configured for this chat cog # # Returns a cached context object that is lazily initialized on first access # and reused for subsequent calls. # #: () -> RubyLLM::Context def ruby_llm_context @ruby_llm_context ||= RubyLLM.context do |context| context.openai_api_key = config.valid_api_key! context.openai_api_base = config.valid_base_url end end ``` -------------------------------- ### Documenting Error Conditions in Ruby Source: https://github.com/shopify/roast/blob/main/internal/documentation/doc-comments-external.md Shows how to document methods that may raise errors in Ruby. This example describes a method that retrieves a validated provider name, noting that it will raise an `InvalidConfigError` if the provider is invalid. ```ruby # Get the validated provider name that the cog is configured to use when invoking an agent # # Note: this method will return the name of a valid provider or raise an `InvalidConfigError`. # It will not, however, validate that the agent is properly installed on your system. # #: () -> Symbol def valid_provider! # implementation end ``` -------------------------------- ### Migrating Ruby Expressions in Roast Workflows Source: https://github.com/shopify/roast/blob/main/docs/ITERATION_SYNTAX.md Provides an example of migrating existing Roast workflows by wrapping Ruby expressions in the new `{{...}}` syntax for 'until' conditions, ensuring compatibility with standardized iteration inputs. ```yaml # Old # until: "output['counter'] >= 5" # New # until: "{{output['counter'] >= 5}}" ``` -------------------------------- ### Configure Multiple Cog Types Globally Source: https://github.com/shopify/roast/blob/main/tutorial/04_configuration_options/README.md Define default configurations for different cog types within a single 'config' block. This example sets defaults for both 'chat' and 'agent' cogs, specifying their respective models and providers. ```ruby config do chat do model "gpt-4o-mini" provider :openai end agent do model "claude-3-5-haiku-20241022" provider :claude end end ``` -------------------------------- ### Control Display Options for Chat and Agent Cogs Source: https://github.com/shopify/roast/blob/main/tutorial/04_configuration_options/README.md Manage the visibility of prompts, responses, and statistics for chat and agent cogs. This example hides all responses by default but explicitly shows the response for a specific 'summarize' cog. ```ruby config do chat do no_show_response! # Hide all responses by default end chat(:summarize) do show_response! # But show the final summary end end ``` -------------------------------- ### Execute Roast Workflows from Command Line (Bash) Source: https://github.com/shopify/roast/blob/main/tutorial/07_processing_collections/README.md Provides bash commands to execute Roast workflows from the command line. It includes examples for running basic map operations with collect, reduce, and accessing specific iterations, as well as running workflows configured for parallel execution. ```bash # Basic map with collect, reduce, and accessing specific iterations bin/roast execute tutorial/07_processing_collections/basic_map.rb # Parallel execution bin/roast execute tutorial/07_processing_collections/parallel_map.rb ``` -------------------------------- ### Define Basic Roast Workflow Structure Source: https://github.com/shopify/roast/blob/main/tutorial/01_your_first_workflow/README.md The fundamental structure of a Roast workflow requires an execute block where the task logic resides. ```ruby execute do # Your workflow goes here end ``` -------------------------------- ### Execute Workflow via CLI Source: https://github.com/shopify/roast/blob/main/tutorial/01_your_first_workflow/README.md The command line interface command used to trigger a specific Roast workflow file. It requires the path to the Ruby workflow file as an argument. ```bash bin/roast execute path/to/workflow.rb ``` -------------------------------- ### Track Roast Workflow Events with Shopify's Monorail Source: https://github.com/shopify/roast/blob/main/docs/INSTRUMENTATION.md This Ruby example shows how to use Roast's instrumentation hooks to track workflow start and completion events with Shopify's internal Monorail service. It sends relevant payload data for 'run' and 'run_complete' commands. ```ruby # .roast/initializers/monorail.rb # Track workflow execution ActiveSupport::Notifications.subscribe("roast.workflow.start") do |name, start, finish, id, payload| Roast::Support::Monorail.track_command("run", { "workflow_path" => payload[:workflow_path], "options" => payload[:options], "name" => payload[:name] }) end ActiveSupport::Notifications.subscribe("roast.workflow.complete") do |name, start, finish, id, payload| Roast::Support::Monorail.track_command("run_complete", { "workflow_path" => payload[:workflow_path], "success" => payload[:success], "execution_time" => payload[:execution_time] }) end ``` -------------------------------- ### Documenting Aliases and Inverse Methods in Ruby Source: https://github.com/shopify/roast/blob/main/internal/documentation/doc-comments-external.md Demonstrates how to document methods with aliases and inverse methods in Ruby. It emphasizes listing the primary method first in the alias list and using dedicated subsections for clarity. This approach ensures that documentation is accessible regardless of which alias is used. ```ruby # Configure the cog to run the agent with __no__ permissions applied # # The cog's default behaviour is to run with __no__ permissions. # # #### Alias Methods # - `no_apply_permissions!` # - `skip_permissions!` # # #### Inverse Methods # - `apply_permissions!` # - `no_skip_permissions!` # #: () -> void def no_apply_permissions! @values[:apply_permissions] = false end alias_method(:skip_permissions!, :no_apply_permissions!) ``` -------------------------------- ### Ruby: Customize iteration start index with `repeat` Source: https://github.com/shopify/roast/blob/main/tutorial/08_iterative_workflows/README.md Shows how to customize the starting index for iterations in Ruby using the `repeat` block. This allows for flexible control over the iteration sequence, beginning from a specified value. ```ruby execute do repeat(run: :process) do |my| my.value = 100 my.index = 10 # Start counting from 10 end ruby do puts "Final: #{repeat!.value}" end end ``` -------------------------------- ### Basic Documentation Comment Format in Ruby Source: https://github.com/shopify/roast/blob/main/internal/documentation/doc-comments-external.md Demonstrates the standard structure for documentation comments in Ruby, including a one-line summary, optional multi-line details, and type signatures. This format is crucial for generating helpful user-facing documentation. ```ruby # [One-line summary of what the method does] # # [Optional: Additional details, context, or explanation] # # [Optional: Subsections for cross-references, notes, etc.] # #: (ParamType) -> ReturnType # Type signatures are enforced by Sorbet/RuboCop def method_name(param) # implementation end ``` -------------------------------- ### Execute Workflow with Targets (Bash) Source: https://github.com/shopify/roast/blob/main/tutorial/03_targets_and_params/README.md Demonstrates how to execute a Roast workflow and pass file paths or URLs as targets directly on the command line. Shell globs are automatically expanded. ```bash bin/roast execute workflow.rb https://example.com bin/roast execute workflow.rb README.md bin/roast execute workflow.rb src/*.rb bin/roast execute workflow.rb Gemfile Gemfile.lock ``` -------------------------------- ### Work with Indices in `map` Cog Scopes (Ruby) Source: https://github.com/shopify/roast/blob/main/tutorial/07_processing_collections/README.md Details how scopes called by `map` receive the iteration index as a third parameter. It shows default index starting at 0 and how to customize the starting index using `initial_index`. It also explains how `call` simulates processing a single item with a specific index. ```ruby execute(:process_with_index) do chat(:numbered) do |_, item, index| "Process item #{index}: #{item}" end end execute do # Default: indices start at 0 map(run: :process_with_index) { ["a", "b", "c"] } # Custom starting index map(run: :process_with_index) do |my| my.items = ["a", "b", "c"] my.initial_index = 1 # Start counting from 1 end end # Simulate processing one item from the middle of a collection call(run: :some_scope) do |my| my.value = "some data" my.index = 3 end ``` -------------------------------- ### Configure Agent Step Options Source: https://github.com/shopify/roast/blob/main/docs/AGENT_STEPS.md Shows how to configure 'continue' and 'include_context_summary' options for agent steps to manage session state and workflow context. ```yaml steps: - analyze_code - implement_fix: ^Fix the issues identified in the analysis - add_tests: ^Prepare and publish PR implement_fix: include_context_summary: true # Include a summary of the workflow context so far add_tests: continue: true # does not need context since is continuing from the previous step ``` -------------------------------- ### Check configuration state with predicates Source: https://github.com/shopify/roast/blob/main/internal/documentation/doc-comments-external.md Implements boolean predicate methods to check configuration state. These methods should be documented with references to related setter and bang methods. ```ruby def apply_permissions? !!@values[:apply_permissions] end ``` -------------------------------- ### Parallel Code Analysis with Async Cogs Source: https://github.com/shopify/roast/blob/main/tutorial/09_async_cogs/README.md A practical example of running multiple independent analysis tasks concurrently and aggregating their results. ```ruby config do agent { async! } end execute do # All three start immediately agent(:security) do "Review files in src/ for security vulnerabilities" end agent(:performance) do "Identify performance bottlenecks in src/" end agent(:style) do "Check code style and formatting in src/" end # Collect results as they complete ruby do puts "\n=== Security Issues ===" puts agent!(:security).response puts "\n=== Performance Issues ===" puts agent!(:performance).response puts "\n=== Style Issues ===" puts agent!(:style).response end end ``` -------------------------------- ### Combine Targets and Arguments in Ruby Workflow Source: https://github.com/shopify/roast/blob/main/tutorial/03_targets_and_params/README.md Shows a Ruby workflow that utilizes both targets and custom arguments (simple and key-value) passed from the command line, demonstrating how to access and use them together. ```ruby execute do ruby do puts "Processing #{targets.length} files" puts "Save data: #{arg?(:save_data)}" puts "Format: #{kwarg(:format) || "default"}" end end ``` -------------------------------- ### Define Technical Agent Step Prompts Source: https://github.com/shopify/roast/blob/main/docs/AGENT_STEPS.md Provides an example of a technical prompt for an agent step, specifically for creating a Rails migration file, where precise execution is required. ```markdown Create a new migration file with the following specifications: 1. Create a new migration file: db/migrate/{{timestamp}}_add_user_preferences.rb 2. The migration must include: - Add column :users, :preferences, :jsonb, default: {} - Add index :users, :preferences, using: :gin - Add column :users, :notification_settings, :jsonb, default: {} 3. Ensure proper up/down methods 4. Follow Rails migration conventions exactly ``` -------------------------------- ### Configure Asynchronous Execution in Ruby Source: https://context7.com/shopify/roast/llms.txt Demonstrates how to configure tasks to run asynchronously using the async! directive. It shows how to initiate multiple commands simultaneously and block for their results when needed. ```ruby config do cmd(:slow_task) { async! } # Run asynchronously cmd(:fast_task) { sync! } # Run synchronously (default) end execute do # These start immediately, don't wait for each other cmd(:download1) { "curl -s https://api.example.com/data1" } cmd(:download2) { "curl -s https://api.example.com/data2" } # This blocks until both complete when accessing output ruby do data1 = cmd!(:download1).json # Blocks until download1 completes data2 = cmd!(:download2).json # Blocks until download2 completes puts "Combined: #{data1.merge(data2)}" end end ``` -------------------------------- ### Subscribe to Specific Event Patterns Source: https://github.com/shopify/roast/blob/main/docs/INSTRUMENTATION.md Shows how to use regular expressions to subscribe to a group of related events, such as all events starting with 'roast.workflow.'. This reduces overhead by only processing relevant notifications. ```ruby # Subscribe only to workflow events ActiveSupport::Notifications.subscribe(/roast\.workflow\./) do |name, start, finish, id, payload| # Handle only workflow events end ``` -------------------------------- ### Pass Simple Arguments to Workflow (Bash) Source: https://github.com/shopify/roast/blob/main/tutorial/03_targets_and_params/README.md Demonstrates passing simple word tokens as arguments to a Roast workflow using the `--` separator on the command line. These arguments are accessible as symbols. ```bash bin/roast execute workflow.rb -- hello world bin/roast execute workflow.rb -- save_data something_else ``` -------------------------------- ### Pass Key-Value Arguments to Workflow (Bash) Source: https://github.com/shopify/roast/blob/main/tutorial/03_targets_and_params/README.md Illustrates how to pass key-value parameters to a Roast workflow using the `key=value` format after the `--` separator on the command line. ```bash bin/roast execute workflow.rb -- name=Alice format=json bin/roast execute workflow.rb -- name=Alice email=alice@example.net ``` -------------------------------- ### Access Simple Arguments in Ruby Workflow Source: https://github.com/shopify/roast/blob/main/tutorial/03_targets_and_params/README.md Shows how to access simple arguments passed to a Ruby workflow using the `args` method and how to check for the presence of a specific argument using `arg?`. ```ruby execute do ruby do puts "Arguments: #{args.inspect}" # [:hello, :world] # Check if a specific argument is present if arg?(:save_data) puts "Will save incremental data files" end end end ``` -------------------------------- ### Define Agent Steps in YAML Source: https://github.com/shopify/roast/blob/main/docs/AGENT_STEPS.md Demonstrates how to define regular steps versus agent steps (prefixed with ^) within a YAML configuration file. Supports both file-based prompts and inline text prompts. ```yaml steps: # File-based prompts - analyze_code # Regular step - processed by LLM first - ^implement_fix # Agent step - direct to CodingAgent # Inline prompts - Analyze the code quality and suggest improvements # Regular inline - ^Fix all ESLint errors and apply Prettier formatting # Agent inline ``` -------------------------------- ### Monitor Slow Step Completions with Roast Events Source: https://github.com/shopify/roast/blob/main/docs/INSTRUMENTATION.md This Ruby example shows how to specifically subscribe to the 'roast.step.complete' event. It checks the execution duration and logs a warning if a step takes longer than 10.0 seconds. ```ruby # .roast/initializers/performance.rb ActiveSupport::Notifications.subscribe("roast.step.complete") do |name, start, finish, id, payload| duration = finish - start if duration > 10.0 puts "WARNING: Step '#{payload[:step_name]}' took #{duration.round(1)}s" end end ``` -------------------------------- ### Executing tutorial workflows via CLI Source: https://github.com/shopify/roast/blob/main/tutorial/05_control_flow/README.md Provides the command-line interface commands to run the tutorial scripts associated with control flow concepts. ```bash # Conditional execution example bin/roast execute tutorial/05_control_flow/conditional_execution.rb # Handling failures example bin/roast execute tutorial/05_control_flow/handling_failures.rb ``` -------------------------------- ### Programmatic Workflow Validation in Ruby Source: https://github.com/shopify/roast/blob/main/docs/VALIDATION.md Integrate Roast's workflow validation directly into Ruby applications. This example demonstrates reading workflow content, initializing the validator, and checking for validity, warnings, and errors. ```ruby require 'roast' yaml_content = File.read('workflow.yml') validator = Roast::Workflow::Validators::ValidationOrchestrator.new(yaml_content, 'workflow.yml') if validator.valid? puts "Workflow is valid!" # Check for warnings validator.warnings.each do |warning| puts "Warning: #{warning[:message]}" puts " → #{warning[:suggestion]}" end else # Handle errors validator.errors.each do |error| puts "Error: #{error[:message]}" puts " → #{error[:suggestion]}" end end ``` -------------------------------- ### Step Names for Repeat and Each in Roast Source: https://github.com/shopify/roast/blob/main/docs/ITERATION_SYNTAX.md Shows how to use step names directly as strings for 'repeat' until conditions and 'each' collection iteration in Roast. This allows one step's output to control or populate another. ```yaml # Repeat until a step returns a truthy value - repeat: steps: - process_batch until: "check_completion" max_iterations: 100 # Iterate over items returned by a step - each: "get_pending_items" as: "pending_item" steps: - process_pending_item ``` -------------------------------- ### Configure Cog Behavior and Display Settings Source: https://github.com/shopify/roast/blob/main/tutorial/04_configuration_options/README.md Demonstrates how to apply global configurations to cog types and override them for specific instances using naming or regex patterns. Also includes methods for controlling the visibility of prompts and responses in the console output. ```ruby # Global configuration for chat cogs config :chat do temperature 0.7 end # Override for a specific cog by name config :chat, :my_cog do temperature 0.2 end # Pattern-based configuration using regex config :chat, /gpt-.*/ do provider :openai end # Control display output show_prompt! no_show_response! ``` -------------------------------- ### Execute Roast Workflow with Multiple Parameters Source: https://github.com/shopify/roast/blob/main/tutorial/04_configuration_options/README.md Command to execute a Roast workflow script that involves configuring multiple parameters across different steps. This is typically used for more complex workflows like controlling display and temperature settings. ```bash bin/roast execute tutorial/04_configuration_options/control_display_and_temperature.rb ``` -------------------------------- ### CI/CD Workflow Validation with GitHub Actions Source: https://github.com/shopify/roast/blob/main/docs/VALIDATION.md Example configuration for a GitHub Actions workflow to automatically validate Roast workflows on push or pull request events. It sets up Ruby and runs the Roast validation command in strict mode. ```yaml # .github/workflows/validate.yml name: Validate Workflows on: [push, pull_request] jobs: validate: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: ruby/setup-ruby@v1 with: ruby-version: '3.0' bundler-cache: true - name: Validate all workflows run: bundle exec roast validate --strict ``` -------------------------------- ### Run Local Coding Agents with Agent Cog Source: https://context7.com/shopify/roast/llms.txt Shows how to configure and execute local coding agents to perform filesystem tasks, maintain sessions, and retrieve execution statistics. ```ruby config do agent do provider :claude model "sonnet" append_system_prompt "Always respond concisely" show_prompt! show_progress! show_response! show_stats! end end execute do agent(:refactor) do <<~PROMPT Review the file lib/calculator.rb and refactor it to: 1. Add input validation 2. Improve error messages 3. Add documentation comments PROMPT end agent(:followup) do |my| my.prompt = "Now add unit tests for the changes you made" my.session = agent!(:refactor).session end ruby do response = agent!(:analyze).response stats = agent!(:analyze).stats puts "Agent response: #{response}" end end ``` -------------------------------- ### Documenting Methods with Type Signatures in Ruby Source: https://github.com/shopify/roast/blob/main/internal/documentation/doc-comments-internal.md Standard format for documenting methods in Roast, utilizing a one-line summary and a Sorbet-enforced type signature. ```ruby # Execute the agent with the given input and return the output # #: (Input) -> Output def execute(input) # implementation end ``` -------------------------------- ### Ruby Bang Method Convention for State Setters Source: https://github.com/shopify/roast/blob/main/internal/documentation/doc-comments-external.md Illustrates the use of the bang (`!`) suffix for no-argument state-setting methods in Ruby. This example shows a method `show_stdout!` which configures the cog to write STDOUT to the console, indicating it's disabled by default. ```ruby # Configure the cog to write STDOUT to the console # # Disabled by default # #: () -> void def show_stdout! @values[:show_stdout] = true end ``` -------------------------------- ### Define and Execute AI Workflows in Ruby Source: https://github.com/shopify/roast/blob/main/README.md Demonstrates the declarative syntax for chaining shell commands, AI agents, and chat summaries within a Roast workflow. The workflow uses 'cmd' to fetch data, 'agent' to analyze it, and 'chat' to generate a final summary. ```ruby execute do # Get recent changes cmd(:recent_changes) { "git diff --name-only HEAD~5..HEAD" } # AI agent analyzes the code agent(:review) do files = cmd!(:recent_changes).lines <<~PROMPT Review these recently changed files for potential issues: #{files.join("\n")} Focus on security, performance, and maintainability. PROMPT end # Summarize for stakeholders chat(:summary) do "Summarize this for non-technical stakeholders:\n\n#{agent!(:review).response}" end end ``` -------------------------------- ### Reduce Results from `map` Cog Iterations (Ruby) Source: https://github.com/shopify/roast/blob/main/tutorial/07_processing_collections/README.md Illustrates using the `reduce` cog to combine outputs from `map` cog iterations into a single value. Examples include summing numerical outputs and building a hash by merging results, with options to skip items or handle specific conditions. ```ruby # Sum all outputs # The second argument to `reduce` is the initial value for the accumulator. It is required. total = reduce(map!(:calculate_scores), 0) do |sum, output| # the block given to `reduce` should return the new value of the accumulator at each step sum + output end # Build a hash results = reduce(map!(:process_items), {}) do |hash, output, item, index| # returning nil will skip this item; it will not reset the accumulator to nil hash.merge(item => output) unless output.text.include?("failure") end ``` -------------------------------- ### Define Global and Scoped Configuration Options Source: https://context7.com/shopify/roast/llms.txt Provides a reference for configuring chat providers, agent settings, command execution behavior, and parallelism. Settings can be applied globally, by type, or via regex patterns. ```ruby config do chat do provider :openai model "gpt-4o-mini" temperature 0.7 end agent do provider :claude model "sonnet" end cmd do fail_on_error! working_directory "/path" end map(:name) do parallel 4 end chat(:special) { model "gpt-4o" } cmd(/test_/) { no_fail_on_error! } end ``` -------------------------------- ### Documenting Methods with Additional Context in Ruby Source: https://github.com/shopify/roast/blob/main/internal/documentation/doc-comments-internal.md Format for documenting methods where the interface contract requires additional explanation regarding behavior, such as caching or lazy initialization. ```ruby # Get the RubyLLM context configured for this chat cog # # Returns a cached context object that is lazily initialized on first access # and reused for subsequent calls. # #: () -> RubyLLM::Context def ruby_llm_context @ruby_llm_context ||= RubyLLM.context do |context| # configuration end end ```