Skip to content

[file-diet] Refactor trial_command.go - Split 1000-line file into focused modules #12747

@agentic-workflows-dev

Description

@agentic-workflows-dev

Overview

The file pkg/cli/trial_command.go has grown to 1000 lines, making it difficult to maintain and test. While some functionality has already been extracted to trial_repository.go (473 lines) and trial_support.go (408 lines), the main command file remains oversized with a complex 372-line orchestration function. This task involves refactoring it into smaller, focused files with improved test coverage.

Current State

  • File: pkg/cli/trial_command.go
  • Size: 1000 lines
  • Test Coverage: 607 lines in trial_command_test.go (ratio: 0.61)
  • Complexity: High - Contains workflow orchestration, UI rendering, result processing, and command setup
  • Related Files: trial_repository.go (473 LOC), trial_support.go (408 LOC), trial_command_lipgloss_test.go (248 LOC), trial_issue_mode_test.go (134 LOC)
Full File Analysis

Current Structure

Types (4):

  • WorkflowTrialResult - Result data structure
  • CombinedTrialResult - Multi-workflow result aggregation
  • RepoConfig - Repository configuration grouping
  • TrialOptions - Command options container

Functions (8):

  1. NewTrialCommand() - 130 lines - Command definition with flags and help text
  2. RunWorkflowTrials() - 372 lines - Main orchestration logic (VERY LARGE)
  3. getCurrentGitHubUsername() - 13 lines - GitHub API helper
  4. showTrialConfirmation() - 223 lines - UI confirmation dialog
  5. triggerWorkflowRun() - 44 lines - Workflow execution
  6. parseIssueSpec() - 23 lines - Issue number parsing
  7. saveTrialResult() - 16 lines - JSON file writer
  8. copyTrialResultsToHostRepo() - ~100 lines (estimated) - Result copying

Complexity Hotspots

  1. RunWorkflowTrials() function (lines 196-567, 372 lines):

    • Repository mode determination (80 lines)
    • Host repository setup (60 lines)
    • Secret tracking setup (20 lines)
    • Clone repository handling (50 lines)
    • Workflow disabling logic (40 lines)
    • Multi-trial loop orchestration (80 lines)
    • Result collection and saving (40 lines)
    • High cyclomatic complexity with nested conditionals
  2. showTrialConfirmation() function (lines 583-804, 223 lines):

    • Complex UI rendering with Lipgloss
    • Multiple conditional sections
    • Tight coupling to console rendering
  3. Command setup (NewTrialCommand(), 130 lines):

    • Extensive help text and examples
    • Flag configuration
    • Validation logic mixed with setup

Areas with High Coupling

  • Orchestration logic tightly coupled to repository operations
  • UI confirmation logic mixed with business logic
  • Result processing scattered across multiple functions
  • GitHub API calls interspersed throughout

Refactoring Strategy

Proposed File Splits

Based on semantic analysis, split the file into the following focused modules:

  1. trial_command.go (target: 200-250 lines)

    • Command definition and flag setup
    • High-level orchestration (calling other modules)
    • Types: TrialOptions, RepoConfig
    • Functions: NewTrialCommand(), simplified RunWorkflowTrials()
  2. trial_orchestration.go (target: 250-300 lines)

    • Main trial execution orchestration
    • Multi-trial loop logic
    • Repository mode determination
    • Workflow installation coordination
    • Functions: Extracted orchestration logic from RunWorkflowTrials()
  3. trial_results.go (target: 150-200 lines)

    • Result collection and aggregation
    • JSON file operations
    • Artifact handling
    • Types: WorkflowTrialResult, CombinedTrialResult
    • Functions: saveTrialResult(), copyTrialResultsToHostRepo(), result processing helpers
  4. trial_workflow_execution.go (target: 150-200 lines)

    • Workflow triggering and tracking
    • Run ID management
    • Workflow state monitoring
    • Functions: triggerWorkflowRun(), execution helpers
  5. trial_ui.go (target: 250-300 lines)

    • User confirmation dialogs
    • Console rendering and formatting
    • Progress indicators
    • Functions: showTrialConfirmation(), UI helper functions
  6. trial_helpers.go (target: 100-150 lines)

    • Small utility functions
    • GitHub username fetching
    • Issue spec parsing
    • Functions: getCurrentGitHubUsername(), parseIssueSpec(), other utilities

Interface Abstractions

Consider introducing interfaces to reduce coupling:

