← Agentic Harness / Design
Agentic Harness · DesignChapter 01

Agent Harness Design: Planning, Self-Verification & Self-Refine Loops, Context Engineering, and Memory

Why sequential ReAct loops bottleneck on serial tool latency, how LLMCompiler-style DAG planners collapse multi-tool execution to the critical path, why self-refine loops fail without external deterministic verifiers, how append-only context engineering preserves $92.4\%$ GPU KV-cache hit rates, and how to structure working, episodic, and semantic memory in production agents.

1. Planning Architectures: ReAct vs. Plan-and-Solve vs. Parallel DAG Compilation

When a user asks a shopping assistant at VogueCart: “Compare the fabric breathability, in-stock sizes, and return policies of the Linen Resort Shirt and the Tencel Camp Collar Shirt, and check if either qualifies for my loyalty tier discount,” the agent must invoke at least four distinct tools: two product detail lookups, a policy lookup, and a user loyalty profile fetch. How the agent harness schedules those calls determines whether the user waits $4.6\text{ seconds}$ or $1.1\text{ seconds}$.

1.1 Sequential ReAct and the Serial Latency Trap

In a standard ReAct (Reason + Act) loop, the policy generates a thought and a single action $a_t \sim \pi_\theta(\cdot \mid h_t)$, blocks while the environment executes $o_t = \text{Exec}(a_t)$, appends $(a_t, o_t)$ to history $h_{t+1}$, and invokes the LLM again. Across $T$ tool calls, total wall-clock latency is strictly additive:

$$L_{\text{ReAct}} = \sum_{t=1}^{T} \left(L_{\text{prefill}}(h_t) + L_{\text{decode}}(a_t) + L_{\text{tool}}(a_t)\right) + L_{\text{synth}}(h_{T+1}).$$

Even when four tool calls are completely independent, sequential ReAct pays four separate LLM round-trips and four serial network I/O waits. Worse, because the context length $|h_t|$ grows at every step by the size of raw tool payloads $|o_t|$, total prefill token consumption scales quadratically in the number of turns: $\mathcal{O}\!\left(\sum_{t=1}^T |h_t|\right) = \mathcal{O}(T^2 \cdot \bar{o})$.

1.2 ReWOO and Parallel DAG Compilation (LLMCompiler)

To eliminate redundant intermediate LLM decode passes and exploit tool parallelism, production harnesses compile the user query into an explicit Directed Acyclic Graph (DAG) $G = (V, E)$ in a single planning pass:

$$L_{\text{DAG}}(G) = L_{\text{plan}}(x) + \max_{\pi \in \text{Paths}(G)} \sum_{v \in \pi} L_{\text{tool}}(v) + L_{\text{synth}}(x, \{o_v\}_{v \in V}).$$

What if a branch returns an unexpected result (for example, $0$ in-stock sizes) that invalidates downstream nodes? We use Hybrid Adaptive DAG Execution: if every node satisfies its post-condition invariant, the DAG completes in a single plan-execute-synthesize cycle; if any node raises a ReplanSignal (e.g., empty retrieval set or tool timeout), the executor halts dependent branches and invokes a targeted sub-DAG replanner conditioned on the completed prefix.

Sequential ReAct vs Parallel DAG Planner and Verifier-Guided Self-Refine Loop
Figure 1: (Left) Sequential ReAct serializes 4 independent tool calls and 5 LLM invocations ($4,620\text{ ms}$ total), whereas Parallel DAG Compilation (LLMCompiler) schedules independent roots concurrently and resolves symbolic variable dependencies ($1, $2), cutting critical-path latency to $1,140\text{ ms}$ ($4.05\times$ speedup). (Right) Verifier-Guided Self-Refine pairs the generator with deterministic symbolic checks (constraint solver, citation verifier, schema validator) rather than ungrounded intrinsic LLM self-critique.
Planning ParadigmLLM Calls ($T$ Tools)Tool Execution LatencyTotal Prefill TokensAdaptivity to Mid-Run SurprisesBest Production Fit
Sequential ReAct$T + 1$$\sum_{t=1}^T L_{\text{tool}, t}$ (Serial)$\mathcal{O}(T^2 \cdot \bar{o})$High (re-evaluates after every observation)Open-ended debugging or exploratory tasks with unknown tool dependencies
Plan-and-Solve / ReWOO$2$ (Plan + Synth)$\max_{\pi} \sum_{v \in \pi} L_v$ (Parallel)$\mathcal{O}(T \cdot \bar{o})$Low (static plan fails if step 1 returns 0 hits)Predictable workflows with fixed schemas (e.g., multi-API enrichment)
Hybrid Parallel DAG (LLMCompiler + Replan Trigger)$2$ ($+1$ only on invariant violation)$\max_{\pi} \sum_{v \in \pi} L_v$ (Parallel)$\mathcal{O}(T \cdot \bar{o})$High (triggers sub-DAG replan on anomaly)Low-latency e-commerce & CRM assistants (VogueCart, AutoPulse CRM)

