Skip to content

[Enhancement]: Auto-correct Go imports in Code Mode using goimports #116

@spachava753

Description

@spachava753

Enhancement Category

Code mode improvements

Problem or Use Case

When executing Go code in Code Mode (execute_go_code), the LLM-generated code (run.go) frequently contains missing or unused imports. This leads to compilation errors during go build, causing the LLM to trigger a regeneration loop to fix the imports. This wastes tokens, increases latency, and degrades the user experience.

Proposed Solution

Integrate goimports into the ExecuteCode workflow in internal/codemode/executor.go to automatically fix import issues before compilation.

Detailed Plan:

  1. Pre-processing: After writing run.go to the temporary directory and before running go mod tidy, execute goimports -w run.go.
  2. Change Detection: Compare the content of run.go before and after running goimports.
  3. Reporting:
    • If imports were modified, append a notification to the tool's output (e.g., "Note: Imports were auto-corrected: added 'fmt', removed 'strings'").
    • Ideally, parse the changes to list specifically which imports were added or removed.
  4. Error Handling:
    • If goimports fails (e.g., ambiguous imports or syntax errors), proceed to the standard go build step. This allows the existing error reporting mechanism (returning the compilation error to the LLM) to handle the failure, as goimports might not be able to resolve everything.
    • Ensure the system checks for the presence of goimports and handles its absence gracefully (skip the step).

Alternatives Considered

  • LLM Prompting: Trying to prompt the LLM to be more careful with imports. This is unreliable because Go requires imports to be declared at the top of the file. Since LLMs generate text sequentially, they often don't know exactly which libraries will be needed until they write the implementation logic later in the file, making it difficult to predict the correct imports upfront.
  • Go Fix: go fix is unsuitable for this task as it is designed for API migrations rather than automatic import resolution.

Impact Scope

Everyone using CPE

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions