Coding Agent Development: Algorithms and Patterns for AI-Assisted Programming
This article maps the shift from traditional programming constraints to coding agent development, detailing four inference-time search algorithms (ReAct, Best-of-N, tree search, context scheduling) and five engineering patterns (Plan-and-Execute, verification gates, orchestrator-worker, maker-checker, spec-first) with their trade-offs and over-engineering traps.
Reading font

Traditional programming relies on algorithms to trade time against space and design patterns to control coupling, driven by finite compute, memory, and human cognitive limits. Coding agent development faces a new constraint triad: limited context windows, probabilistic model output, and the cost of external verification. The article argues that a corresponding set of "algorithms" and "patterns" is already emerging in production toolchains.
Inference-Time Search Algorithms
1. Linear Closed-Loop Convergence: ReAct and Reflexion
ReAct (Reason + Act) forms the basic while loop of almost every interactive coding agent: the model reasons about the next action, calls tools (read, search, edit, run tests), receives real observations (errors, outputs), and feeds them back into the next reasoning step. This replaces one-shot generation with environment-grounded feedback but remains a single-path greedy search ; an early misdiagnosis can cascade into compounding errors.
Reflexion adds an explicit correction step: on test or compile failure, the model first produces a structured diagnosis summarizing why the last change failed and which assumptions were falsified, stores this lesson in a short-term memory buffer, then attempts the next fix. This reduces repeated spinning on the same error.
2. Width Sampling: Best-of-N with Test Filtering
When a single dialogue chain gets stuck in a local optimum, the algorithmic extension is parallel width sampling. For the same defect-fix or function-implementation task, N candidate implementations are generated in isolated workspaces, then batch-verified by deterministic unit tests, static checks, or an independent scorer. The highest-scoring, most-complete patch is selected. The premise is explicit: verification cost must be far lower than manual triage cost, and the task must have clear executable test criteria . Without automated tests, generating 10 candidates only deepens the review quagmire.
3. State Tree Search: Tree Search and MCTS
For complex cross-file modifications or multi-path refactors, single-path trial-and-error often requires returning to a clean pre-change state. Treating each repository snapshot (Git commit or independent worktree) as a tree node yields Tree Search (e.g., CodeTree) or Monte Carlo Tree Search (MCTS, as in SWE-Search) :
State expansion : from a clean node, explore two to three distinct fix strategies in isolated sandboxes.
Environment scoring : run compilation, unit tests, or review scoring to evaluate whether a branch moves closer to or further from the goal.
Pruning and backtracking : if branch A introduces more regressions, discard it and revert to the parent node to pursue branch B, rather than layering patches on an already corrupted workspace.
These algorithms transplant classic graph/game search into code modification, but the cost is proportional: token consumption and sandbox execution time multiply, so they are justified only for high-value, single-path-stuck hard problems.
4. Context Scheduling Algorithms: Retrieval, Compression, and Checkpoint Reset
If search strategies are CPU scheduling, context management is the memory management algorithm of the coding agent era . Limited window capacity and irrelevant logs dilute model attention. Mature toolchains combine three scheduling strategies:
On-demand paged retrieval : use directory trees, symbol indexes, or text search to locate key positions, reading only relevant function fragments instead of entire large files.
Observation compression and summarization : a single test failure may emit thousands of stack-trace lines; retain core error frames and failed assertions, fold repetitive dependency output, preserving bandwidth for subsequent repair rounds.
Threshold-driven eviction and reset : when multi-round failures and abandoned patches fill the window, keep a "confirmed root-cause and constraint summary," clear historical process, and restart the session — effectively a manual clean garbage collection.
The article includes a diagram comparing the three search algorithm families on progression style, compute overhead, and applicability boundaries, noting that fault tolerance increases downward while total token and sandbox costs rise multiplicatively or by orders of magnitude.
Five Engineering Patterns
While algorithms govern how single or multiple inference runs approach a correct solution, patterns address how software teams organize unstable probabilistic generation into predictable, reviewable engineering workflows. Unlike GoF's 23 class-inheritance/object-composition patterns, coding agent patterns cluster around control-flow orchestration, context isolation, and deterministic gates .
1. Plan-and-Execute (Planning-Execution Separation)
Before editing files, force a two-phase flow: phase one is read-only — the agent investigates relevant modules, dependencies, and constraints, outputting a written plan listing files to change, interface modifications, and verification commands; phase two executes the plan item by item. This mirrors "design interfaces before coding" and moves cheap "text plan correction" before expensive "cross-file code rework," drastically reducing rollback cost after a wrong turn.
2. Harness / Verification Gate (Deterministic Guardrails and Gates)
The foundational pattern: wrap the probabilistic model in a deterministic shell using repository rule files, strong type checking, lint, automated tests, and restricted sandboxes. Do not rely on the model to "remember" team conventions; instead, make it automatically run the toolchain after every change. Compiler errors, type mismatches, red unit tests are objective machine exit codes that pull the agent back on track, freeing humans from manual typo and syntax checks.
3. Orchestrator-Worker / Subagent Isolation (Master-Worker Orchestration and Context Isolation)
For large cross-module tasks, stuffing all file searches, trial logs, and code edits into one conversation drowns the main context in noise. The pattern splits responsibilities: the Orchestrator retains only the global task list, core architectural constraints, and final integration view; it delegates broad code reconnaissance, independent submodule implementation, or specialized test generation to Workers/Subagents with clean contexts, even assigning parallel workers separate working directories (e.g., Git worktrees). This is essentially "scope and module encapsulation for the agent era" — intermediate noise digests locally, only distilled conclusions or clean diffs return to the main flow.
4. Evaluator-Optimizer / Maker-Checker (Generation and Independent Review Opposition)
An agent in the same session often exhibits "self-justification" inertia: after writing logic, asking it to self-review tends to rubber-stamp its own reasoning. Splitting "Maker" and "Checker" into isolated contexts simulates real-team code review: the generator delivers code that passes basic tests; the reviewer, unburdened by history, scrutinizes against design specs, concurrency boundaries, and security checklists, bouncing issues back for repair. In practice this adversarial loop must have a hard ceiling (typically two to three rounds); if convergence fails, the premise or technical approach likely has a blind spot requiring human intervention.
5. Spec-First / Test-First Contract (Contract-First and Red-Green Drive)
In traditional engineering, TDD often stalls due to boilerplate overhead; with coding agents, TDD becomes a high-ROI control lever. The practice: humans or human-AI collaboration first freeze two artifacts — a clear I/O contract (schema, boundary conditions, error codes) and at least one automated test reproducing the issue or covering core constraints (initially red). Then hand "make the test green" to the agent, with a rule explicitly forbidding weakening or modifying original test assertions to force a pass . As long as the referee standard is hard, the agent's exploration speed can be safely unleashed.
A collaboration topology diagram illustrates four layers: top-level contract and planning lock direction; middle-layer master-worker isolation protects main context purity; lower amber guardrail layer handles high-frequency auto-repair; only machine-gate-passed results reach the bottom-right independent review; exceeding failure rounds triggers the left red stop-loss branch that cuts contamination and returns control to humans.
Why They Haven't Solidified Like GoF Patterns — Three Over-Engineering Traps
Despite wide adoption in mainstream frameworks and teams, these algorithms and patterns lack GoF's stable "textbook status" for two realistic reasons:
Foundation capabilities still shifting violently : traditional compilers and memory models stayed stable for decades, allowing patterns to settle; LLM long-context reasoning and tool-calling accuracy are still rapidly iterating. Many complex state machines built today to compensate for model shortcomings may be replaced in six months by a simple loop on a stronger base model.
Complexity and ROI easily invert : each added scheduling or review layer stacks latency, token cost, and state-sync risk. Front-line practice (e.g., Anthropic's core advice on agent architecture) universally emphasizes "start from the simplest loop" and only layer tree search or multi-agent orchestration when a concrete bottleneck is observed.
Three common over-engineering traps in practice:
Excessive multi-agent orchestration : a single-file, ten-minute task forced into product-manager, architect, coder, tester — five or six agents passing messages. Every role handoff loses information, doubles latency and token bills, and often yields worse output than a single direct conversation.
"Idle reflection" without objective referees : if the environment lacks a compiler, test suite, or real runtime logs, relying solely on model self-reflection or two models critiquing each other in natural language traps the system in a "looks reasonable" hallucination loop. Without machine-verifiable ground truth, the loop is just tautology.
Treating large context windows as garbage bins : a window supporting hundreds of thousands of tokens does not mean stuffing the entire repo and all history improves results. Redundant context raises retrieval noise, distracts attention from key constraints, and underperforms on-demand slicing and timely cleanup.
Traditional data-structure algorithms and design patterns are not obsolete — they have moved to the background, changing position. We used to type them line by line; now they still underpin architectural judgment — e.g., spotting an agent's accidental O(N²) performance trap in a nested loop, or recognizing it bypassed an interface layer and broke a clean dependency-inversion boundary. Tools write the code, but the design yardstick stays in your hands.
Pattern Selection by Task Complexity
Not every task needs the full stack; tiered selection by complexity and fault tolerance is most cost-effective:
Well-defined single-point changes and small utility scripts : "Single-agent ReAct + local type/unit-test gate" suffices; keep context clean, avoid multi-agent or complex search.
Cross-module feature development or core business refactors : "Plan-and-Execute + Spec/Test-First + independent Reviewer"; use read-only subagents to isolate search noise during large-scale reconnaissance, and decisively reset the session after two to three consecutive unfixed rounds.
High-difficulty bugs or multi-option architectural probes : run small-scale Best-of-N comparisons or branch backtracking in isolated worktrees or sandboxes; let real automated tests and benchmark data adjudicate solution quality, rather than endlessly stacking patches in a single dirty session.
Coding agent development is undergoing an evolution akin to early software engineering: from individual prompt craft and gut feel toward reusable engineering patterns built around search trajectories, context boundaries, and deterministic verification. Understanding the constraints behind these patterns matters more than memorizing any framework terminology.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.