2. Self-Verification & Self-Refine Loops: Why Intrinsic Critique Fails

A common anti-pattern in agent design is adding a generic reflection prompt after generation: “Review your draft response above for any errors or hallucinations and output an improved version.” As shown by Huang et al. (2024), intrinsic self-correction without external feedback rarely improves task accuracy and frequently degrades it: if the base model lacked the knowledge or arithmetic precision to avoid a mistake during forward generation $y^{(0)} \sim p_\theta(\cdot \mid x)$, sampling from the same model distribution $p_\theta(\cdot \mid x, y^{(0)})$ either rubber-stamps the error or flips correct answers into second-guessed mistakes.

2.1 Formalizing Verifier-Guided Self-Refine

Self-refine only yields positive expected value when the critique step is anchored by an external, asymmetric verification oracle $V(x, y^{(k)}, \mathcal{O}) \to (\text{pass} \in \{0,1\},\, \mathbf{e}^{(k)})$, where Verification is strictly easier or more deterministic than Generation ($\text{Complexity}(V) \ll \text{Complexity}(G)$). At iteration $k \in \{0, \dots, K_{\max}-1\}$:

$$\mathbf{e}^{(k)} = \bigoplus_{m=1}^{M} v_m\!\left(x,\, y^{(k)},\, \mathcal{O}_{\text{tools}}\right), \qquad y^{(k+1)} = \begin{cases} y^{(k)} & \text{if } \mathbf{e}^{(k)} = \varnothing, \\ \pi_{\text{refine}}\!\left(x,\, y^{(k)},\, \mathbf{e}^{(k)},\, \mathcal{O}_{\text{tools}}\right) & \text{if } \mathbf{e}^{(k)} \neq \varnothing. \end{cases}$$

In our production harnesses at VogueCart and AutoPulse CRM, the deterministic verifier suite $\{v_m\}_{m=1}^M$ executes in $<8\text{ ms}$ of CPU time before any response or high-stakes tool call is emitted:

  1. Entity & SKU Groundedness Verifier ($v_{\text{ground}}$): Extracts every product ID, price, and percentage mentioned in $y^{(k)}$ via regex/NER and asserts exact set membership against the raw JSON tool observations $\mathcal{O}_{\text{tools}}$. Any unverified SKU or mismatched price generates a structured violation: {"error": "UNGROUNDED_PRICE", "sku": "VC-8821", "claimed": "$79", "actual_in_tool": "$84"}.
  2. Symbolic Constraint Satisfaction Verifier ($v_{\text{constraint}}$): Checks every recommended item against the session’s active slot ledger $\mathcal{L}_t$ (e.g., price_usd <= 90.0, material != "polyester", in_stock_sizes_contains("M")).
  3. SQL / API Dry-Run Verifier ($v_{\text{ast}}$): For analytics or CRM database queries, parses the generated SQL into an AST via sqlglot, verifies table/column existence against the catalog schema, checks tenant isolation predicates (WHERE dealer_id = :ctx_dealer_id), and runs EXPLAIN before execution.

Crucially, we bound the loop to $K_{\max} = 2$ refinement iterations. Empirically, $89.4\%$ of recoverable constraint/grounding violations are fixed on $k=1$, an additional $6.8\%$ on $k=2$, and $<0.5\%$ on $k \ge 3$—meaning unbounded reflection loops waste latency and token budget without improving reliability.

3. Context Engineering & GPU KV-Cache Economics

Context engineering is the discipline of structuring, ordering, and compacting the token sequence fed to the LLM at each step $t$ to simultaneously maximize **reasoning signal-to-noise ratio** and **vLLM PagedAttention KV-cache reuse**.