// TrialOrchestrator handles high-level trial coordination
type TrialOrchestrator interface {
    Execute(specs []string, opts TrialOptions) error
}

// ResultCollector manages trial result collection and storage
type ResultCollector interface {
    Collect(runID string, workflowName string) (*WorkflowTrialResult, error)
    SaveToFile(filename string, result any) error
    CopyToRepository(tempDir, dateTimeID string, workflowNames []string, targetRepoSlug string) error
}

// WorkflowExecutor handles workflow triggering and monitoring
type WorkflowExecutor interface {
    Trigger(repoSlug, workflowName, triggerContext string) (string, error)
    WaitForCompletion(repoSlug, runID string, timeout time.Duration) error
}
Test Coverage Plan

Add comprehensive tests for each new file:

  1. trial_orchestration_test.go

    • Test cases: Repository mode selection, multi-trial loops, error handling, cleanup
    • Target coverage: >80%
    • Focus: Orchestration logic paths
  2. trial_results_test.go

    • Test cases: Result JSON marshaling, file operations, artifact copying, error conditions
    • Target coverage: >80%
    • Focus: Data handling and file I/O
  3. trial_workflow_execution_test.go

    • Test cases: Workflow triggering, run ID extraction, timeout handling, API errors
    • Target coverage: >80%
    • Focus: Workflow lifecycle management
  4. trial_ui_test.go

    • Test cases: Confirmation rendering, user interaction, display formatting (leverage existing trial_command_lipgloss_test.go)
    • Target coverage: >80%
    • Focus: UI rendering correctness
  5. trial_helpers_test.go

    • Test cases: GitHub username fetching, issue parsing (URLs, refs, numbers), edge cases
    • Target coverage: >80%
    • Focus: Utility function correctness
  6. Update trial_command_test.go

    • Refocus on command-level integration tests
    • Reduce duplication with new focused test files
    • Target coverage: >80%

Implementation Guidelines

  1. Preserve Behavior: Ensure all existing functionality works identically
  2. Maintain Exports: Keep public API unchanged (NewTrialCommand, RunWorkflowTrials, TrialOptions)
  3. Add Tests First: Write tests for extracted functions before moving them
  4. Incremental Changes: Split one module at a time in this order:
    • Extract trial_helpers.go first (smallest, least coupled)
    • Extract trial_results.go (clear domain boundary)
    • Extract trial_workflow_execution.go (workflow operations)
    • Extract trial_ui.go (UI rendering)
    • Extract trial_orchestration.go (main logic)
    • Update trial_command.go to use new modules
  5. Run Tests Frequently: Verify make test-unit passes after each extraction
  6. Update Imports: Ensure all import paths reference the correct package
  7. Document Changes: Add comments explaining module boundaries and responsibilities

Acceptance Criteria

  • Original file is split into 6 focused files (command, orchestration, results, execution, ui, helpers)
  • Each new file is under 300 lines
  • trial_command.go reduced to ~200-250 lines (command setup only)
  • All tests pass (make test-unit)
  • Test coverage is ≥80% for new files
  • No breaking changes to public API (NewTrialCommand, RunWorkflowTrials, TrialOptions)
  • Code passes linting (make lint)
  • Build succeeds (make build)
  • Existing integration tests pass (trial_command_test.go, trial_issue_mode_test.go)
Additional Context

Related Files to Review:

  • trial_repository.go - Repository operations (already extracted)
  • trial_support.go - Secret tracking and artifact handling (already extracted)
  • trial_command_lipgloss_test.go - UI rendering tests (can inform trial_ui_test.go)
  • trial_issue_mode_test.go - Issue mode integration tests

Repository Guidelines:

  • Follow patterns in .github/agents/developer.instructions.agent.md
  • Use logger.New("cli:trial_*") for debug logging in new files
  • Use console formatting helpers for user-facing output
  • Maintain existing error handling patterns

Code Organization Principles:

  • Prefer many small files grouped by functionality
  • Each file should have a single, clear responsibility
  • Avoid circular dependencies between new modules
  • Keep types close to their usage

Testing Strategy:

  • Match existing test patterns in pkg/cli/*_test.go
  • Use table-driven tests for multiple scenarios
  • Prefer require.* for setup, assert.* for validations
  • Include helpful assertion messages

Priority: Medium
Effort: Large (6 new files, ~1000 lines to refactor, comprehensive test updates)
Expected Impact: Significantly improved maintainability, easier testing, reduced complexity, better separation of concerns

AI generated by Daily File Diet

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions