### Example Debug Log Output Source: https://github.com/19h/ratio/blob/master/README.md This snippet shows example output found in a debug log file when running Ratio with the `--debug` flag. It illustrates ACP protocol messages, subprocess output, and Ratio's internal logging. ```text # In debug.log you'll see: # [acp:worker] send request id=1 method=initialize params={...} # [acp:worker] recv response id=1 result={...} # [acp:reviewer] send request id=1 method=prompt params={...} # [stderr:worker] Loading model anthropic/claude-sonnet-4-5... # [ratio] [Info] Parsed verdict: NEEDS_REVISION (feedback: 2847 chars) ``` -------------------------------- ### Ratio TOML Configuration Example Source: https://context7.com/19h/ratio/llms.txt Illustrates the structure of a TOML configuration file for Ratio. Defines the project goal, working directory, agent settings (worker and reviewer), orchestration parameters, and various constraints like required/forbidden tools and paths. ```toml # The goal — a detailed natural-language description of what to accomplish goal = """ Build a REST API server with user authentication, input validation, and comprehensive test coverage. """ # Working directory for all agents (defaults to current directory) cwd = "/path/to/project" # Worker agent configuration [worker] binary = "opencode" model = "anthropic/claude-sonnet-4-5" # agent = "custom-agent-name" # Custom agent name within opencode # env = [{ key = "API_KEY", value = "sk-..." }] # extra_args = ["--some-flag"] # Reviewer agent configuration [reviewer] binary = "opencode" model = "anthropic/claude-sonnet-4-5" # Orchestration behavior [orchestration] max_review_cycles = 5 # reviewer_system_prompt = "You are a senior Rust engineer..." # worker_system_prompt = "You are a precise coding agent..." stall_timeout_secs = 120 # Nudge stalled agents after 2 minutes max_nudges = 3 # Max nudge attempts before failure # Enforced constraints [constraints] required_tools = ["cargo clippy", "cargo test"] forbidden_tools = ["rm -rf"] required_approaches = [ "Use Result for all error handling", "All public types must derive Debug", ] forbidden_approaches = ["unsafe code blocks"] allowed_paths = ["src/"] # Empty = unrestricted forbidden_paths = ["Cargo.lock"] custom_rules = [ "Do not add new dependencies without approval", "Preserve existing public API signatures", ] ``` -------------------------------- ### Ratio CLI Usage Examples Source: https://context7.com/19h/ratio/llms.txt Demonstrates various ways to invoke the Ratio CLI for code orchestration. Includes basic invocation, configuration file usage, headless mode for CI, debug logging, resuming sessions, and overriding model configurations. ```bash # Basic invocation with a goal and working directory ratio --goal "Add comprehensive error handling to src/lib.rs" --cwd /path/to/project # Run with a TOML configuration file ratio --config ratio.toml # Headless mode for CI/scripts (worker output to stdout, logs to stderr) ratio --config ratio.toml --headless > worker_output.txt # Debug mode with ACP protocol logging ratio --config ratio.toml --headless --debug 2>debug.log # Resume a previous session from saved state ratio --config ratio.toml --resume # Override models via CLI ratio --config ratio.toml --worker-model "anthropic/claude-sonnet-4-5" --reviewer-model "anthropic/claude-sonnet-4-5" ``` -------------------------------- ### Ratio Stakeholder Configuration Example Source: https://context7.com/19h/ratio/llms.txt Defines how to configure stakeholder agents in Ratio's TOML file. Shows examples of a Security Auditor, UX Engineer, and SRE, specifying their personas, the phases they participate in, and their agent configurations. ```toml # Security auditor participating in both planning and review [[stakeholders]] name = "Security Auditor" persona = """ You are a security engineer. Review for auth flaws, injection vulnerabilities, data exposure risks, and insecure crypto. Think like an attacker. """ phases = ["planning", "review"] # Override agent config for this stakeholder [stakeholders.agent] binary = "opencode" model = "anthropic/claude-sonnet-4-5" # UX engineer participating only in review [[stakeholders]] name = "UX Engineer" persona = """ You review API ergonomics, error messages, and user-facing behavior. Are error responses consistent and helpful? """ phases = ["review"] # SRE reviewing for operational concerns [[stakeholders]] name = "SRE" persona = """ Review for observability (logging, metrics), failure modes, migration safety, and operational risk. What breaks at 3am? """ phases = ["planning", "review"] [stakeholders.agent] binary = "opencode" model = "anthropic/claude-sonnet-4-5" ``` -------------------------------- ### Tokio Runtime Model for Ratio Source: https://github.com/19h/ratio/blob/master/README.md Illustrates the single-threaded tokio runtime with a LocalSet used by Ratio. This setup is necessary due to the `!Send` nature of ACP SDK's `Client` trait, allowing the use of `Rc` instead of `Arc`. ```text tokio::main (current_thread) └─ LocalSet ├─ spawn_local: reviewer ACP I/O loop ├─ spawn_local: worker ACP I/O loop ├─ spawn_local: reviewer event forwarder ├─ spawn_local: worker event forwarder ├─ spawn_local: stakeholder ACP I/O loops (one per stakeholder) ├─ spawn_local: stakeholder event forwarders (one per stakeholder) ├─ spawn_local: stderr drain tasks (one per subprocess) └─ orchestrator.run() — drives the planning/review loop ↕ mpsc channels ↕ TUI event loop (select! on terminal input + orchestrator events + timer) ``` -------------------------------- ### Stakeholder Configuration Example in TOML Source: https://github.com/19h/ratio/blob/master/README.md This TOML snippet demonstrates how to define a stakeholder agent within the Ratio configuration file. It specifies the stakeholder's name, persona (defining its role and concerns), and the phases (planning, review, or both) in which it participates during the orchestration loop. ```toml [[stakeholders]] name = "Security Auditor" persona = """ You are a security engineer. Review for auth flaws, injection vulnerabilities, data exposure, and insecure crypto. """ phases = ["planning", "review"] # or just ["review"] ``` -------------------------------- ### Save and Load Session State in Rust Source: https://context7.com/19h/ratio/llms.txt Demonstrates how to save and load session state (SessionState and UIState) using Rust. This is crucial for the `--resume` functionality, allowing the application to pick up where it left off. It includes saving and loading both core session data and UI elements like todos and logs, as well as methods for getting the session file path and removing session files. ```rust use ratio::session::{SessionState, UIState, SavedTodoItem, SavedLogEntry}; use std::path::Path; let cwd = Path::new("/path/to/project"); // Save session state let session = SessionState { reviewer_session_id: "reviewer-session-123".to_string(), worker_session_id: "worker-session-456".to_string(), last_active_agent: "reviewer".to_string(), phase: "reviewing".to_string(), cycle: 3, goal: "Add error handling".to_string(), }; session.save(cwd)?; // Load session state for resume if let Some(saved) = SessionState::load(cwd)? { println!("Resuming from cycle {} in {} phase", saved.cycle, saved.phase); println!("Last active: {}", saved.last_active_agent); } // Get session file path let session_path = SessionState::path(cwd); // -> /path/to/project/.ratio-session.json // Save UI state (todos + logs) let ui_state = UIState { todos: vec![ SavedTodoItem { content: "Implement error handling".to_string(), status: "completed".to_string(), priority: "high".to_string(), }, SavedTodoItem { content: "Add tests".to_string(), status: "in_progress".to_string(), priority: "medium".to_string(), }, ], logs: vec![ SavedLogEntry { timestamp: "2024-01-15T10:30:00Z".to_string(), level: "info".to_string(), message: "Cycle 1 completed".to_string(), }, ], }; u_state.save(cwd)?; // Load UI state if let Some(saved_ui) = UIState::load(cwd) { println!("Restored {} todos", saved_ui.todos.len()); } // Clean up session files after successful completion SessionState::remove(cwd); ``` -------------------------------- ### Load and Apply Configuration with Rust Source: https://context7.com/19h/ratio/llms.txt Demonstrates loading configuration from a TOML file, applying CLI overrides, validating the configuration, and accessing its fields using the `ratio::config` module in Rust. ```rust use ratio::config::{Config, CliOverrides}; use std::path::PathBuf; // Load configuration from a TOML file let mut config = Config::from_file(std::path::Path::new("ratio.toml"))?; // Apply CLI overrides config.apply_overrides(&CliOverrides { goal: Some("Fix all clippy warnings".to_string()), cwd: Some(PathBuf::from("/path/to/project")), worker_model: Some("anthropic/claude-sonnet-4-5".to_string()), reviewer_model: None, max_iterations: Some(10), }); // Validate configuration (ensures goal is not empty) config.validate()?; // Access configuration fields println!("Goal: {}", config.goal); println!("Working directory: {}", config.cwd.display()); println!("Worker binary: {}", config.worker.binary); println!("Max cycles: {}", config.orchestration.max_review_cycles); ``` -------------------------------- ### Ratio CLI Reference Source: https://github.com/19h/ratio/blob/master/README.md This is the command-line interface reference for the Ratio tool, an LLM agent orchestrator. It details the available options for setting goals, configuration files, working directories, LLM models, and other operational parameters. ```bash ratio — LLM agent orchestrator Usage: ratio [OPTIONS] Options: -g, --goal The goal to accomplish -c, --config Path to TOML configuration file -C, --cwd Working directory for all agents --worker-model LLM model for the worker agent --reviewer-model LLM model for the reviewer agent --max-cycles Cycle cap override (currently not enforced) --headless Run without TUI (output to stdout/stderr) --debug Log ACP protocol messages to stderr --resume Resume a previous session from saved state -V, --version Print version -h, --help Print help **Precedence:** CLI flags > config file > defaults. ``` -------------------------------- ### Headless Mode Output and Debugging in Bash Source: https://context7.com/19h/ratio/llms.txt Shows how to run Ratio in headless mode using bash scripts for scripting and CI integration. It covers redirecting stdout and stderr to log files, checking logs for specific information like cycle completion, and enabling debug mode for a full ACP protocol trace. ```bash #!/bin/bash set -euo pipefail # Run ratio in headless mode ratio \ --config ratio.toml \ --headless \ --cwd ./my-project \ 2>ratio-stderr.log # Worker output goes to stdout # Reviewer output, stakeholder output, and orchestrator logs go to stderr # Check the log for cycle results grep "cycle.*completed" ratio-stderr.log # Debug mode with full ACP protocol trace ratio --config ratio.toml --headless --debug 2>debug.log # Debug log contains: # [acp:worker] send request id=1 method=initialize params={...} # [acp:worker] recv response id=1 result={...} # [acp:reviewer] send request id=1 method=prompt params={...} # [stderr:worker] Loading model anthropic/claude-sonnet-4-5... # [ratio] [Info] Parsed verdict: NEEDS_REVISION (feedback: 2847 chars) ``` -------------------------------- ### Ratio TUI Panes and Behavior Source: https://github.com/19h/ratio/blob/master/README.md Documentation for the Ratio terminal user interface (TUI), built with ratatui. It describes the different panes (Agent, Todo, Log), agent stream behavior, and keyboard shortcuts for navigation and control. ```markdown ## TUI Ratio includes a terminal interface built with [ratatui](https://ratatui.rs). ### Panes | Pane | Content | |---|---| | **Agent** | Unified stream for the currently selected agent (Reviewer, Worker, or Stakeholder): text output, thought chunks, tool calls, phase separators | | **Todo** | Shared todo list from `TodoWrite` tool calls | | **Log** | Orchestrator/system messages with timestamps and severity | The Agent pane is first-class for all agents. Stakeholders are not collapsed into logs — each stakeholder has its own stream and title color. ### Agent stream behavior - `r` cycles forward through agents: Reviewer -> Worker -> Stakeholder 1 -> ... - `R` cycles backward - Phase changes auto-follow activity (`Working/Revising` -> Worker, `Planning/Reviewing` -> Reviewer) - During stakeholder consultation, the first stakeholder text chunk auto-switches from Reviewer to that stakeholder stream - Thought chunks are dim italic; tool calls are updated in place as status changes ### Agent colors - Reviewer: magenta - Worker: cyan - Stakeholders: rotating palette (light green, yellow, red, blue, magenta, cyan, orange, lavender) ### Keyboard shortcuts | Key | Action | |---|---| | `Ctrl+K` | Emergency kill — immediately terminates all agents | | `Ctrl+C` x2 | Double-tap abort (within 800ms) | | `q` | Quit (when orchestration is finished) | | `i` or `:` | Enter message input mode | | `Esc` | Exit input mode | | `Enter` | Queue message to current agent (input mode) | | `r` / `R` | Cycle next / previous agent stream (Agent pane focused) | | `Tab` | Focus next pane | | `Shift+Tab` | Focus previous pane | | `j` / `Down` | Scroll down | | `k` / `Up` | Scroll up | | `PageDown` / `PageUp` | Scroll by 20 lines | | `End` | Jump to bottom (re-enables auto-scroll) | | `Home` | Jump to top (disables auto-scroll) | ### Auto-scroll Each pane auto-scrolls independently. Scrolling up manually disables auto-scroll for that pane. Press `End` to re-enable it. ``` -------------------------------- ### Rust Configuration for Ratio Project Source: https://github.com/19h/ratio/blob/master/README.md This Rust code defines configuration rules for the Ratio project, including required and forbidden coding approaches, allowed and forbidden file paths, and custom quality rules. It also includes optional stakeholder configurations for planning and review phases. ```rust # Coding approaches the worker must follow. required_approaches = [ "Use Result for all error handling — no unwrap() or expect()", "All public types must derive Debug", ] # Approaches the worker must avoid. forbidden_approaches = [ "unsafe code blocks", ] # File paths the worker may modify (empty = unrestricted). # allowed_paths = ["src/"] # File paths the worker must NOT touch. forbidden_paths = [ "Cargo.lock", ] # Free-form rules expressed as sentences. These are injected as # MANDATORY QUALITY RULES — the reviewer cannot approve unless # every single rule is satisfied. custom_rules = [ "Do not add new dependencies without explicit approval", "Preserve existing public API signatures", ] # ── Stakeholders (optional) ─────────────────────────────────── # Each [[stakeholders]] entry adds a persona that participates in # planning and/or review phases. # [[stakeholders]] # name = "Security Reviewer" # persona = "You are a security engineer. Review for auth flaws..." # phases = ["planning", "review"] # Default: both # # # Override the agent config (binary, model, env). Default: reviewer's config. # [stakeholders.agent] # binary = "opencode" # model = "anthropic/claude-sonnet-4-5" ``` -------------------------------- ### Debug Failing Session with Full Protocol Trace Source: https://github.com/19h/ratio/blob/master/README.md This command initiates Ratio in headless mode with debug logging enabled, redirecting all protocol traces and subprocess stderr to a specified log file for detailed debugging. ```sh # Full protocol trace ratio --config ratio.toml --headless --debug 2>debug.log ``` -------------------------------- ### Enable Debug Logging for Ratio Source: https://github.com/19h/ratio/blob/master/README.md This command enables debug-level logging for the Ratio project by setting the RUST_LOG environment variable. It also specifies a configuration file to be used. ```sh # Enable debug-level logging RUST_LOG=ratio=debug ratio --config ratio.toml ``` -------------------------------- ### Define and Render Constraints with Rust Source: https://context7.com/19h/ratio/llms.txt Illustrates defining hard constraints for worker behavior using the `Constraints` struct from the `ratio::config` module in Rust. It also shows how to render these constraints into a prompt section. ```rust use ratio::config::Constraints; let constraints = Constraints { required_tools: vec![ "cargo clippy -- -D warnings".to_string(), "cargo test".to_string(), ], forbidden_tools: vec!["rm -rf".to_string()], required_approaches: vec![ "Use Result for error handling".to_string(), ], forbidden_approaches: vec!["unsafe code blocks".to_string()], allowed_paths: vec!["src/".to_string()], forbidden_paths: vec!["Cargo.lock".to_string(), ".env".to_string()], custom_rules: vec![ "All database queries must use parameterized statements".to_string(), "Tokens must use OsRng, not thread_rng".to_string(), ], }; // Render constraints as a prompt section let prompt_section = constraints.render_prompt_section(); // Output: // ═══ ENFORCED CONSTRAINTS ═══ // REQUIRED TOOLS — you MUST use each of these: // - cargo clippy -- -D warnings // - cargo test // FORBIDDEN TOOLS — you MUST NOT use any of these: // - rm -rf // ... // ═══ END CONSTRAINTS ═══ ``` -------------------------------- ### Watch Ratio Logs Source: https://github.com/19h/ratio/blob/master/README.md This command allows you to monitor the log output of the Ratio project in real-time from a separate terminal. It is useful for debugging and observing the application's behavior. ```sh # Watch logs in another terminal tail -f "$TMPDIR/ratio.log" ``` -------------------------------- ### Headless CI Pipeline Script Source: https://github.com/19h/ratio/blob/master/README.md This bash script executes the Ratio tool in headless mode for a CI pipeline. It specifies a configuration file, maximum cycles, and the working directory, redirecting stderr to a log file. ```sh #!/bin/bash set -euo pipefail ratio \ --config ratio.toml \ --headless \ --max-cycles 3 \ --cwd ./my-project \ 2>ratio-stderr.log echo "Orchestration complete" ``` -------------------------------- ### TOML Configuration for Feature Implementation Source: https://github.com/19h/ratio/blob/master/README.md This TOML configuration specifies requirements for implementing a WebSocket server, including model choices for worker and reviewer, orchestration settings, and detailed constraints on allowed paths, tools, and coding practices. ```toml goal = """ Implement a WebSocket server in src/ws/ that handles authentication via JWT, supports pub/sub channels, and gracefully handles disconnections. Include integration tests for all connection lifecycle events. """ [worker] model = "anthropic/claude-sonnet-4-5" [reviewer] model = "anthropic/claude-sonnet-4-5" [orchestration] max_review_cycles = 8 [constraints] required_tools = ["cargo test", "cargo clippy"] required_approaches = [ "Use tokio-tungstenite for WebSocket handling", "All public types must implement Debug and Clone", "Use tracing for structured logging", ] allowed_paths = ["src/ws/", "tests/"] forbidden_paths = ["Cargo.lock", "src/main.rs"] custom_rules = [ "Do not modify any existing modules outside src/ws/", "All new dependencies must be justified in code comments", ] ``` -------------------------------- ### Shared Workspace Protocol using Markdown Source: https://context7.com/19h/ratio/llms.txt Illustrates the shared workspace protocol used by Ratio agents for coordination. This involves using markdown files for communication, such as `agents.md` for implementation notes and decisions, and `.ratio/research/error-analysis.md` for research findings and recommended approaches. ```markdown # agents.md - Implementation notes maintained by both agents ## Current Understanding - Task: Add comprehensive error handling to src/lib.rs - All functions should return Result instead of panicking ## Implementation Decisions - Using thiserror for custom error types - Wrapping all I/O operations in error handling ## Progress - [x] Identified all unwrap() calls - [x] Created Error enum in src/error.rs - [ ] Update parse() function - [ ] Add tests for error cases ## Open Questions - None remaining --- # .ratio/research/error-analysis.md - Research file created by reviewer ## Summary Analyzed all error-prone code paths in src/lib.rs. ## Findings - 15 unwrap() calls found - 3 expect() calls with unhelpful messages - File I/O has no error handling ## Recommended Approach Create centralized Error type with variants for: - IoError(std::io::Error) - ParseError { line: usize, message: String } - ValidationError(String) ``` -------------------------------- ### TUI Keyboard Shortcuts for Ratio Source: https://context7.com/19h/ratio/llms.txt Lists the keyboard shortcuts available in the Ratio terminal user interface (TUI). These shortcuts enable navigation between panes, scrolling within panes, controlling agent streams, entering input mode, and executing control commands like emergency kill or quitting. ```text # Navigation Tab / Shift+Tab Focus next / previous pane j / Down Scroll down k / Up Scroll up PageDown / PageUp Scroll by 20 lines Home / End Jump to top / bottom (End re-enables auto-scroll) # Agent Stream Control r / R Cycle next / previous agent stream (Reviewer -> Worker -> Stakeholders) # Input Mode i or : Enter message input mode Esc Exit input mode Enter Queue message to current agent # Control Ctrl+K Emergency kill — immediately terminate all agents Ctrl+C x2 Double-tap abort (within 800ms) q Quit (when orchestration is finished) ``` -------------------------------- ### Manage Orchestration Loop with Rust Source: https://context7.com/19h/ratio/llms.txt Shows how to initialize and manage the `Orchestrator` in Rust, including setting up an event channel for UI updates and handling various `OrchestratorEvent` types like phase changes and cycle completions. ```rust use ratio::orchestrator::{Orchestrator, OrchestratorEvent, Phase, ReviewVerdict}; use tokio::sync::mpsc; // Create event channel for UI updates let (event_tx, mut event_rx) = mpsc::unbounded_channel::(); // Create orchestrator with configuration let mut orchestrator = Orchestrator::new(config, event_tx); // Check current phase assert_eq!(orchestrator.phase(), &Phase::Idle); // Access completed cycles let cycles = orchestrator.cycles(); println!("Completed {} cycles", cycles.len()); // Handle orchestrator events in UI/headless mode tokio::spawn(async move { while let Some(event) = event_rx.recv().await { match event { OrchestratorEvent::PhaseChanged(phase) => { println!("Phase: {:?}", phase); } OrchestratorEvent::WorkerEvent(agent_event) => { // Handle worker text chunks, tool calls, etc. } OrchestratorEvent::ReviewerEvent(agent_event) => { // Handle reviewer output } OrchestratorEvent::StakeholderEvent(idx, name, agent_event) => { println!("Stakeholder {}: {:?}", name, agent_event); } OrchestratorEvent::Log(level, msg) => { println!("[{:?}] {}", level, msg); } OrchestratorEvent::CycleCompleted(record) => { println!("Cycle {} verdict: {:?}", record.cycle, record.verdict); } OrchestratorEvent::Finished(final_phase) => { println!("Finished: {:?}", final_phase); break; } } } }); ``` -------------------------------- ### Agent Lifecycle Command for Ratio Source: https://github.com/19h/ratio/blob/master/README.md Shows the command used to spawn agents (reviewer, worker, stakeholder) for Ratio. It utilizes the `opencode acp` command with specified working directory, optional model, agent type, and additional arguments. ```sh opencode acp --cwd [--model ] [--agent ] [extra_args...] ``` -------------------------------- ### Orchestration Flow Diagram for Ratio Source: https://github.com/19h/ratio/blob/master/README.md Visualizes the orchestration flow within the Ratio project, detailing the planning phase and the work-review loop. It shows the progression from goal setting through reviewer and worker interactions to the final verdict. ```text Planning Work-Review Loop (cycles) ┌─────────┐ ┌─────────────────────────┐ │ ▼ │ ▼ goal ──► reviewer ──► stakeholders ──► reviewer synthesis ──► worker (planning) (final instruction) │ │ ┌──────────────────────────────────────────────────────┘ │ ▼ reviewer ──► stakeholders ──► reviewer synthesis ──► verdict (draft) (review) (final verdict) │ ▲ │ │ NEEDS_REVISION │ └──────────────────────────────────────────────────┘ ``` -------------------------------- ### Interact with Agent Subprocesses using WorkerConnection in Rust Source: https://context7.com/19h/ratio/llms.txt Demonstrates how to use the WorkerConnection in Rust to communicate with agent subprocesses. This includes performing ACP handshakes, setting models, sending prompts with and without watchdog timers, cancelling turns, and loading existing sessions. It requires the `ratio::protocol::WorkerConnection` and `std::time::Duration` types. ```rust use ratio::protocol::WorkerConnection; use std::time::Duration; // After spawning agent and obtaining connection... // Perform ACP handshake (initialize + new_session) worker_conn.handshake(&config.cwd).await?; // Get the established session ID if let Some(session_id) = worker_conn.session_id() { println!("Session: {}", session_id); } // Set the model for this session worker_conn.set_model("anthropic/claude-sonnet-4-5").await?; // Send a prompt and wait for completion let (stop_reason, output_text) = worker_conn.prompt( "Implement error handling for the parse function in src/parser.rs" ).await?; println!("Stop reason: {:?}", stop_reason); println!("Output: {}", output_text); // Send prompt with stall watchdog (nudges if agent hangs) let (stop_reason, output_text) = worker_conn.prompt_with_nudge( "Fix all clippy warnings in the codebase", Duration::from_secs(120), // stall timeout 3, // max nudges |attempt| { eprintln!("Agent stalled, sending nudge {}/3", attempt); }, ).await?; // Cancel the current turn (emergency stop) worker_conn.cancel().await?; // Load an existing session for --resume functionality worker_conn.load_existing_session( "session-id-string".to_string(), &config.cwd, ).await?; ``` -------------------------------- ### TOML Configuration for Code Review Source: https://github.com/19h/ratio/blob/master/README.md This TOML configuration defines a goal for reviewing source code for quality issues, including specific constraints like required tools and forbidden approaches. ```toml goal = """ Review src/ for code quality issues: fix all clippy warnings, add missing error handling, ensure consistent naming conventions, and verify all tests pass. """ [constraints] required_tools = ["cargo clippy -- -D warnings", "cargo test"] forbidden_approaches = ["unsafe code blocks", "unwrap() on Results"] ``` -------------------------------- ### Spawn Agent Subprocesses using spawn_agent in Rust Source: https://context7.com/19h/ratio/llms.txt Details the process of spawning agent subprocesses (worker or reviewer roles) using the `spawn_agent` function in Rust. This involves configuring the agent, creating an event channel, spawning the process, handling its I/O, performing a handshake, and managing the process lifecycle. It utilizes types from `ratio::subprocess`, `ratio::config`, `ratio::protocol`, and `tokio::sync::mpsc`. ```rust use ratio::subprocess::{spawn_agent, AgentRole, AgentProcess}; use ratio::config::AgentConfig; use ratio::protocol::AgentEvent; use tokio::sync::mpsc; use std::path::Path; // Create event channel for agent events let (event_tx, mut event_rx) = mpsc::unbounded_channel::(); // Configure the agent let agent_config = AgentConfig { binary: "opencode".to_string(), model: "anthropic/claude-sonnet-4-5".to_string(), env: vec![], agent: None, extra_args: vec![], }; // Spawn worker agent subprocess let (mut worker_conn, mut worker_proc, worker_io) = spawn_agent( AgentRole::Worker, &agent_config, Path::new("/path/to/project"), event_tx, )?; // Spawn the ACP I/O task tokio::task::spawn_local(async move { if let Err(e) = worker_io.await { eprintln!("Worker I/O error: {}", e); } }); // Drain stderr to prevent pipe buffer deadlock if let Some(stderr) = worker_proc.stderr.take() { tokio::task::spawn_local(async move { use tokio::io::AsyncBufReadExt; let reader = tokio::io::BufReader::new(stderr); let mut lines = reader.lines(); while let Ok(Some(line)) = lines.next_line().await { eprintln!("[worker stderr] {}", line); } }); } // Perform handshake worker_conn.handshake(Path::new("/path/to/project")).await?; // Check if process is running if worker_proc.is_running() { println!("Worker process is active"); } // Kill the subprocess worker_proc.kill(); ``` -------------------------------- ### Event Flow Diagram for Ratio Source: https://github.com/19h/ratio/blob/master/README.md Depicts the event flow from an `opencode` subprocess to the TUI rendering in Ratio. It illustrates how ACP session notifications are translated into `AgentEvent`s, processed by the Orchestrator, and finally update the application state for rendering. ```text opencode subprocess │ ACP session_notification (JSON-RPC) ▼ OrchestratorClient (implements acp::Client) │ AgentEvent (TextChunk, ThoughtChunk, ToolCallStarted, ToolCallUpdated, │ TodoUpdated, PlanUpdated, ...) ▼ mpsc channel → Orchestrator │ OrchestratorEvent (PhaseChanged, WorkerEvent, ReviewerEvent, │ StakeholderEvent, Log, CycleCompleted, Finished) ▼ mpsc channel → TUI App / headless printer │ Updates app state (agent streams, thoughts, tool calls, todos, logs) ▼ ratatui render (clamped scroll, styled paragraphs) ``` -------------------------------- ### Configure Feature Implementation with Stakeholders (TOML) Source: https://context7.com/19h/ratio/llms.txt Sets up a configuration for implementing a feature with multi-stakeholder review using TOML. It includes the feature goal, agent models, orchestration cycles, detailed stakeholder personas and phases, and project-specific constraints. ```toml goal = "Add a user invitation system with email tokens and role assignment." [worker] model = "anthropic/claude-sonnet-4-5" [reviewer] model = "anthropic/claude-sonnet-4-5" [orchestration] max_review_cycles = 6 [[stakeholders]] name = "Security Auditor" persona = """ Review for auth flaws, injection vulnerabilities, insecure token generation, and data exposure risks. Think like an attacker. """ phases = ["planning", "review"] [[stakeholders]] name = "SRE" persona = """ Review for observability (logging, metrics), failure modes, migration safety, and operational risk. What breaks at 3am? """ phases = ["review"] [constraints] required_tools = ["cargo test"] custom_rules = [ "Invitation tokens must use OsRng, not thread_rng", "All database queries must use parameterized statements", ] ``` -------------------------------- ### Configure Code Review Task (TOML) Source: https://context7.com/19h/ratio/llms.txt Defines a code quality review task using TOML. It specifies the review goal, worker and reviewer agent configurations, orchestration settings, and constraints like required tools and forbidden approaches. ```toml goal = """ Review src/ for code quality issues: fix all clippy warnings, add missing error handling, ensure consistent naming conventions, and verify all tests pass. """ [worker] binary = "opencode" model = "anthropic/claude-sonnet-4-5" [reviewer] binary = "opencode" model = "anthropic/claude-sonnet-4-5" [orchestration] max_review_cycles = 5 [constraints] required_tools = ["cargo clippy -- -D warnings", "cargo test"] forbidden_approaches = ["unsafe code blocks", "unwrap() on Results"] custom_rules = [ "All public functions must have documentation comments", "Error messages must be descriptive and actionable", ] ``` -------------------------------- ### Handle Agent Events using AgentEvent Enum in Rust Source: https://context7.com/19h/ratio/llms.txt Illustrates how to process various events forwarded from ACP connections using the `AgentEvent` enum in Rust. This includes handling text and thought chunks, tool call statuses, todo list updates, and turn completion. It requires types from `ratio::protocol`. ```rust use ratio::protocol::{AgentEvent, ToolKind, ToolCallState, TodoEntry}; fn handle_agent_event(event: AgentEvent) { match event { AgentEvent::TextChunk(text) => { // Streaming text output from the agent print!("{}", text); } AgentEvent::ThoughtChunk(text) => { // Agent reasoning/thinking (displayed dimmed in TUI) eprintln!("[thinking] {}", text); } AgentEvent::ToolCallStarted { id, title, kind, raw_input, locations } => { // Tool execution started let kind_str = match kind { ToolKind::Read => "read", ToolKind::Edit => "edit", ToolKind::Execute => "exec", ToolKind::Search => "search", ToolKind::Todo => "todo", _ => "other", }; println!("[{}] {} started...", kind_str, title); } AgentEvent::ToolCallUpdated { id, status, content, .. } => { // Tool execution progress/completion match status { ToolCallState::Completed => println!("[ok] Tool completed"), ToolCallState::Failed => println!("[FAIL] Tool failed"), _ => {} } } AgentEvent::TodoUpdated(todos) => { // Shared todo list updated for todo in todos { println!("[{}] {}", todo.status, todo.content); } } AgentEvent::TurnComplete { stop_reason } => { println!("Turn complete: {:?}", stop_reason); } _ => {} } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.