3.1 The Prefix Cache Invalidation Trap

In modern inference engines (vLLM, SGLang, TensorRT-LLM) using Automatic Prefix Caching (APC), the KV cache is partitioned into fixed-size blocks (e.g., $B=16$ tokens). Each block $b_k$ is indexed by a cryptographic hash of its token IDs chained with the hash of all preceding blocks:

$$H(b_k) = \text{SHA256}\!\left(H(b_{k-1}) \;\Vert\; \text{tokens}(b_k)\right).$$

Because $H(b_k)$ depends recursively on $H(b_{k-1})$, modifying even a single token near the beginning of the prompt invalidates $100\%$ of all subsequent KV blocks. Three common mistakes silently destroy KV-cache hit rates in production agents:

  1. Dynamic Timestamps or UUIDs in the System Prompt Header: Placing Current time: 2026-10-22T14:03:19.412Z | Request ID: 9f8a... at line 1 of the system prompt changes block $b_0$ on every step, forcing a full $8,000$-token prefill from scratch on every tool call.
  2. Dynamic Tool Schema Re-Ordering: Injecting top-$k$ retrieved tools directly into the system prompt header in varying relevance order across turns changes the tool declaration prefix.
  3. Sliding-Window Summarization on Every Step: Rewriting or summarizing turns $1\dots t-1$ after every single tool call shifts the token offset of the entire conversation history.
KV-Cache-Friendly Context Layout and Multi-Tier Agent Memory Architecture
Figure 2: (Top) Anti-pattern vs. KV-Cache-Aligned Context Layout: keeping the System Instructions, Tool Registry, and Few-Shot Examples strictly immutable at prefix blocks $b_0 \dots b_K$ while appending dynamic session metadata, slot ledgers, and tool observations at the tail boosts vLLM prefix cache hit rate from $14.2\%$ to $92.4\%$. (Bottom) Three-tier agent memory architecture separating in-context Working Memory, hybrid-scored Episodic Memory, and schema-enforced Semantic Profile Memory.

3.2 Append-Only Context Layout & Observation Masking

To achieve $92\%+$ KV-cache hit rates across multi-step agent trajectories, we enforce four strict context engineering invariants:

4. Multi-Tier Memory Architecture: Working, Episodic, and Semantic

Stuffing a user’s entire 6-month interaction history into the prompt causes severe lost-in-the-middle attention degradation and blows up cost. Production agents partition state into three distinct memory tiers with explicit read/write protocols:

4.1 Working Memory (In-Context Slot Ledger)

Maintains the active task state for the current session as a compact JSON object updated deterministically after every user turn and tool call: active hard constraints (max_budget_usd, required_size, excluded_fabrics), candidate entity IDs currently on screen, and pending sub-goals.

4.2 Episodic Memory (Time-Decayed Experience Retrieval)

Stores compressed summaries of past episodes $m_i = (\text{summary}_i, \mathbf{e}_i, t_i, \text{importance}_i)$—such as “On 2026-09-14, user returned SKU VC-512 (Silk Blouse, Size S) citing tight shoulder fit; exchanged for Size M.” At session initialization or topic shift, the harness retrieves top-$k$ episodes using a hybrid score combining semantic similarity, exponential recency decay, and outcome importance (Park et al., 2023):

$$\text{Score}(m_i, q, t_{\text{now}}) = \alpha \cos\!\left(\mathbf{e}_q, \mathbf{e}_i\right) + \beta \exp\!\left(-\lambda (t_{\text{now}} - t_i)\right) + \gamma \cdot \text{Importance}(m_i),$$

where $\lambda = \ln(2) / \tau_{1/2}$ sets the half-life $\tau_{1/2}$ (e.g., $30\text{ days}$ for browsing episodes, $365\text{ days}$ for post-purchase return episodes).

4.3 Semantic & Procedural Memory (Typed Fact Store with Conflict Resolution)

Stores persistent, time-invariant user facts and domain preferences as structured triples $(\text{subject}, \text{predicate}, \text{object}, \text{confidence}, \text{updated\_at})$ in a low-latency key-value / relational store (e.g., (user_882, shirt_size, "M", 0.96, 2026-09-14)). When a new episode contradicts an existing semantic fact (e.g., user states “I now wear Size L in linen shirts”), an asynchronous memory consolidation worker runs a schema-governed upsert that archives the superseded triple with a `valid_until` timestamp rather than letting contradictory prose accumulate in a vector store.

