Part 08 Scope & Analytical Objectives
- Quantify compounding error rates across multi-step agent trajectories and raise end-to-end reliability using deterministic step verifiers and Plan-Execute-Verify loops.
- Architect three-tier agent memory (Working Context, Episodic Trace Logs, and Long-Term Semantic/Procedural Memory) without triggering context rot or memory poisoning.
- Apply automatic context compaction and artifact pointer patterns so long-horizon tasks stay fast and focused.
Executive & Technical Overview
Single-turn demos mask a fundamental mathematical law of sequential autonomy: **errors compound multiplicatively across unverified steps**. Scaling an agent from a 3-step lookup to a 25-step engineering investigation requires explicit **step-level verification math** and **disciplined memory management** so intermediate tool outputs do not drown out task constraints.
8.1 Plan-Execute-Verify Topologies & Multi-Step Error Math
A. The Reliability Mathematics of Multi-Step Trajectories
Suppose an autonomous workflow requires N sequential steps, each succeeding independently with probability p. Without intermediate error detection and recovery, end-to-end trajectory success decays exponentially:
Even at an impressive single-step accuracy of p = 0.95, a 20-step chain succeeds only 0.9520 ≈ **35.8%** of the time! Now introduce a deterministic step verifier (compiler check, schema assertion, unit balance test, or solver constraint check) that catches step errors and permits up to R independent corrective attempts per step (each succeeding with probability p):
With p = 0.95 and just R = 2 verified attempts per step, per-step success rises to 1 − 0.052 = 0.9975, lifting 20-step end-to-end success from **35.8% to 95.1%**! Verification—not larger prompt instructions—is what makes long-horizon agents viable.
B. Plan-Execute-Verify vs. Interleaved ReAct
Pure ReAct plans only one step ahead, making it susceptible to local myopic detours on multi-part tasks. **Plan-Execute-Verify** separates strategic decomposition from tactical execution:
- Planner Node: Generates an explicit, ordered task Directed Acyclic Graph (DAG) with verifiable acceptance criteria per subtask.
- Scoped Executor Node: Executes one subtask at a time using a clean, minimal context window, returning only the verified structured result (not 15,000 tokens of intermediate trial-and-error logs).
- Verifier / Re-Planner Node: Audits subtask outputs against acceptance criteria and updates remaining DAG steps if empirical observations invalidate an initial assumption.
8.2 Working, Episodic & Semantic Memory Without Context Bloat
A. Three-Tier Agent Memory Taxonomy
Borrowing from cognitive systems architecture, separate agent state into three distinct storage tiers with explicit write policies:
| Memory Tier | Storage Substrate | Contents & Eviction / Write Discipline |
|---|---|---|
| 1. Working Memory | Active LLM Context Window + Structured State Object | Current goal, active plan checklist, and compacted summaries of completed steps. Prune raw verbose tool payloads into external artifact pointers! |
| 2. Episodic Memory | Append-only Trace Store / Time-stamped Event Log | Complete immutable record of past runs, tool inputs/outputs, and verified post-mortem resolutions for debugging and few-shot retrieval. |
| 3. Semantic & Procedural Memory | Curated Knowledge Base / Verified Playbooks | Domain schemas, validated SOPs, and user preferences. Never let an agent write unverified model guesses into permanent semantic memory (prevents self-reinforcing memory poisoning). |
B. Artifact Handle Pattern & Context Compaction
When Tool A retrieves a 5,000-row time-series dataframe needed by Tool B (a forecasting or plotting function), **do not serialize 5,000 rows into JSON tokens inside the LLM context**. Instead, store the dataframe in host session memory under an opaque typed handle (`artifact_id = "df_load_2026Q3"`), return a 6-line summary schema (`rows=5000, cols=['timestamp','mw'], min=412.0, max=985.4`) to the LLM, and let the LLM pass `artifact_id="df_load_2026Q3"` directly to Tool B—cutting token consumption by >99% and eliminating transcription corruption.
Worked Engineering Lab & Reference Implementation
The Python module below computes **Multi-Step Trajectory Reliability Curves** under verified retries and demonstrates the **Opaque Artifact Registry Pattern** that keeps large numerical payloads out of LLM token streams:
from typing import Any, Dict
import uuid
def trajectory_reliability(step_prob: float, num_steps: int, max_attempts_per_step: int = 1) -> float:
"""Computes end-to-end success probability across `num_steps` with verified step retries."""
assert 0.0 <= step_prob <= 1.0 and num_steps >= 1 and max_attempts_per_step >= 1
effective_step_prob = 1.0 - ((1.0 - step_prob) ** max_attempts_per_step)
return round(effective_step_prob ** num_steps, 4)
class SessionArtifactStore:
"""Holds large dataframes/arrays out-of-band so agents pass lightweight handles."""
def __init__(self) -> None:
self._store: Dict[str, Any] = {}
def put(self, prefix: str, data: list[float]) -> Dict[str, Any]:
handle = f"{prefix}_{uuid.uuid4().hex[:8]}"
self._store[handle] = data
n = len(data)
return {
"artifact_handle": handle,
"length": n,
"min": round(min(data), 4) if n else None,
"max": round(max(data), 4) if n else None,
"preview_head": data[:3],
}
def get(self, handle: str) -> Any:
if handle not in self._store:
raise KeyError(f"Unknown artifact handle '{handle}'.")
return self._store[handle]
# Compare 25-step agent at p = 0.93:
# Unverified (R=1): 0.93^25 = 0.1630 (16.3% success)
# With deterministic step verifier & R=2 tries: (1 - 0.07^2)^25 = 0.8844 (88.4% success)
# With R=3 tries: (1 - 0.07^3)^25 = 0.9915 (99.15% success)
Analytical Review & Self-Study Questions
Work through each analytical problem independently before expanding the reference derivation:
Problem 8.1 (Reliability Budgeting): Your architecture requires >=95% end-to-end completion reliability across a 15-step analytical workflow where individual LLM tool-generation steps succeed with probability p = 0.90. Assuming you have an exact deterministic step verifier (zero false positives), what minimum number of attempts R per step is required?
Problem 8.2 (Memory Poisoning Vulnerability): What happens if a customer-support or research agent automatically summarizes every conversation and writes extracted 'facts' into its shared long-term vector memory without provenance gating?
Problem 8.3 (Context Compaction Strategy): Halfway through a 12-step debugging session, working context reaches 60,000 tokens of raw grep outputs. What should be compacted and what must remain verbatim?
Public-Domain Standards & Open-Access References
All theoretical formulations, worked numerical examples, and Python implementations in this publication are originally authored by AhnLim Foundation and grounded exclusively in public-domain government standards and peer-reviewed open-access scientific literature:
- Shinn, N. et al. (2023). Reflexion: Language Agents with Verbal Reinforcement Learning. NeurIPS (open-access arXiv:2303.11366).
- Sumers, T. R. et al. (2023). Cognitive Architectures for Language Agents (CoALA). Transactions on Machine Learning Research (open-access arXiv:2309.02427).
- NIST (2024). NIST AI 600-1: Generative AI Profile — Information Integrity & Data Poisoning Controls (Public Domain).
ahnlim.org. Educators, researchers, practitioners, and independent readers may freely share, print, and adapt this publication under CC BY-NC 4.0 with attribution to AhnLim Foundation (Series I, Part 08).