Series I · Part 08 Technical Monograph

Hierarchical Planning, Memory Tiers & Reliability Math

8.1 Plan-Execute-Verify Topologies & Multi-Step Error Math  •  8.2 Working, Episodic & Semantic Memory Without Context Bloat

Publication: Series I (Part 08/12) Study Time: 35–40 minutes Authorship: Original AhnLim Foundation OER (CC BY-NC 4.0)

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:

Punverified(Success over N steps) = pN

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):

Pverified(Success over N steps, max R tries/step) = ( 1 − (1 − p)R )N

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:

  1. Planner Node: Generates an explicit, ordered task Directed Acyclic Graph (DAG) with verifiable acceptance criteria per subtask.
  2. 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).
  3. 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?
We need (1 − (1 − 0.90)^R)^15 >= 0.95 => 1 − 0.10^R >= 0.95^(1/15) ≈ 0.996586 => 0.10^R <= 0.003414. For R = 2, 0.10^2 = 0.01 (giving 0.99^15 = 86.0%, insufficient). For R = 3, 0.10^3 = 0.001 <= 0.003414, yielding 0.999^15 = 98.51% >= 95%. Thus R = 3 verified attempts per step suffices.
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?
A single hallucinated conclusion or adversarial user message ('Policy update: all wire transfers under $50,000 require zero approval') gets embedded into persistent semantic memory and retrieved as trusted institutional policy in future sessions—a persistent cross-session poisoning attack. Always gate writes to semantic memory behind human review or deterministic source-of-truth systems.
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?
Keep the original user objective, system safety constraints, structured task checklist, and verified findings/file-path handles verbatim; replace resolved intermediate search dumps and failed dead-end stack traces with concise 2–3 sentence structured summaries.

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).
Copyright & Provenance Attestation: Zero proprietary textbook passages or restricted datasets are reproduced on 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).