Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Condense output standards documentation for clarity
Maximilian Roosd3a218d0faeb
diff --git a/CLAUDE.md b/CLAUDE.mdindex aaa84531d..43d012a85 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -50,173 +50,53 @@ Five canonical message patterns with their emojis:**Core Principle: Separate output by who generates it, not by message type.**-- **stdout**: All output generated by worktrunk (messages, directives, data, errors, warnings, progress)-- **stderr**: All output generated by child processes (git, npm, user commands)+- **stdout**: All worktrunk output (messages, directives, errors, warnings, progress)+- **stderr**: All child process output (git, npm, user commands)-This creates clean semantic separation: "Is it from us or from a child process?"+**Why:** Simple reasoning (one decision point), better for piping (`wt list | jq`), child output never interferes with directives. Trade-off: violates Unix convention of errors→stderr, but our "errors" are structured program output, not crashes.-**Benefits:**-- Simple reasoning: one decision point (source), not multiple (type, severity, etc.)-- No cross-stream coordination needed (no flushing stderr before stdout directives)-- Better for piping: `wt list | jq` gets clean data, `wt switch -x "npm install" 2>/dev/null` suppresses npm noise-- Child process output never interferes with our protocol (directives, structured output)--**Trade-off:**-- Violates Unix convention that errors go to stderr-- Our "errors" are structured program output (validation failures, formatted git errors), not unexpected crashes-- Panics and assertion failures still go to stderr via Rust's default handler (which is correct)--**Implementation:**```rust-use worktrunk::styling::{println, ERROR, ERROR_EMOJI};-// ALL our output goes to stdout (including errors)println!("{ERROR_EMOJI} {ERROR}Branch already exists{ERROR:#}");-println!("✅ Created worktree");-println!("💡 Run 'wt list' to see all worktrees");-```-**Child processes:**-```rust-// Redirect child stdout to stderr so all child output goes there+// Redirect child processes to stderrlet wrapped = format!("{{ {}; }} 1>&2", command);-Command::new("sh")- .arg("-c")- .arg(&wrapped)- .stdout(Stdio::inherit()) // Actually goes to stderr due to redirect- .stderr(Stdio::inherit())- .status()?;+Command::new("sh").arg("-c").arg(&wrapped).status()?;```### Temporal Locality: Output Should Be Close to Operations**Core Principle: Output should appear immediately adjacent to the operations they describe.**-Users experience commands as temporal sequences. Output that appears far from its triggering operation creates confusion and breaks the mental model of what's happening.--**When to Show Progress Messages:**--Progress messages (`🔄 Doing something...`) are only appropriate for operations that take perceptible time (>400ms). For fast operations like file checks or simple file writes, show only the result.--- **Show progress for**: Operations that take noticeable time (>400ms)- - Git operations (rebase, push, commit, worktree operations)- - Network requests- - Building/compiling- - Operations on large files- - Batch operations that iterate multiple slow steps--- **Don't show progress for**: Fast operations (<400ms)- - Checking if a line exists in a file- - Writing a single line to a config file- - Reading small files- - Simple validations+Output that appears far from its triggering operation breaks the user's mental model.-**Examples:**+**Progress messages only for slow operations (>400ms):** Git operations, network requests, builds. Not for file checks or config reads.+**Pattern for sequential operations:**```rust-// ❌ Bad - progress for fast operation-output::progress("🔄 Checking config file...")?;-let exists = config_file.exists(); // <1ms - way too fast for progress-output::success("Config file checked")?;--// ✅ Good - just show the result for fast operations-if config_file.exists() {- println!("Config file found at {}", path);+for item in items {+ output::progress(format!("🔄 Removing {item}..."))?;+ perform_operation(item)?;+ output::success(format!("Removed {item}"))?; // Immediate feedback}--// ✅ Good - progress for slow operation-output::progress("🔄 Removing worktree...")?;-repo.remove_worktree(&path)?; // Takes >400ms - worth showing progress-output::success("Removed worktree")?;```-**The Two Patterns:**--1. **Progress → Operation → Success** (for sequential operations)- ```- 🔄 Removing worktree for feature...- ✅ Removed worktree for feature- 🔄 Removing worktree for bugfix...- ✅ Removed worktree for bugfix- ```--2. **Progress → Operation → Success → Summary** (for complex multi-step operations)- ```- 🔄 Squashing 3 commits into one...- 🔄 Generating commit message...- [commit message display]- ✅ Squashed 3 commits into one ← Immediate feedback- 🔄 Rebasing onto main...- ...- ✅ Merged feature → main ← Final summary- Squashed 3 commits ← Context in summary- ```--**Bad pattern - output decoupled from operations:**+**Bad - output decoupled from operations:**```🔄 Removing worktree for feature...🔄 Removing worktree for bugfix...-🔄 Removing worktree for hotfix...- ← Long delay, no feedback-Removed worktree for feature ← All output at the end+ ← Long delay, no feedback+Removed worktree for feature ← All output at the endRemoved worktree for bugfix-Removed worktree for hotfix-```--**Why this matters:**--- **Temporal locality**: Feedback appears when the action completes, not seconds/minutes later-- **User confidence**: Immediate success messages confirm each operation worked-- **Debugging**: If something fails, users know exactly which operation failed-- **Progress visibility**: Users can see what's done vs. what's still in progress-- **Interrupt recovery**: If user hits Ctrl+C, they know what completed-- **Natural mental model**: Matches how users think about sequential operations--**Implementation patterns:**--```rust-// Pattern 1: Simple sequential operations (like batch remove)-for item in items {- // Show what we're about to do- output::progress(format!("🔄 {CYAN}Removing {item}...{CYAN:#}"))?;-- // Do the operation- let result = perform_operation(item)?;-- // Show immediate success- output::success(format!("Removed {item}"))?;-}--// Pattern 2: Complex operation with substeps-output::progress("🔄 Starting complex operation...")?;--// Substep 1-output::progress("🔄 Validating...")?;-validate()?;-output::success("Validated")?;--// Substep 2-output::progress("🔄 Processing...")?;-process()?;-output::success("Processed")?;--// Final summary (optional, for context)-output::success("Completed complex operation")?;```-**Red flags - violations of temporal locality:**+**Red flags:**+- Collecting messages in a buffer: `let mut messages = Vec::new()` → emit immediately instead+- Single success message for batch operations → show success after each item+- No progress before slow operations → user sees nothing, then sudden output+- Progress without matching success → always pair them-1. **Collecting messages in a buffer**: `let mut messages = Vec::new(); messages.push(...)` → emit immediately instead-2. **Single success message for batch operations**: Loop that shows all successes at the end-3. **No progress before slow operations**: User sees nothing, then suddenly output appears-4. **Progress without matching success**: Progress messages that aren't followed by success/failure-5. **Success before operation**: Showing success message before operation completes (async timing bugs)--**Apply this to:**-- Batch operations: Show progress + success for each item in the loop-- Multi-step operations: Show success after each major step completes-- Slow operations: Show progress immediately before starting-- Error handling: Show failure immediately when detected, not collected for later+**Why this matters:** Immediate feedback builds confidence, failed operations are obvious, Ctrl+C interrupts don't leave uncertainty, matches how users think about sequential operations.### Semantic Style Constants@@ -263,67 +143,34 @@ println!("{HINT_EMOJI} {HINT}Use 'wt list' to see all worktrees{HINT:#}");### Composing Styles-Compose styles using anstyle methods (`.bold()`, `.fg_color()`, etc.):+Compose styles using anstyle methods (`.bold()`, `.fg_color()`, etc.). **Always bold branch names:**```rust-use worktrunk::styling::{println, AnstyleStyle, ERROR, WARNING};+use worktrunk::styling::{println, AnstyleStyle, ERROR};// Error with bold branch namelet error_bold = ERROR.bold();println!("❌ Branch '{error_bold}{branch}{error_bold:#}' already exists");-// Warning with bold-let warning_bold = WARNING.bold();-println!("🟡 {warning_bold}{message}{warning_bold:#}");-// Just bold (no color)let bold = AnstyleStyle::new().bold();println!("Switched to worktree: {bold}{branch}{bold:#}");```-### Branch Name Formatting--**Always format branch names in bold** when they appear in messages:--```rust-use worktrunk::styling::{println, AnstyleStyle, ERROR};--// Good - bold branch name in error-let error_bold = ERROR.bold();-println!("❌ Branch '{error_bold}{branch}{error_bold:#}' already exists");--// Good - bold in regular message-let bold = AnstyleStyle::new().bold();-println!("Switched to worktree: {bold}{branch}{bold:#}");--// Bad - plain branch name-println!("Switched to worktree: {branch}")-```-### Information Hierarchy & Path Styling**Principle: Bold what answers the user's question, dim what provides context.**-Style elements based on **user intent**, not data type. The same information (like a file path) can be primary in one context and secondary in another.--**File paths:**--- **Primary information** (answering the user's main question): **Bold**- - Example: `wt config list` - paths are the answer to "where is my config?"--- **Secondary information** (contextual metadata): **Dim**- - Example: `wt switch` output - path provides context, branch name is the answer+Style based on **user intent**, not data type. Branch names are always bold. Paths are bold when they're the answer (`wt config list`), dimmed when they're context (`wt switch` output).```rust-use worktrunk::styling::AnstyleStyle;--// Path as primary answer (config list)+// Path as primary answerlet bold = AnstyleStyle::new().bold();println!("Global Config: {bold}{}{bold:#}", path.display());-// Path as secondary context (switch output)+// Path as secondary contextlet dim = AnstyleStyle::new().dimmed();-println!("✅ Created {bold}{branch}{bold:#}\n {dim}Path: {}{dim:#}", path.display());+println!("✅ Created {bold}{branch}{bold:#}\n{dim}Path: {}{dim:#}", path.display());```**Visual hierarchy patterns:**@@ -339,61 +186,18 @@ println!("✅ Created {bold}{branch}{bold:#}\n {dim}Path: {}{dim:#}", path.disp**Core Principle: No manual indentation for secondary information.**-Styling (bold, dim, color) already provides visual hierarchy. Manual indentation adds cognitive load without adding clarity.--**Rules:**--1. **Secondary paths, metadata**: No indent, use dimmed styling only- ```rust- // Good - dimming provides hierarchy- println!("✅ Created {bold}{branch}{bold:#}");- println!("{dim}Path: {}{dim:#}", path.display());-- // Bad - unnecessary indent- println!("✅ Created {bold}{branch}{bold:#}");- println!(" {dim}Path: {}{dim:#}", path.display());- ```--2. **File lists (bullets)**: No indent, bullet provides visual separation- ```rust- // Good - bullet is enough- for file in &files {- println!("{dim}•{dim:#} {}", file);- }-- // Bad - redundant indent- for file in &files {- println!(" {dim}•{dim:#} {}", file);- }- ```--3. **Log file paths**: No indent, dimming is sufficient- ```rust- // Good- println!("{dim}Logs: {}{dim:#}", path);-- // Bad- println!(" {dim}Logs: {}{dim:#}", path);- ```--4. **Quoted content (commands, config)**: Use `format_with_gutter()` instead of manual indents- ```rust- // Good - gutter provides visual separation- print!("{}", format_with_gutter(&command));-- // Bad - manual indentation- for line in command.lines() {- println!(" {}", line);- }- ```--**Exception:** Nested hierarchies where structural relationships must be clear (not yet encountered in this codebase).--**Rationale:**-- Styling already creates visual hierarchy-- Indentation is redundant cognitive load-- Simpler output is easier to scan-- Follows git's own output conventions+Styling (bold, dim, color) already provides visual hierarchy. Don't add redundant indentation.++```rust+// Good - dimming provides hierarchy+println!("✅ Created {bold}{branch}{bold:#}");+println!("{dim}Path: {}{dim:#}", path.display());++// Bad - unnecessary indent+println!(" {dim}Path: {}{dim:#}", path.display());+```++For quoted content (commands, config), use `format_with_gutter()` instead of manual indents.### Color Detection@@ -414,42 +218,6 @@ All handled automatically by `anstream` macros.- **Unicode-aware** - Width calculations respect emoji and CJK characters (via `StyledLine`)- **Graceful degradation** - Must work without color support-### Complete Examples--```rust-use worktrunk::styling::{- eprintln, println, AnstyleStyle,- ERROR, ERROR_EMOJI, WARNING, WARNING_EMOJI, HINT, HINT_EMOJI-};-use anstyle::Style;--// Simple error-println!("{ERROR_EMOJI} {ERROR}Working tree has uncommitted changes{ERROR:#}");--// Error with bold branch name-let error_bold = ERROR.bold();-println!("{ERROR_EMOJI} Branch '{error_bold}{branch}{error_bold:#}' already exists");--// Warning with bold-let warning_bold = WARNING.bold();-println!("{WARNING_EMOJI} {warning_bold}Uncommitted changes detected{warning_bold:#}");--// Hint-println!("{HINT_EMOJI} {HINT}Use 'wt list' to see all worktrees{HINT:#}");--// Bold branch name in regular message-let bold = Style::new().bold();-println!("Switched to worktree: {bold}{branch}{bold:#}");--// Complex multi-part error-let error_bold = ERROR.bold();-println!("{ERROR_EMOJI} Not a fast-forward from '{error_bold}{target_branch}{error_bold:#}' to HEAD");--// Dimmed secondary info-let dim = Style::new().dimmed();-println!(" {dim}Path: {path}{dim:#}");-```-### StyledLine APIFor complex table formatting with proper width calculations, use `StyledLine`:@@ -473,63 +241,21 @@ See `src/commands/list/render.rs` for advanced usage.### Gutter Formatting for Quoted Content-The **gutter** is a subtle visual separator (single space with background color) used for quoted content like commands and configuration.--**Core Principle: Gutter provides all the separation needed**--The gutter's visual distinction is sufficient - no additional indentation required. This keeps the output clean and maximizes horizontal space for content.--#### Formatting Rules--1. **Gutter at column 0**: `format_with_gutter(content)`- - Gutter appears at column 0- - Content appears at column 1 (after the gutter + 1 space)- - The colored background provides visual separation from surrounding text--2. **Preserve internal structure**: Multi-line content maintains its original formatting- - Don't strip leading whitespace that's part of the content- - Apply gutter treatment uniformly to each line+Use `format_with_gutter()` for quoted content (commands, config). The gutter is a visual separator (colored background) at column 0 - no additional indentation needed.-#### Examples--**Config display:**-```-Global Config: /path/to/config- worktree-path = "../{main-worktree}.{branch}"-- [llm]-```+```rust+use worktrunk::styling::format_with_gutter;-**Command approval:**-```-project wants to execute:- [ -d {repo_root}/target ] &&- [ ! -e {worktree}/target ] &&- cp -cR {repo_root}/target/. {worktree}/target/+print!("{}", format_with_gutter(&command));```-**Command execution:**+**Example output:**```🔄 Executing (post-create):npm install```-#### Implementation--```rust-use worktrunk::styling::format_with_gutter;--// Simple usage - gutter provides all separation-print!("{}", format_with_gutter(&command));-print!("{}", format_with_gutter(&config));-```--**Function signature:**-```rust-/// Arguments:-/// - content: Text to format (preserves internal structure for multi-line)-pub fn format_with_gutter(content: &str) -> String-```+The colored space at column 0 provides visual separation from surrounding text.## Output System Architecture@@ -614,33 +340,19 @@ For the complete API, see `src/output/global.rs`.When adding new output capabilities:-1. **Add the function to both handlers** - `InteractiveOutput` and `DirectiveOutput`-2. **Add dispatch in global.rs** - Route to both handlers via enum match-3. **Never add mode parameters** - The handlers already know their mode--**Example: Adding a hypothetical `warning()` function**--This illustrates the pattern - follow these steps when adding any new output capability:+1. Add the function to both `InteractiveOutput` and `DirectiveOutput` handlers+2. Add dispatch in `global.rs` - route to both handlers via enum match+3. Never add mode parameters - the handlers already know their mode+**Example pattern:**```rust// In interactive.rs-impl InteractiveOutput {- pub fn warning(&mut self, message: String) -> io::Result<()> {- println!("{WARNING_EMOJI} {WARNING}{message}{WARNING:#}");- Ok(())- }-}--// In directive.rs-impl DirectiveOutput {- pub fn warning(&mut self, message: String) -> io::Result<()> {- // Warnings go to stderr in directive mode- write!(io::stderr(), "{}\0", strip_str(&message))?;- io::stderr().flush()- }+pub fn warning(&mut self, message: String) -> io::Result<()> {+ println!("{WARNING_EMOJI} {WARNING}{message}{WARNING:#}");+ Ok(())}-// In global.rs+// In global.rs - dispatch to both handlerspub fn warning(message: impl Into<String>) -> io::Result<()> {OUTPUT_CONTEXT.with(|ctx| {let msg = message.into();@@ -654,116 +366,30 @@ pub fn warning(message: impl Into<String>) -> io::Result<()> {### Why This Matters-This architecture maintains the "one canonical path" principle from the global guidelines:--**Without this architecture**, you'd see:-- Mode conditionals scattered throughout 50+ command functions-- HIGH CARDINALITY: Two divergent code paths that must be kept in sync-- Mode parameters threading through the entire call stack-- Easy to forget one branch when changing behavior--**With this architecture**:-- Commands have ONE code path that works for both modes (LOW CARDINALITY)-- Mode-specific behavior encapsulated in two handler files-- Adding new commands requires zero mode awareness-- Changing behavior means updating one function, not hunting down 50+ conditionals+This maintains "one canonical path": commands have ONE code path that works for both modes (LOW CARDINALITY), not mode conditionals scattered throughout 50+ functions (HIGH CARDINALITY). Mode-specific behavior is encapsulated in two handler files. Same pattern as logging frameworks (`log`, `tracing`).-This is the same pattern as logging frameworks (`log`, `tracing`) - you configure once at startup, then the rest of the code just logs without caring where it goes.--### Red Flags and Solutions--**Red Flag: "I need to check if we're in interactive mode"**--This is always wrong. If you're tempted to check the mode, you have two options:--1. **The behavior should be the same in both modes** - Just do it directly, no check needed-2. **The behavior should differ between modes** - Add a new output function that encapsulates the difference--**Example scenario**: "I want to print a hint in interactive mode but not directive mode"--```rust-// ❌ DON'T DO THIS-if mode == OutputMode::Interactive {- println!("💡 Use 'wt list' to see all worktrees");-}--// ✅ DO THIS - progress() already handles this (shown in interactive, suppressed in directive)-output::progress("💡 Use 'wt list' to see all worktrees")?;-```--If the output function you need doesn't exist yet, follow the pattern in "Adding New Output Functions" above.+**Red Flag:** "I need to check if we're in interactive mode" - This is always wrong. Either the behavior should be the same (just do it), or different (add a new output function). Never check the mode in commands.### Architectural Constraint: --internal Commands Must Use Output System-**CRITICAL: Commands that support `--internal` mode must NEVER use direct print macros (`print!()`, `println!()`, `eprint!()`, or `eprintln!()`).**--Commands that support the `--internal` flag (switch, remove, merge) emit directives for shell wrapper integration. Using direct print statements bypasses the output system and causes directive leaks - directives become visible to users in interactive mode.--#### The Problem+**CRITICAL: Commands that support `--internal` mode must NEVER use direct print macros (`print!()`, `println!()`, `eprint!()`, `eprintln!()`).**-When a command uses `println!()` directly:--1. **Interactive mode**: Output appears correctly (luck, not design)-2. **Directive mode**: Direct prints get concatenated with NUL-terminated directives, causing directives to leak into user-visible output--**Example of the bug:**-```-🔄 Starting (background):-__WORKTRUNK_CD__/Users/name/workspace/repo.branch-Created new worktree...-```+Using direct prints bypasses the output system and causes directive leaks - directives become visible to users.-The `__WORKTRUNK_CD__` directive should be invisible, parsed only by the shell wrapper.--#### The Solution--**Commands supporting `--internal` must use `crate::output::*` functions exclusively:**+**Restricted files** (see `scripts/check-output-system.sh`):+- `src/commands/worktree.rs` (switch, remove)+- `src/commands/merge.rs`+**Always use output system:**```rust-// ❌ NEVER DO THIS in commands that support --internal+// ❌ NEVER in --internal commandsprintln!("🔄 Starting operation...");-print!("{}", formatted_output);-eprintln!("Some progress message");-eprint!("{}", error_message);-// ✅ ALWAYS DO THIS+// ✅ ALWAYScrate::output::progress("🔄 Starting operation...")?;-crate::output::progress(formatted_output)?;-crate::output::progress("Some progress message")?;-crate::output::progress(error_message)?;-```--#### Which Commands Are Restricted--Files that support `--internal` mode (see `scripts/check-output-system.sh`):--- `src/commands/worktree.rs` (switch, remove commands)-- `src/commands/merge.rs` (merge command)--Other command files can use direct `println!()` if they never emit directives.--#### Enforcement--The restriction is enforced by:--1. **Lint script**: `scripts/check-output-system.sh` checks restricted files for direct print usage-2. **Integration tests**: `tests/integration_tests/shell_wrapper.rs` executes commands through the actual bash wrapper to catch directive leaks--Run the lint script to verify compliance:-```bash-./scripts/check-output-system.sh```-#### Why This Matters--This constraint maintains architectural integrity:--- **Separation of concerns**: Output formatting is centralized in the output system-- **Mode transparency**: Commands don't need to know which mode they're running in-- **Protocol correctness**: Directives are properly NUL-terminated and never leak-- **Testability**: Shell integration can be tested end-to-end--When adding new functionality to restricted commands, always ask: "Does this need output?" If yes, use `crate::output::progress()` or `crate::output::success()`, never direct prints.+**Enforcement:** Run `./scripts/check-output-system.sh` to verify compliance. Integration tests catch directive leaks via `tests/integration_tests/shell_wrapper.rs`.## Command Execution Principles