Back to Picoclaw

AgentLoop File Split

docs/architecture/agent-refactor/loop-split.md

0.2.83.3 KB
Original Source

AgentLoop File Split

Note: This document describes the file split that was completed in a previous phase. The loop_* naming has since been renamed to agent_* and turn_*. See agent-rename-plan.md for the current file structure.

Overview

The pkg/agent/loop.go file (originally 4384 lines) has been split into 12 focused source files. This is a pure refactoring with no behavioral changes.

Goals

  • Reduce cognitive load when navigating agent loop code
  • Enable parallel work by decoupling concerns
  • Maintain all existing functionality and tests
  • Keep imports minimal per file

Original File Map (Renamed in Phase 2)

Old FileNew FileResponsibility
loop.goagent.goCore AgentLoop struct, Run, Stop, Close
loop_turn.goturn_coord.go + pipeline_*.goTurn execution: coordinator + Pipeline methods
loop_utils.goagent_utils.goStandalone utility functions
loop_init.goagent_init.goNewAgentLoop constructor and tool registration
loop_message.goagent_message.goMessage handling and routing
loop_command.goagent_command.goCommand processing
loop_mcp.goagent_mcp.goMCP runtime
loop_event.goagent_event.goEvent system helpers
loop_media.goagent_media.goMedia resolution
loop_outbound.goagent_outbound.goResponse publishing
loop_transcribe.goagent_transcribe.goAudio transcription
loop_steering.goagent_steering.goSteering queue
loop_inject.goagent_inject.goSetter injection

Current File Structure

See agent-rename-plan.md for the complete current file structure.

Phase 2: Rename and Pipeline Restructuring

Phase 2 completed the following:

  1. File renaming: All loop_* files renamed to agent_* or turn_*
  2. Turn state merging: turn.go + turn_exec.goturn_state.go
  3. Pipeline extraction: Split large runTurn into Pipeline methods

Pipeline Architecture

The Pipeline methods provide structured turn execution:

MethodFileResponsibility
SetupTurn()pipeline_setup.goHistory assembly, message building, candidate selection
CallLLM()pipeline_llm.goPreLLM hooks, fallback, retry, AfterLLM hooks
ExecuteTools()pipeline_execute.goTool execution with hooks
Finalize()pipeline_finalize.goSession persistence, compression

Core Principles Applied

1. Same Package, Independent Files

All files belong to the agent package and compile together. This preserves the original visibility rules.

2. No Logic Changes

All functions were moved verbatim. The extraction preserved behavioral equivalence.

3. Shared Types in turn_state.go

The turnState, turnExecution, Control, ToolControl, and LLMPhase types are centralized in turn_state.go.

Testing

All existing tests pass. The 5 failing tests (TestGlobalSkillFileContentChange and 4 Seahorse tests) are pre-existing failures unrelated to this refactor.

Build status: go build ./pkg/agent/... passes with no errors.

See Also