5. Reference Implementation: Parallel DAG Executor with Verifier Self-Refine

Below is a self-contained Python implementation combining parallel DAG task scheduling (with symbolic $i dependency resolution), deterministic verifier-guided self-refine, and KV-cache-preserving context assembly.

import asyncio
import re
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Set

@dataclass
class DAGNode:
    node_id: int
    tool_name: str
    args: Dict[str, Any]
    depends_on: Set[int] = field(default_factory=set)

@dataclass
class VerificationViolation:
    rule_id: str
    message: str
    remediation_hint: str

class ParallelDAGAgentHarness:
    """Executes tool DAGs along the critical path and runs deterministic verifier self-refine."""
    VAR_PATTERN = re.compile(r"^\$(\d+)\.([a-zA-Z0-9_]+)$")

    def __init__(self, tools: Dict[str, Callable], verifiers: List[Callable], max_refine: int = 2):
        self.tools = tools
        self.verifiers = verifiers
        self.max_refine = max_refine

    def _resolve_args(self, raw_args: Dict[str, Any], results: Dict[int, Dict[str, Any]]) -> Dict[str, Any]:
        resolved = {}
        for k, v in raw_args.items():
            if isinstance(v, str) and (m := self.VAR_PATTERN.match(v)):
                dep_id, field_name = int(m.group(1)), m.group(2)
                resolved[k] = results[dep_id][field_name]
            else:
                resolved[k] = v
        return resolved

    async def execute_dag(self, nodes: List[DAGNode]) -> Dict[int, Dict[str, Any]]:
        pending: Dict[int, DAGNode] = {n.node_id: n for n in nodes}
        results: Dict[int, Dict[str, Any]] = {}

        while pending:
            # Find all nodes whose upstream dependencies have completed
            ready = [
                n for n in pending.values()
                if n.depends_on.issubset(results.keys())
            ]
            if not ready:
                raise RuntimeError("Cycle or unresolved dependency detected in tool DAG.")

            async def _run_node(node: DAGNode):
                bound_args = self._resolve_args(node.args, results)
                out = await self.tools[node.tool_name](**bound_args)
                return node.node_id, out

            # Dispatch all ready nodes in parallel along the current frontier
            completed_batch = await asyncio.gather(*(_run_node(n) for n in ready))
            for nid, output in completed_batch:
                results[nid] = output
                del pending[nid]

        return results

    async def synthesize_with_self_refine(
        self,
        query: str,
        slot_ledger: Dict[str, Any],
        tool_outputs: Dict[int, Dict[str, Any]],
        llm_generate_fn: Callable,
    ) -> Dict[str, Any]:
        draft = await llm_generate_fn(query=query, ledger=slot_ledger, observations=tool_outputs, feedback=None)
        for attempt in range(self.max_refine + 1):
            violations: List[VerificationViolation] = []
            for verifier in self.verifiers:
                violations.extend(verifier(draft, slot_ledger, tool_outputs))

            if not violations:
                return {"response": draft, "refine_iterations": attempt, "verified": True}

            if attempt < self.max_refine:
                feedback_payload = [
                    {"rule": v.rule_id, "error": v.message, "fix": v.remediation_hint}
                    for v in violations
                ]
                draft = await llm_generate_fn(
                    query=query, ledger=slot_ledger, observations=tool_outputs, feedback=feedback_payload
                )
        return {"response": draft, "refine_iterations": self.max_refine, "verified": False}

Key Takeaways for Production Agent Harnesses

  • Compile independent tools into parallel DAGs: Replacing serial ReAct with an asynchronous DAG executor collapses tool latency from $\sum_i L_i$ to the critical path $\max_\pi \sum_{i \in \pi} L_i$, cutting p95 latency by $3.2\times\text{--}4.1\times$ on multi-tool queries.
  • Never run self-refine without an external verifier: Pair bounded reflection ($K_{\max}=2$) with deterministic CPU verifiers (entity/price grounding, constraint satisfaction, SQL AST checks) that provide exact error coordinates.
  • Treat the prompt prefix as an immutable KV-cache artifact: Keep system instructions, sorted tool schemas, and few-shot examples frozen at block $b_0$, append dynamic state at the tail, and compact stale tool observations only at high-watermark checkpoints.