# How the Developer Agent Iterates Through Tasks and Generates Diffs Sequentially in SWE-Agent

> Learn how the SWE-Agent Developer agent iterates tasks sequentially. Discover its state-graph architecture, contextual research tools, and unified diff generation for code changes.

- Repository: [LangTalks/swe-agent](https://github.com/langtalks/swe-agent)
- Tags: deep-dive
- Published: 2026-03-05

---

**The Developer agent processes implementation plans sequentially using a state-graph architecture that tracks task indices, performs contextual research via tool calls, and generates unified diffs by parsing structured code change requests from Claude Sonnet.**

The Developer agent in the `langtalks/swe-agent` repository automates software engineering tasks by walking through atomic implementation steps. It combines a LangGraph-based state machine with intelligent diff generation to transform high-level plans into concrete code changes.

## The State-Graph Architecture for Sequential Task Processing

The Developer agent operates as a **state-graph** defined in [`agent/developer/graph.py`](https://github.com/langtalks/swe-agent/blob/main/agent/developer/graph.py). This graph orchestrates the entire workflow, moving between nodes that handle initialization, research, diff generation, and task progression.

### Initializing Task Indices

When the workflow begins, the `start_implementing` function establishes the iteration counters. It sets both `current_task_idx` and `current_atomic_task_idx` to 0, ensuring the agent starts at the first task of the implementation plan.

```python

# From agent/developer/graph.py, lines 33-38

def start_implementing(state: SoftwareDeveloperState):
    """Initialize indices to start processing the first task."""
    return {
        "current_task_idx": 0,
        "current_atomic_task_idx": 0,
    }

```

### Loading Files and Resetting Research Context

Before processing any atomic task, the `prepare_for_implementation` node loads the target file content (or creates a placeholder for new files) and clears previous research messages. It also captures the current repository structure using the `write` tool's `get_files_structure` function to provide context for the upcoming changes.

## Research Phase: Context Gathering for Atomic Tasks

For each atomic task, the agent enters a research loop to gather necessary context before generating code changes.

### Generating Research Plans

The `get_clear_implementation_plan_for_atomic_task` function prompts Claude Sonnet to produce a concise research snippet. It passes the current file content, task description, and any prior context to determine what information is needed to implement the specific atomic task.

### Determining When Research is Complete

The `should_continue_implementation_research` function acts as a conditional router in the state-graph. It inspects the last research message: if the message contains a tool call (indicating the model wants to search for more information), the graph routes back to the research tool node. Otherwise, it proceeds to the diff generation phase.

### Tool Execution Loop

When research tools are needed, the `research_tool_node` executes **search** and **codemap** tools. It appends their results to `atomic_implementation_research` and loops back to the planning step, allowing the model to iteratively refine its understanding until sufficient context is gathered.

## Diff Generation: From Code Change Requests to File Updates

Once research is complete, the `creating_diffs_for_task` node generates and applies code changes. This function distinguishes between creating new files and modifying existing ones.

### Handling New Files

For new files, the agent prompts Claude to write the complete file content directly. The model outputs the full source code, which the agent then writes to the specified path.

### Editing Existing Files with Structured Blocks

For existing files, the process involves structured generation to ensure precise edits:

1. **Line Number Injection**: The agent adds line numbers to the current file content to help the model identify specific locations.

2. **Structured Output**: Claude is prompted to emit a `<code_change_request>` block containing:
   - `original_code_snippet`: The exact existing code to be replaced
   - `edit_code_snippet`: The new code to insert

3. **Diff Application**: The agent parses these blocks, computes the affected line range by matching the original snippet, and rewrites only those specific lines in the file.

This approach ensures that the Developer agent generates **unified diffs sequentially**, one atomic task at a time, maintaining file integrity throughout the implementation process.

## Progression Logic: Moving to the Next Task

After applying changes for the current atomic task, the `proceed_to_next_atomic_task` function advances the iteration counters.

### Index Management and Completion Detection

The function increments `current_atomic_task_idx`. If all atomic tasks for the current top-level task are exhausted, it increments `current_task_idx` and resets the atomic index to 0.

Finally, `is_implementation_complete` checks whether `current_task_idx` exceeds the total number of tasks in the implementation plan. If complete, it returns `END` to terminate the graph; otherwise, it routes back to `prepare_for_implementation` to process the next file.

## Running the Developer Agent

To execute the Developer agent programmatically, initialize the state with an implementation plan and invoke the compiled graph:

```python
from agent.developer.graph import swe_developer
from agent.developer.state import SoftwareDeveloperState
from agent.common.entities import ImplementationPlan

# Load the implementation plan (typically generated by the Architect agent)

plan = ImplementationPlan.parse_file("plan.json")

# Initialize state with the plan

state = SoftwareDeveloperState(implementation_plan=plan)

# Execute the graph - automatically iterates through all tasks

final_state = swe_developer.invoke(state)

print(f"Completed {len(final_state.diffs)} diffs across all tasks")

```

For debugging or step-by-step execution, access the underlying `StateGraph` object:

```python

# Access the underlying graph for manual stepping

graph = swe_developer.graph

# Manually execute specific nodes

ctx = graph.apply(state, "start_implementing")
ctx = graph.apply(ctx, "prepare_for_implementation")
ctx = graph.apply(ctx, "get_clear_implementation_plan_for_atomic_task")

```

## Key Files in the Developer Agent

| File | Purpose | Key Components |
|------|---------|----------------|
| [`agent/developer/graph.py`](https://github.com/langtalks/swe-agent/blob/main/agent/developer/graph.py) | Core state-graph definition | `start_implementing`, `prepare_for_implementation`, `creating_diffs_for_task`, `proceed_to_next_atomic_task`, `is_implementation_complete` |
| [`agent/developer/state.py`](https://github.com/langtalks/swe-agent/blob/main/agent/developer/state.py) | State management | `SoftwareDeveloperState`, `current_task_idx`, `current_atomic_task_idx`, `atomic_implementation_research` |
| [`agent/common/entities.py`](https://github.com/langtalks/swe-agent/blob/main/agent/common/entities.py) | Data schemas | `ImplementationPlan`, task definitions |
| [`agent/tools/write.py`](https://github.com/langtalks/swe-agent/blob/main/agent/tools/write.py) | File operations | `get_files_structure` for repo context |
| [`agent/tools/search.py`](https://github.com/langtalks/swe-agent/blob/main/agent/tools/search.py) | Research tools | Code search functionality |
| [`agent/tools/codemap.py`](https://github.com/langtalks/swe-agent/blob/main/agent/tools/codemap.py) | Research tools | Code mapping and navigation |

## Summary

The Developer agent in SWE-Agent iterates through tasks and generates diffs sequentially through a sophisticated state-graph architecture:

- **State-machine workflow**: Uses LangGraph to manage transitions between initialization, research, diff generation, and task progression nodes defined in [`agent/developer/graph.py`](https://github.com/langtalks/swe-agent/blob/main/agent/developer/graph.py).
- **Dual indexing system**: Tracks progress via `current_task_idx` (top-level tasks) and `current_atomic_task_idx` (sub-tasks), managed by `start_implementing` and `proceed_to_next_atomic_task`.
- **Research loop**: Implements iterative context gathering through `get_clear_implementation_plan_for_atomic_task` and `should_continue_implementation_research`, allowing the agent to search codebases until sufficient context is gathered.
- **Structured diff generation**: Distinguishes between new files (full content generation) and existing files (precise edits via `<code_change_request>` blocks with `original_code_snippet` and `edit_code_snippet` parsing).
- **Sequential completion check**: Uses `is_implementation_complete` to determine when all tasks are finished, routing back to file preparation or terminating the graph.

## Frequently Asked Questions

### How does the Developer agent handle multiple files in an implementation plan?

The Developer agent processes files sequentially based on the `current_task_idx` index. Each top-level task in the `ImplementationPlan` typically corresponds to a specific file. After completing all atomic tasks for the current file (tracked by `current_atomic_task_idx`), the `proceed_to_next_atomic_task` function increments the task index and resets the atomic counter, allowing `prepare_for_implementation` to load the next target file.

### What triggers the research phase versus immediate diff generation?

The `should_continue_implementation_research` function inspects the last message in the `atomic_implementation_research` list. If the message contains a tool call (indicating the model wants to execute a search or codemap operation), the state-graph routes to the `research_tool_node`. If the message contains a final answer or implementation plan without tool calls, the graph proceeds directly to `creating_diffs_for_task`.

### How does the agent ensure precise edits to existing files?

For existing files, the `creating_diffs_for_task` function injects line numbers into the current content before prompting Claude Sonnet. The model returns a structured `<code_change_request>` XML block containing `original_code_snippet` (the exact text to replace) and `edit_code_snippet` (the new code). The agent parses these blocks, locates the matching line range in the original file, and rewrites only those specific lines, ensuring atomic, precise modifications.

### Can the Developer agent create entirely new files?

Yes. When `prepare_for_implementation` detects that the target file does not exist, it creates a placeholder entry. During the `creating_diffs_for_task` phase, the agent detects this new file condition and prompts Claude to generate the complete file content rather than edit snippets. The resulting content is written directly to the new file path, allowing the agent to scaffold entirely new modules or configuration files as part of the implementation plan.