### Create and List Shards (Bash) Source: https://github.com/wirasm/shards/blob/main/TESTING.md Demonstrates how to start a new shard, verify its existence in the list of active shards, and retrieve its detailed information. This involves using `shards start`, `shards list`, and `shards info` commands. ```bash # Create a basic shard ./target/debug/shards start test-basic echo "Hello World" # Verify it appears in list ./target/debug/shards list # Expected: Shows test-basic as Active # Check shard info ./target/debug/shards info test-basic # Expected: Shows name, status, command, path, creation time, worktree exists ✅ ``` -------------------------------- ### Start Shard with Ghostty (Bash) Source: https://github.com/wirasm/shards/blob/main/TESTING.md Tests the integration of Shards CLI with Ghostty terminal emulator. This command starts a shard, specifying Ghostty as the terminal, and expects Ghostty to open and automatically type the command. The command used is `shards start --terminal ghostty`. ```bash # Test with Ghostty (should use AppleScript automation) ./target/debug/shards start ghostty-test --terminal ghostty echo "Ghostty test" # Expected: Ghostty window opens, command is typed automatically # Verify: Check that Ghostty opened in correct directory (.shards/ghostty-test) ``` -------------------------------- ### Configure and Use Default Agent Profile (Bash) Source: https://github.com/wirasm/shards/blob/main/TESTING.md Demonstrates setting up a default agent configuration in `~/.shards/config.toml` and then starting a shard without specifying an agent, which should prompt for selection or use the default. This involves creating a config file and using `shards start`. ```bash # Create config file mkdir -p ~/.shards cat > ~/.shards/config.toml << EOF terminal = "terminal" default_agent = "echo 'Default agent'" [agents] test = "echo 'Test agent'" kiro = "kiro-cli chat" claude = "claude" EOF # Test default agent (no command specified) ./target/debug/shards start default-agent-test # Expected: Prompts to choose agent or uses default_agent ``` -------------------------------- ### Start a Shard for AI Agent Task Source: https://github.com/wirasm/shards/blob/main/README.md An example of how an AI agent can programmatically start a new Shard workspace for a specific task, such as fixing a bug. It demonstrates the agent integration capability of Shards. ```bash # AI agent creates isolated workspace for bug fix shards start bug-fix-123 "kiro-cli chat" ``` -------------------------------- ### Start Shard with Terminal.app (Bash) Source: https://github.com/wirasm/shards/blob/main/TESTING.md Tests the integration of Shards CLI with Terminal.app. This command starts a shard and explicitly directs it to use Terminal.app for execution, expecting a new Terminal window to open and run the specified command. The command used is `shards start --terminal terminal`. ```bash # Test with Terminal.app (should auto-execute command) ./target/debug/shards start terminal-test --terminal terminal echo "Terminal.app test" # Expected: Terminal.app window opens, runs command, shows output # Verify: Check that terminal opened in correct directory (.shards/terminal-test) ``` -------------------------------- ### Shards CLI Usage Examples (Bash) Source: https://github.com/wirasm/shards/blob/main/docs/PROMPT_PIPING_PLAN.md Provides a collection of bash command examples demonstrating various ways to use the Shards CLI, including creating shards with different prompt sources, setting timeouts, running headless, sending follow-up prompts, attaching to terminals, and listing agents. ```bash # Basic: create with prompt shards create auth-fix --agent claude --prompt "Fix the authentication bug in login.rs" # From file shards create feature-x --agent claude --prompt-file ./tasks/feature-x.md # From stdin (pipe) echo "Add unit tests for the User model" | shards create add-tests --prompt - # With timeout shards create big-refactor --prompt "Refactor the entire auth module" --timeout 300 # Headless only (no terminal) shards create batch-job --prompt "Update all copyright headers" --no-terminal # With allowed tools shards create fix-tests --prompt "Fix failing tests" --allowed-tools "Bash(npm:*),Read,Edit" # Send follow-up prompt shards send auth-fix "Now add tests for the fix" # Attach to session shards attach auth-fix # List agents shards agents shards agents --verbose ``` -------------------------------- ### Start Kiro CLI Agent Test Source: https://github.com/wirasm/shards/blob/main/TESTING.md Starts the Kiro CLI agent within a new shard. This test verifies that the Kiro CLI can be launched and is ready for user interaction. ```bash ./target/debug/shards start kiro-test kiro-cli chat # Expected: Kiro CLI starts in terminal, ready for interaction # Manual: Type a simple question to verify it works ``` -------------------------------- ### Example Session JSON Structure Source: https://github.com/wirasm/shards/blob/main/docs/PROMPT_PIPING_PLAN.md Provides a concrete example of a JSON object representing a session. This demonstrates the expected format and values for fields like `name`, `agent_session_id`, `prompt_history`, and `status`. ```json { "name": "auth-fix", "branch": "shard_a1b2c3d4", "worktree_path": "/repo/.shards/auth-fix", "agent": "claude", "agent_session_id": "550e8400-e29b-41d4-a716-446655440000", "initial_prompt": "Fix the authentication bug in login.rs", "prompt_history": [ { "prompt": "Fix the authentication bug in login.rs", "sent_at": "2025-01-17T10:30:00Z", "success": true, "session_id": "550e8400-e29b-41d4-a716-446655440000" }, { "prompt": "Now add tests for the fix", "sent_at": "2025-01-17T11:00:00Z", "success": true, "session_id": "550e8400-e29b-41d4-a716-446655440000" } ], "status": "Interactive", "command": "claude --resume 550e8400-e29b-41d4-a716-446655440000", "process_id": 12345, "process_name": "claude", "process_start_time": 1705487400, "created_at": "2025-01-17T10:30:00Z", "port_range_start": 8100, "port_count": 10 } ``` -------------------------------- ### Start Shard with Auto-Detected Terminal (Bash) Source: https://github.com/wirasm/shards/blob/main/TESTING.md Tests the automatic detection of a terminal emulator by the Shards CLI. If Ghostty is available, it will be used; otherwise, Terminal.app will be the fallback. The command used is `shards start` without a specific terminal flag. ```bash # Test auto-detection (should pick Ghostty if available, else Terminal.app) ./target/debug/shards start auto-test echo "Auto-detection test" # Expected: Opens in detected terminal # Verify: Command executes automatically ``` -------------------------------- ### Start Shard with Specific Agent Profile (Bash) Source: https://github.com/wirasm/shards/blob/main/TESTING.md Tests starting a shard using a specific agent profile defined in the Shards configuration. The `--agent` flag is used to select the desired profile, overriding the default agent. The command used is `shards start --agent `. ```bash # Test specific agent profile ./target/debug/shards start profile-test --agent test # Expected: Uses "echo 'Test agent'" command ``` -------------------------------- ### Install and Use Pre-commit Hook Source: https://github.com/wirasm/shards/blob/main/CONTRIBUTING.md Sets up a pre-commit hook to automatically enforce code formatting standards before each commit. This requires installing the `pre-commit` package and then installing the git hook. ```bash # Install pre-commit (if not already installed) pip install pre-commit # Install the git hook pre-commit install ``` -------------------------------- ### Best Practice: Example Rust Error Handling Pattern Source: https://github.com/wirasm/shards/blob/main/scripts/RALPH_LOOP.md Demonstrates a Rust code snippet for error handling, intended to be included in the `prompt.md` file as an example pattern for the Ralph Loop agent to follow. It showcases the use of `thiserror` for defining custom error types. ```rust // SOURCE: src/sessions/errors.rs:4-15 #[derive(Debug, thiserror::Error)] pub enum GuiError { #[error("PTY process failed: {message}")] PtyError { message: String }, } ``` -------------------------------- ### Manage and Monitor Processes Source: https://context7.com/wirasm/shards/llms.txt Provides functionality to check if a process is running, retrieve its information (name, status, start time), and get its resource metrics (CPU, memory). It also includes a secure method to kill processes by validating their name and start time. ```rust use shards::process::{is_process_running, get_process_info, get_process_metrics, kill_process}; let pid: u32 = 12345; // Check if process is running let running = is_process_running(pid).unwrap(); // Get process information if let Ok(info) = get_process_info(pid) { println!("Name: {}", info.name); println!("Status: {:?}", info.status); println!("Start Time: {}", info.start_time); } // Get process metrics if let Ok(metrics) = get_process_metrics(pid) { println!("CPU: {}%", metrics.cpu_usage_percent); println!("Memory: {} bytes", metrics.memory_usage_bytes); } // Kill process with validation (prevents PID reuse attacks) kill_process( pid, Some("claude"), // Expected process name Some(1705312800), // Expected start time ).unwrap(); ``` -------------------------------- ### Create Shard and Verify Git Worktree (Bash) Source: https://github.com/wirasm/shards/blob/main/TESTING.md Tests the Git integration by creating a shard and verifying that a Git worktree is set up correctly. It checks for the existence of the worktree directory and confirms that a unique Git branch is created for the shard. Commands include `shards start`, `ls`, and `git branch --show-current`. ```bash # Create shard and verify Git setup ./target/debug/shards start git-test echo "Git test" # Verify worktree exists ls .shards/git-test/ # Expected: Should contain project files # Verify unique branch created cd .shards/git-test && git branch --show-current # Expected: Shows branch like "shard_a1b2c3d4..." # Return to main directory cd ../.. ``` -------------------------------- ### Run Ralph with Custom Iteration Limit Source: https://github.com/wirasm/shards/blob/main/scripts/RALPH_LOOP.md This example demonstrates running the Ralph script with a custom iteration limit. By providing a second argument to `ralph-loop.sh`, you can control the maximum number of iterations the agent will perform. This is useful for debugging or when a specific number of training steps is required. ```bash ./scripts/ralph-loop.sh .kiro/artifacts/prds/my-feature 100 ``` -------------------------------- ### Install Shards using Cargo Source: https://github.com/wirasm/shards/blob/main/README.md Installs the Shards CLI tool from the local source code using the Cargo package manager. This command assumes you have Rust and Cargo installed and are in the root directory of the Shards project. ```bash cargo install --path . ``` -------------------------------- ### Manage Shards Sessions Programmatically (Rust) Source: https://context7.com/wirasm/shards/llms.txt Demonstrates managing Shards sessions using the `shards::sessions` library in Rust, including creating, listing, getting, restarting, and destroying sessions. ```rust use shards::sessions::{handler, types::{CreateSessionRequest, Session, SessionStatus}}; use shards::core::config::ShardsConfig; // Load configuration let config = ShardsConfig::load_hierarchy().unwrap_or_default(); // Create a new session let request = CreateSessionRequest::new( "feature/new-api".to_string(), Some("claude".to_string()), // Optional agent override ); match handler::create_session(request, &config) { Ok(session) => { println!("Session ID: {}", session.id); println!("Branch: {}", session.branch); println!("Worktree: {}", session.worktree_path.display()); println!("Port Range: {}-{}", session.port_range_start, session.port_range_end); println!("PID: {:?}", session.process_id); } Err(e) => eprintln!("Failed: {}", e), } // List all sessions let sessions = handler::list_sessions().unwrap(); for session in sessions { println!("{}: {} ({:?})", session.branch, session.agent, session.status); } // Get specific session let session = handler::get_session("feature/new-api").unwrap(); // Restart session with different agent let restarted = handler::restart_session("feature/new-api", Some("kiro".to_string())).unwrap(); // Destroy session handler::destroy_session("feature/new-api").unwrap(); ``` -------------------------------- ### Create and List Multiple Shards (Bash) Source: https://github.com/wirasm/shards/blob/main/TESTING.md Tests the ability to create and manage multiple shards concurrently. It starts three distinct shards, verifies that all are listed as active using `shards list`, and checks that each shard has its own unique Git branch. This demonstrates isolation and proper management of multiple shard instances. ```bash # Create multiple shards ./target/debug/shards start shard-1 echo "Shard 1" ./target/debug/shards start shard-2 echo "Shard 2" ./target/debug/shards start shard-3 echo "Shard 3" # Verify all are listed ./target/debug/shards list # Expected: Shows all 3 shards as Active # Verify each has unique branch cd .shards/shard-1 && git branch --show-current && cd ../.. cd .shards/shard-2 && git branch --show-current && cd ../.. cd .shards/shard-3 && git branch --show-current && cd ../.. # Expected: Each shows different shard_* branch ``` -------------------------------- ### SHARDS Regression Test Output Example Source: https://github.com/wirasm/shards/blob/main/REGRESSION_TESTING.md An example of the expected output from the SHARDS regression test script. This output demonstrates the script's progress through different test phases, including session creation, management, and overall test completion status. ```bash [15:30:01] Starting SHARDS regression tests... [15:30:01] Building SHARDS... ✅ Build successful [15:30:02] === Phase 1: Testing Session Creation === [15:30:02] Testing session creation: claude-native ✅ Session created successfully: regression-test-claude-native-20260113-153002 [15:30:05] Testing session creation: codex-iterm2 ✅ Session created successfully: regression-test-codex-iterm2-20260113-153002 ... ✅ All session creation tests passed [15:30:15] === Phase 2: Testing Session Management === ✅ Session listing works ✅ Found session in list: regression-test-claude-native-20260113-153002 ... ✅ Regression tests completed! ``` -------------------------------- ### CLI List Command Output Source: https://github.com/wirasm/shards/blob/main/PR_MERGE_COMPLETION.md Example output of the 'list' command in the Shards CLI, showing active shards with their branch, agent, status, creation time, port range, and process information. This output reflects the integrated features from PR #9 (Port Range) and PR #8 (Process status). ```text Active shards: ┌──────────────────┬─────────┬─────────┬─────────────────────┬─────────────┬─────────────┐ │ Branch │ Agent │ Status │ Created │ Port Range │ Process │ ├──────────────────┼─────────┼─────────┼─────────────────────┼─────────────┼─────────────┤ │ test-all-feat... │ kiro │ active │ 2026-01-14T13:42... │ 1-10 │ Stop(57729) │ └──────────────────┴─────────┴─────────┴─────────────────────┴─────────────┴─────────────┘ ``` -------------------------------- ### Start Claude Code Agent Test Source: https://github.com/wirasm/shards/blob/main/TESTING.md Starts the Claude Code agent within a new shard. This test verifies the agent's launch, with an alternative command using an alias. ```bash ./target/debug/shards start claude-test claude # or with alias: ./target/debug/shards start cc-test cc # Expected: Claude Code starts in terminal ``` -------------------------------- ### Integrate Port Allocation and PID Capture in Session Creation (Rust) Source: https://github.com/wirasm/shards/blob/main/PR_MERGE_ANALYSIS.md Demonstrates the integration of port allocation and PID capture within the `create_session` function in `src/sessions/handler.rs`. It shows how to allocate ports, spawn a terminal, capture its process ID, and initialize the `Session` struct with these new fields. ```rust pub fn create_session(...) -> Result { // ... existing validation ... // FROM PR #9: Allocate ports let (port_start, port_end) = operations::allocate_port_range(...)?; // ... worktree creation ... // FROM PR #10: Copy include patterns files::handler::copy_include_patterns(...)?; // FROM PR #8: Capture PID from terminal spawn let spawn_result = terminal::handler::spawn_terminal(...)?; let process_id = spawn_result.process_id; // Create session with ALL fields let session = Session { // ... existing fields ... port_start, port_end, process_id, }; // ... save session ... } ``` -------------------------------- ### ClaudeAgent Initialization and Configuration (Rust) Source: https://github.com/wirasm/shards/blob/main/docs/PROMPT_PIPING_PLAN.md Demonstrates how to initialize and configure the ClaudeAgent. This includes setting the binary path and default flags for subsequent command executions. The agent supports various capabilities like headless operation, JSON output, and stdin piping. ```rust use std::path::Path; use std::process::Stdio; use async_trait::async_trait; use tokio::process::Command; use tokio::time::{timeout, Duration}; use serde_json::Value; use super::traits::{ AgentRunner, AgentCapabilities, AgentError, HeadlessOptions, HeadlessResult }; #[derive(Debug, Clone)] pub struct ClaudeAgent { /// Binary name or path (default: "claude") pub binary: String, /// Default flags to pass to all invocations pub default_flags: Vec, } impl Default for ClaudeAgent { fn default() -> Self { Self { binary: "claude".to_string(), default_flags: vec![], } } } impl ClaudeAgent { pub fn new(binary: impl Into) -> Self { Self { binary: binary.into(), default_flags: vec![], } } pub fn with_flags(mut self, flags: Vec) -> Self { self.default_flags = flags; self } } #[async_trait] impl AgentRunner for ClaudeAgent { fn name(&self) -> &'static str { "claude" } fn display_name(&self) -> &'static str { "Claude Code" } fn capabilities(&self) -> AgentCapabilities { AgentCapabilities { supports_headless: true, supports_resume: true, supports_json_output: true, supports_stdin_pipe: true, provides_session_id: true, } } fn is_available(&self) -> bool { which::which(&self.binary).is_ok() } fn binary(&self) -> &str { &self.binary } async fn run_headless( &self, prompt: &str, working_dir: &Path, options: &HeadlessOptions, ) -> Result { // Build command let mut cmd = Command::new(&self.binary); cmd.current_dir(working_dir) .arg("-p") .arg(prompt) .arg("--output-format") .arg("json") .stdout(Stdio::piped()) .stderr(Stdio::piped()); // Add default flags for flag in &self.default_flags { cmd.arg(flag); } // Add allowed tools if specified if let Some(tools) = &options.allowed_tools { cmd.arg("--allowedTools").arg(tools); } // Add extra flags for flag in &options.extra_flags { cmd.arg(flag); } // Execute with optional timeout let output = if let Some(secs) = options.timeout_secs { timeout(Duration::from_secs(secs), cmd.output()) .await .map_err(|_| AgentError::Timeout { seconds: secs })?? } else { cmd.output().await? }; let stdout = String::from_utf8_lossy(&output.stdout).to_string(); let stderr = String::from_utf8_lossy(&output.stderr).to_string(); let exit_code = output.status.code().unwrap_or(-1); // Parse JSON output let (session_id, result) = if output.status.success() { match serde_json::from_str::(&stdout) { Ok(json) => { let sid = json.get("session_id") .and_then(|v| v.as_str()) .map(String::from); let res = json.get("result") .and_then(|v| v.as_str()) .map(String::from); (sid, res) } Err(_) => (None, None), } } else { (None, None) }; Ok(HeadlessResult { success: output.status.success(), exit_code, session_id, stdout, stderr, result, }) } fn build_resume_command(&self, session_id: &str) -> Option { let flags = if self.default_flags.is_empty() { String::new() } else { format!(" {}", self.default_flags.join(" ")) }; Some(format!("claude --resume {}{}", session_id, flags)) } fn build_interactive_command(&self) -> String { if self.default_flags.is_empty() { "claude".to_string() } else { format!("claude {}", self.default_flags.join(" ")) } } fn parse_session_id(&self, stdout: &str) -> Option { // Try to parse as JSON first if let Ok(json) = serde_json::from_str::(stdout) { if let Some(sid) = json.get("session_id").and_then(|v| v.as_str()) { return Some(sid.to_string()); } } // Fallback: try to find session_id in output (for streaming JSON) for line in stdout.lines() { if let Ok(json) = serde_json::from_str::(line) { if let Some(sid) = json.get("session_id").and_then(|v| v.as_str()) { return Some(sid.to_string()); } } } None } } ``` -------------------------------- ### Prompt Markdown Format for Meta Context Source: https://github.com/wirasm/shards/blob/main/scripts/RALPH_LOOP.md Illustrates the structure of the `prompt.md` file, which contains meta-context for Ralph Loop. This includes implementation rules, key dependencies, and patterns to mirror, providing constant guidance across iterations. ```markdown # Implementation Rules 1. Work ONE user story at a time 2. Follow existing patterns 3. Use vertical slice architecture 4. Maintain compatibility 5. Validate immediately # Key Dependencies - dependency1 = "version" - dependency2 = "version" # Patterns to Mirror [Code examples from existing codebase] ``` -------------------------------- ### Basic Testing Strategy (Shell) Source: https://github.com/wirasm/shards/blob/main/PR_MERGE_ANALYSIS.md Outlines a testing strategy that includes running unit tests, type checks, linting, and building the release version of the project after each merge. This ensures code quality and stability throughout the development process. ```bash # After Each Merge 1. **Unit Tests**: `cargo test` 2. **Type Check**: `cargo check` 3. **Lint**: `cargo clippy` 4. **Build**: `cargo build --release` ``` -------------------------------- ### Override Agent Profile with Explicit Command (Bash) Source: https://github.com/wirasm/shards/blob/main/TESTING.md Verifies that providing an explicit command when starting a shard overrides any command specified in the selected agent profile. This ensures that the explicit command takes precedence. The command used is `shards start --agent `. ```bash # Test that explicit command overrides profiles ./target/debug/shards start override-test --agent test echo "Override command" # Expected: Uses "echo 'Override command'" instead of profile command ``` -------------------------------- ### Handle Duplicate Shard Name Error (Bash) Source: https://github.com/wirasm/shards/blob/main/TESTING.md Tests the error handling for attempting to create a shard with a name that already exists. The CLI should return a specific error message indicating that the shard name is already in use. The command used is `shards start` with a duplicate name. ```bash # Try to create shard with existing name ./target/debug/shards start shard-1 echo "Duplicate test" # Expected: Error "Shard 'shard-1' already exists" ``` -------------------------------- ### Handle Invalid Agent Profile Error (Bash) Source: https://github.com/wirasm/shards/blob/main/TESTING.md Tests the error handling when attempting to use an agent profile that is not defined in the Shards configuration. The CLI should return an error message indicating that the specified agent profile was not found. The command used is `shards start --agent `. ```bash # Try to use non-existent agent profile ./target/debug/shards start invalid-agent-test --agent nonexistent # Expected: Error "Agent profile 'nonexistent' not found" ``` -------------------------------- ### Handle Non-existent Shard Operations Errors (Bash) Source: https://github.com/wirasm/shards/blob/main/TESTING.md Tests error handling for operations on shards that do not exist. This includes attempting to stop or get information about a non-existent shard, expecting specific error messages for each case. Commands tested are `shards stop ` and `shards info `. ```bash # Try to stop non-existent shard ./target/debug/shards stop non-existent # Expected: Error "Shard 'non-existent' not found" # Try to get info for non-existent shard ./target/debug/shards info non-existent # Expected: Error "Shard 'non-existent' not found" ``` -------------------------------- ### Create Command Structure for Shards CLI (Rust) Source: https://github.com/wirasm/shards/blob/main/docs/PROMPT_PIPING_PLAN.md Defines the `CreateCommand` struct using Rust's `clap` derive macros for parsing command-line arguments. It includes fields for branch name, agent selection, prompt source (direct, file, stdin), timeout, and execution options. ```rust // src/cli/app.rs #[derive(Parser)] pub struct CreateCommand { /// Branch name for the shard #[arg(value_name = "BRANCH")] pub branch: String, /// Agent to use (claude, codex, gemini, aider, kiro) #[arg(short, long, default_value = "claude")] pub agent: String, /// Initial prompt to run in headless mode before opening terminal #[arg(short, long, value_name = "PROMPT")] pub prompt: Option, /// Read prompt from file #[arg(long, value_name = "FILE")] pub prompt_file: Option, /// Read prompt from stdin (use "-" as value) /// Example: echo "Fix the bug" | shards create mybranch --prompt - #[arg(long = "prompt-stdin", visible_alias = "prompt=-")] pub prompt_stdin: bool, /// Timeout for headless execution in seconds #[arg(long, value_name = "SECONDS")] pub timeout: Option, /// Don't open terminal after headless execution #[arg(long)] pub no_terminal: bool, /// Allowed tools for headless execution (Claude: --allowedTools) #[arg(long, value_name = "TOOLS")] pub allowed_tools: Option, /// Additional flags to pass to the agent #[arg(long = "flag", short = 'f', value_name = "FLAG")] pub flags: Vec, } ``` -------------------------------- ### Monitor Progress with `watch` and `tail` Source: https://github.com/wirasm/shards/blob/main/scripts/RALPH_LOOP.md This command monitors the `progress.txt` file for agent learning progress. It uses `watch` to execute `tail` every 5 seconds, displaying the last 20 lines of the specified progress file. This helps in observing the agent's learning curve and identifying potential issues. ```bash watch -n 5 tail -20 .kiro/artifacts/prds/my-feature/progress.txt ``` -------------------------------- ### Rust: Create Session with Headless Options Source: https://github.com/wirasm/shards/blob/main/docs/PROMPT_PIPING_PLAN.md Defines options for creating a new session, including initial prompts for headless execution, file-based prompts, stdin prompts, timeouts, terminal skipping, agent flags, and allowed tools. It also defines the result structure for session creation, which includes the session object, headless output, and success status. ```rust use crate::agents::{AgentRegistry, traits::{HeadlessOptions, AgentError}}; use std::path::PathBuf; /// Options for creating a session with optional prompt #[derive(Debug, Clone, Default)] pub struct CreateSessionOptions { /// Initial prompt to run in headless mode before opening terminal pub prompt: Option, /// Read prompt from this file path pub prompt_file: Option, /// Read prompt from stdin (when value is "-") pub prompt_stdin: bool, /// Timeout for headless execution in seconds pub timeout_secs: Option, /// Skip opening terminal after headless (keep session for later) pub no_terminal: bool, /// Additional flags for the agent pub agent_flags: Vec, /// Allowed tools for headless execution pub allowed_tools: Option, } /// Result of session creation #[derive(Debug)] pub struct CreateSessionResult { pub session: Session, /// Output from headless execution (if prompt was provided) pub headless_output: Option, /// Whether headless execution succeeded pub headless_success: Option, } ``` -------------------------------- ### Progress Log TXT Format for Iteration History Source: https://github.com/wirasm/shards/blob/main/scripts/RALPH_LOOP.md Shows the append-only log format for `progress.txt`, detailing the accomplishments of each iteration. It includes timestamps, implemented stories, changed files, and learnings, providing visibility into the agent's progress. ```text # Progress Log - Feature Name Started: 2026-01-14T10:00:00Z ## 2026-01-14T10:15:00Z - US001 - Implemented feature X - Files changed: src/module/file.rs - **Learnings:** - Pattern discovered: Use Arc> for shared state - Gotcha: GPUI requires git dependency --- ## 2026-01-14T10:30:00Z - US002 ... ``` -------------------------------- ### Rust: Core Session Creation Logic Source: https://github.com/wirasm/shards/blob/main/docs/PROMPT_PIPING_PLAN.md Implements the `create_session` function, which handles agent validation, prompt resolution, worktree creation, headless execution, terminal spawning, and session record creation. It returns a `CreateSessionResult` or a `SessionError` if any step fails. ```rust pub async fn create_session( branch: &str, agent_name: &str, options: CreateSessionOptions, config: &ShardsConfig, registry: &AgentRegistry, ) -> Result { // 1. Validate agent exists and is available let agent = registry.get(agent_name) .ok_or_else(|| SessionError::UnknownAgent { agent: agent_name.to_string(), available: registry.list().iter().map(|a| a.name().to_string()).collect(), })?; if !agent.is_available() { return Err(SessionError::AgentNotInstalled { agent: agent_name.to_string(), binary: agent.binary().to_string(), }); } // 2. Resolve prompt from various sources let prompt = resolve_prompt(&options).await?; // 3. Create worktree (existing logic) let worktree_path = create_worktree(branch, config)?; // 4. Run headless if prompt provided let (agent_session_id, headless_output, headless_success) = if let Some(prompt_text) = &prompt { // Check agent supports headless if !agent.capabilities().supports_headless { return Err(SessionError::HeadlessNotSupported { agent: agent_name.to_string(), }); } let headless_opts = HeadlessOptions { timeout_secs: options.timeout_secs, extra_flags: options.agent_flags.clone(), allowed_tools: options.allowed_tools.clone(), }; match agent.run_headless(prompt_text, &worktree_path, &headless_opts).await { Ok(result) => { if !result.success { // Log warning but continue - user may want to debug in terminal tracing::warn!( "Headless execution failed with exit code {}: {}", result.exit_code, result.stderr ); } (result.session_id, Some(result.stdout), Some(result.success)) } Err(AgentError::Timeout { seconds }) => { return Err(SessionError::HeadlessTimeout { seconds }); } Err(e) => { return Err(SessionError::HeadlessFailed { message: e.to_string() }); } } } else { (None, None, None) }; // 5. Determine terminal command let terminal_command = if let Some(ref sid) = agent_session_id { // Resume the headless session agent.build_resume_command(sid) .unwrap_or_else(|| agent.build_interactive_command()) } else { // Fresh interactive session agent.build_interactive_command() }; // 6. Spawn terminal (unless --no-terminal) let process_info = if !options.no_terminal { Some(spawn_terminal(&worktree_path, &terminal_command, config)?) } else { None }; // 7. Create session record let session = Session { name: branch.to_string(), branch: format!("shard_{}", generate_hash(branch)), worktree_path: worktree_path.clone(), agent: agent_name.to_string(), agent_session_id, // NEW FIELD initial_prompt: prompt, // NEW FIELD status: if options.no_terminal { SessionStatus::Headless } else { SessionStatus::Interactive }, process_id: process_info.as_ref().map(|p| p.process_id), process_name: process_info.as_ref().and_then(|p| p.process_name.clone()), process_start_time: process_info.as_ref().and_then(|p| p.process_start_time), }; Ok(CreateSessionResult { session, headless_output, headless_success }) } ``` -------------------------------- ### Run Ralph on GUI Feature (Default Worktree) Source: https://github.com/wirasm/shards/blob/main/scripts/RALPH_LOOP.md This script executes the Ralph learning process for a GUI feature within the default worktree. It takes a path to the artifacts directory as an argument. Ensure you are in the correct project directory before running this command. ```bash ./scripts/ralph-loop.sh .kiro/artifacts/prds/shards-gui-gpui-pty ``` -------------------------------- ### Final Cleanup Commands Source: https://github.com/wirasm/shards/blob/main/TESTING.md Commands to perform a final cleanup after testing, including removing the test configuration file and running the general cleanup command. ```bash # Remove test config rm ~/.shards/config.toml # Final cleanup ./target/debug/shards cleanup ``` -------------------------------- ### Troubleshoot SHARDS Build Failures Source: https://github.com/wirasm/shards/blob/main/REGRESSION_TESTING.md Commands to troubleshoot build failures in SHARDS. This typically involves ensuring all necessary dependencies are installed and running a check to verify the build configuration. ```bash # Ensure dependencies are installed # Run a build check cargo check ``` -------------------------------- ### Stop All Test Shards Source: https://github.com/wirasm/shards/blob/main/TESTING.md This command stops all currently running test shards. It iterates through a list of predefined test shard names and executes the 'stop' command for each. ```bash ./target/debug/shards stop git-test ./target/debug/shards stop shard-1 ./target/debug/shards stop shard-2 ./target/debug/shards stop shard-3 ./target/debug/shards stop terminal-test ./target/debug/shards stop ghostty-test ./target/debug/shards stop auto-test ./target/debug/shards stop default-agent-test ./target/debug/shards stop profile-test ./target/debug/shards stop override-test ``` -------------------------------- ### Mock Claude Agent Implementation in Rust Source: https://github.com/wirasm/shards/blob/main/docs/PROMPT_PIPING_PLAN.md This Rust code defines a mock implementation of the Claude agent for testing purposes. It simulates successful and failed agent runs, provides agent capabilities, and handles headless execution, session ID parsing, and command building. It relies on the `async_trait` crate and custom `AgentRunner`, `AgentCapabilities`, `HeadlessOptions`, `HeadlessResult`, and `AgentError` types. ```rust // src/agents/mock.rs #[cfg(test)] pub struct MockClaudeAgent { pub should_succeed: bool, pub session_id: Option, pub output: String, } #[cfg(test)] impl MockClaudeAgent { pub fn success() -> Self { Self { should_succeed: true, session_id: Some("mock-session-123".to_string()), output: r#"{"session_id": "mock-session-123", "result": "Done"}"#.to_string(), } } pub fn failure() -> Self { Self { should_succeed: false, session_id: None, output: "Error: Something went wrong".to_string(), } } } #[cfg(test)] #[async_trait] impl AgentRunner for MockClaudeAgent { fn name(&self) -> &'static str { "claude" } fn display_name(&self) -> &'static str { "Claude Code (Mock)" } fn capabilities(&self) -> AgentCapabilities { AgentCapabilities { supports_headless: true, supports_resume: true, supports_json_output: true, supports_stdin_pipe: true, provides_session_id: true, } } fn is_available(&self) -> bool { true } fn binary(&self) -> &str { "claude" } async fn run_headless( &self, _prompt: &str, _working_dir: &Path, _options: &HeadlessOptions, ) -> Result { if self.should_succeed { Ok(HeadlessResult { success: true, exit_code: 0, session_id: self.session_id.clone(), stdout: self.output.clone(), stderr: String::new(), result: Some("Done".to_string()), }) } else { Err(AgentError::HeadlessFailed { message: "Mock failure".to_string(), exit_code: 1, }) } } fn build_resume_command(&self, session_id: &str) -> Option { Some(format!("claude --resume {}", session_id)) } fn build_interactive_command(&self) -> String { "claude".to_string() } fn parse_session_id(&self, _stdout: &str) -> Option { self.session_id.clone() } } ``` -------------------------------- ### List and Cleanup Shards Source: https://github.com/wirasm/shards/blob/main/TESTING.md Commands to verify the status of shards and clean up any orphaned entries. 'list' shows active shards, and 'cleanup' removes unassociated shard data. ```bash # Verify cleanup ./target/debug/shards list # Expected: "No active shards" # Test cleanup command ./target/debug/shards cleanup # Expected: "No orphaned shards found" or cleans up any orphaned entries ``` -------------------------------- ### List Shards - Shards CLI Source: https://context7.com/wirasm/shards/llms.txt Displays all active shards for the current project in a formatted table. The table includes columns for Branch, Agent, Status, and Creation Time. ```bash shards list # Output: # Active shards: # ┌──────────────────┬─────────┬──────────┬─────────────────────┐ # │ Branch │ Agent │ Status │ Created │ # ├──────────────────┼─────────┼──────────┼─────────────────────┤ # │ feature/add-login│ claude │ Active │ 2024-01-15T10:30:00Z│ # │ bugfix/auth-issue│ kiro │ Active │ 2024-01-15T11:45:00Z│ # └──────────────────┴─────────┴──────────┴─────────────────────┘ ``` -------------------------------- ### Troubleshoot SHARDS Terminal Launch Issues Source: https://github.com/wirasm/shards/blob/main/REGRESSION_TESTING.md Commands to diagnose issues related to launching terminals for SHARDS. This involves checking if the required terminal emulators are installed and accessible in the system's PATH. ```bash # Check if terminals are installed which ghostty which iterm2 ``` -------------------------------- ### Integrate SHARDS Regression Tests into GitHub Actions Source: https://github.com/wirasm/shards/blob/main/REGRESSION_TESTING.md An example of how to integrate the SHARDS regression tests into a GitHub Actions workflow. This step ensures that automated testing is performed as part of the CI/CD pipeline. ```yaml # Example GitHub Actions step - name: Run Regression Tests run: ./scripts/regression-test.sh ``` -------------------------------- ### Rust: Headless Claude Agent Integration Tests Source: https://github.com/wirasm/shards/blob/main/docs/PROMPT_PIPING_PLAN.md These integration tests verify the functionality of the headless Claude agent. They cover basic prompting, handling timeouts, and resuming previous sessions. Dependencies include the 'tokio' runtime and the 'claude' agent CLI. ```rust // tests/integration/headless_test.rs #[tokio::test] #[ignore] // Requires claude CLI installed async fn test_headless_simple_prompt() { let agent = ClaudeAgent::default(); let temp_dir = TempDir::new().unwrap(); // Initialize a git repo in temp dir init_git_repo(temp_dir.path()).await; let options = HeadlessOptions::default(); let result = agent.run_headless( "What is 2 + 2? Reply with just the number.", temp_dir.path(), &options, ).await.unwrap(); assert!(result.success); assert!(result.session_id.is_some()); assert!(result.stdout.contains("4") || result.result.map(|r| r.contains("4")).unwrap_or(false)); } #[tokio::test] #[ignore] async fn test_headless_with_timeout() { let agent = ClaudeAgent::default(); let temp_dir = TempDir::new().unwrap(); init_git_repo(temp_dir.path()).await; let options = HeadlessOptions { timeout_secs: Some(1), // Very short timeout ..Default::default() }; let result = agent.run_headless( "Write a 10000 word essay about the history of computing.", temp_dir.path(), &options, ).await; assert!(matches!(result, Err(AgentError::Timeout { seconds: 1 }))); } #[tokio::test] #[ignore] async fn test_session_resume_flow() { let agent = ClaudeAgent::default(); let temp_dir = TempDir::new().unwrap(); init_git_repo(temp_dir.path()).await; // First prompt let result1 = agent.run_headless( "Remember the number 42.", temp_dir.path(), &HeadlessOptions::default(), ).await.unwrap(); let session_id = result1.session_id.expect("Should have session ID"); // Second prompt with resume let options = HeadlessOptions { extra_flags: vec![ "--resume".to_string(), session_id.clone(), ], ..Default::default() }; let result2 = agent.run_headless( "What number did I ask you to remember?", temp_dir.path(), &options, ).await.unwrap(); assert!(result2.success); assert!(result2.stdout.contains("42") || result2.result.map(|r| r.contains("42")).unwrap_or(false)); } ``` -------------------------------- ### Get Shard Status Information Source: https://github.com/wirasm/shards/blob/main/README.md Retrieves and displays the current status and details of a specific Shard workspace. This is useful for monitoring the state of an AI agent's isolated environment. ```bash shards status ``` -------------------------------- ### Create Shard with Initial Prompt (Claude Code) Source: https://github.com/wirasm/shards/blob/main/docs/PROMPT_PIPING_PLAN.md This command demonstrates how to create a new Shard (worktree) and immediately initiate an AI agent session with a specific prompt. The agent runs in headless mode, and its completion is tracked before the terminal is opened for interactive use. This relies on Claude Code's ability to run prompts in headless mode (`-p`) and output a session ID for later resumption (`--resume`). ```bash shards create mybranch --agent claude --prompt "Fix the auth bug" ``` -------------------------------- ### Create a New Shard Workspace Source: https://github.com/wirasm/shards/blob/main/README.md Creates a new isolated development workspace (shard) for an AI agent. It takes the desired branch name and the agent command as arguments. Each shard gets its own Git worktree and branch. ```bash shards create --agent # Examples: shards create kiro-session --agent kiro shards create claude-work --agent claude shards create gemini-task --agent gemini ``` -------------------------------- ### Load Shards Configuration Programmatically (Rust) Source: https://context7.com/wirasm/shards/llms.txt Shows how to load the Shards configuration hierarchy programmatically using the `ShardsConfig` struct in Rust and access agent commands and settings. ```rust use shards::core::config::ShardsConfig; // Load merged configuration hierarchy let config = ShardsConfig::load_hierarchy().unwrap_or_default(); // Get agent command with flags let claude_cmd = config.get_agent_command("claude"); // Returns: "claude --yolo --dangerously-skip-permissions" let kiro_cmd = config.get_agent_command("kiro"); // Returns: "kiro-cli chat --trust-all-tools --verbose" // Access configuration values println!("Default agent: {}", config.agent.default); println!("Terminal: {:?}", config.terminal.preferred); ``` -------------------------------- ### Stop and Cleanup Shard (Bash) Source: https://github.com/wirasm/shards/blob/main/TESTING.md Covers the process of stopping an active shard and verifying its removal from the list of active shards. It also includes checking that the associated worktree is cleaned up. Commands used are `shards stop` and `shards list`. ```bash # Stop the shard ./target/debug/shards stop test-basic # Verify it's gone ./target/debug/shards list # Expected: "No active shards" # Verify worktree is cleaned up ls .shards/ # Expected: Directory should be empty or not exist ``` -------------------------------- ### Bash Command for Shards Creation Source: https://github.com/wirasm/shards/blob/main/PR_MERGE_COMPLETION.md Demonstrates the command-line interface (CLI) usage for creating a new shard with specific features integrated. This command is used for the final integration test, verifying the combined functionality of PR #10, PR #9, and PR #8. ```bash ./target/release/shards create test-all-features --agent kiro ```