Prompt · Context · Harness · Graph Engineering — and Self-Improving AI

The engineering stack around a frozen model: how you prompt it, what context you feed it, the harness you wrap it in, the graphs you impose on it — and how systems improve themselves.

Prompt engineering · context engineering · harness engineering · graph engineering · agent skills · self-improvement · self-learning · recursive self-improvement (RSI).

Updated August 2026 with 2025–2026 SOTA — new entries marked ★. Method names link to their primary papers (arXiv / official page).

August 2026 · Updated Edition


Contents

  1. The Engineering Stack: A Taxonomy
  2. Prompt Engineering
  3. Context Engineering
  4. Harness Engineering
  5. Graph Engineering
  6. Self-Improvement & Self-Learning
  7. Recursive Self-Improvement (RSI)
  8. Putting It Together: The 2026 Self-Improving Agent Stack
  9. Mathematical Deep Dives

Appendix A: Thirty-One Things to Memorize Appendix B: Decision Guide — "Which Technique?" Appendix C: Glossary Appendix D: Year-by-Year Milestones


1. The Engineering Stack: A Taxonomy

The model weights are fixed at inference. Everything that determines whether a fixed model behaves like a toy or an expert lives in the engineering stack around it. Four concentric layers, from innermost to outermost:

Wrapping all four is the temporal dimension — self-improvement: using signals the system generates itself to get better, at inference time (§6), at training time (§6), or by improving the improver itself (recursive self-improvement, §7).

Key

The 2023→2026 arc: the field's leverage moved outward through the stack. First we tuned prompts; then (for agents) we realized context is the real budget; then that the harness determines capability more than the prompt; and now that the highest-leverage move is systems that engineer themselves. Same model, different stack → enormous capability delta. Reference index for prompting: The Prompt Report (a systematic survey of 58+ techniques and standardized terminology).

2. Prompt Engineering

2.1 Core prompt anatomy

2.2 Reasoning-elicitation techniques

2.3 In-context learning — theory, selection, calibration

Why ICL works:

Selection & ordering:

Calibration:

2.4 ★ Prompting modern reasoning models (o-series, R1, extended thinking)

Reasoning models are RL-trained to produce a long internal chain before answering, which changes the rules:

Key

The prompting objective shifted from eliciting reasoning (CoT, ToT scaffolds) to budgeting it (reasoning-effort controls, verifier-guided test-time compute). On reasoning models, hand-built decomposition scaffolds often hurt — give the objective, not the method.

2.5 Automatic prompt optimization / programmatic prompting

Stop hand-tuning strings; optimize them against a metric.

Discrete / text-search optimizers:

Frameworks / compilers:

Key

Three families to keep straight: discrete search (APE, OPRO, EvoPrompt) that samples/scores prompt strings; reflective / textual-gradient (ProTeGi, TextGrad, Trace, GEPA) that critiques traces and edits in the "semantic gradient" direction; and soft/continuous prompt tuning (prefix/P-tuning — weight-space, out of scope here). GEPA is the 2025 headline: reflection can beat RL at a fraction of the rollouts.

2.6 Ensembling & sampling

2.7 Adversarial & safety

Attacks:

Defenses:

2.8 Patterns & anti-patterns

Patterns: durable rules in the system prompt; XML/delimiters to fence data; explicit output contracts via constrained decoding; decompose hard tasks; verify/critique loops for factual work; and optimize, don't hand-tune (DSPy/GEPA) once you have eval data. Anti-patterns: forcing CoT scaffolds on reasoning models; demo overload (recency/majority bias, wider jailbreak surface); relying on example label correctness to teach a task; unfenced retrieved content; assuming few-shot ordering is neutral; and trusting "please output JSON" over constrained decoding.

3. Context Engineering

3.1 What it is and why it superseded prompt engineering

Context engineering is the discipline of curating and maintaining the optimal set of tokens — instructions, tool definitions, retrieved documents, history, memory, tool results — in the window during inference. Prompt engineering writes one good static prompt; context engineering manages the entire dynamic state fed to an agent across many turns and tool calls.

Why it matters: an agent runs many inference cycles, assembling context fresh each turn, and context is a finite budget. Transformer attention is pairwise over \(n\) tokens, and models are trained on shorter sequences than their max window, so effective use degrades before the nominal limit. The canonical framing — Anthropic, "Effective context engineering for AI agents" — treats attention as a scarce resource to spend on the "smallest set of high-signal tokens." A useful operational taxonomy (LangChain): Write (persist outside the window), Select (pull in what's relevant), Compress (summarize/trim), Isolate (split across sub-agents).

3.2 Long-context mechanics & failure modes

3.3 Retrieval-Augmented Generation (RAG)

Naive RAG = chunk → embed → top-\(k\) vector search → stuff. Advanced RAG adds pre-retrieval (query transformation), retrieval (hybrid + rerank), and post-retrieval (compression, reordering). Agentic RAG makes retrieval a tool an agent invokes in a loop (§3.4).

Foundational:

Query transformation:

Hybrid search & rerankers:

Embedding models: E5 (contrastive, query:/passage: prefixes), BGE / C-Pack, GTE, Nomic Embed (open-data, 8192-token).

Structure-aware & adaptive:

3.4 Agentic context management

Short-term memory = the working window (this session's messages/tool results). Long-term memory = an external store (vector DB / graph / files) selectively read back in. Strategy: keep the window lean, offload the rest.

3.5 Prompt / context compression

Hard (discrete) = drop/edit actual tokens (model-agnostic, portable). Soft (continuous) = compress into embeddings/soft tokens (needs model access). KV-cache-aware / prompt caching = reuse a stable prefix's KV cache instead of reprocessing it.

3.6 Structured context assembly

Design the system prompt at the "right altitude" (specific enough to steer, general enough not to overfit); use XML/markdown structure to demarcate instructions vs data vs tool results; format tool outputs to be token-efficient (signal over raw dumps); exploit the U-shaped bias by placing the most critical content at the start or end, not buried mid-context; use a few diverse canonical examples rather than exhaustive rules; and quarantine/validate tool outputs and retrieved text before they become trusted history (Anthropic).

3.7 Evaluation of context / RAG

Key

"Bigger window" ≠ "problem solved" — Context Rot and NoLiMa show degradation is real at scale. The 2025 shift: for long-horizon agents, treat context as a managed budget — retrieve just-in-time, compact aggressively, isolate sub-agents, and keep only high-signal tokens resident. Memory tooling (Mem0, Zep/Graphiti, cognee) is moving from flat vector stores to temporal/knowledge graphs (§5.5).

4. Harness Engineering

4.1 What a harness is and why it dominates

The weights are fixed; the harness — loop + tools + context assembly + control flow + verification + orchestration — is what turns a next-token predictor into an agent. The canonical design reference is Anthropic, "Building effective agents", which separates workflows (predefined code paths) from agents (the LLM directs its own process) and catalogs the reusable patterns:

Guidance: start with the simplest thing that works; add agentic complexity only when it pays.

4.2 The core agent loop

4.3 Tool use & interfaces

4.4 Planning & control flow

4.5 Multi-agent orchestration

4.6 Verification & reliability harness

4.7 Agent frameworks / SDKs

4.8 Coding-agent harnesses & benchmarks

4.9 Observability & agent evals

4.10 Agent Skills — the capability layer

An Agent Skill packages reusable procedural knowledge as a folder: a SKILL.md file with YAML frontmatter (name + description) and a Markdown body of instructions, plus optional bundled reference files and executable scripts. It is the harness's modular capability layer — where "how to do this task well" lives, versionable and inspectable, with no fine-tuning.

Progressive disclosure is the core mechanism: context loads in three tiers so a large library stays cheap.

  1. Metadata — only name + description (~100 tokens/skill) are always resident; this is what the model routes on.
  2. Instructions — the full SKILL.md body (target <5k tokens) loads when the description matches the task.
  3. Resources & code — bundled files and scripts load or execute on demand; a script's output enters context, not its source.

Per the docs, the description must state both what it does and when to use it — it is the routing signal (§4.11). Skills run across the Claude apps, Claude Code, the Agent SDK, and the API, and ship as an open format (anthropics/skills). The quantitative payoff of progressive disclosure is derived in §9.19.

4.11 Skills vs tools/MCP; authoring; plugins

Skills vs tools/MCP. MCP and function calling provide actions (what the agent can do or connect to); a skill provides procedure (how to do a multi-step task well), typically orchestrating those tools plus bundled scripts. They are complementary, not competing — the skill teaches the workflow, MCP supplies the connections.

Authoring (best practices): write a crisp third-person description with concrete trigger terms (routing quality depends on it); keep the body short (only what the model doesn't already know); push detail into reference files one level deep; bundle scripts for determinism ("sorting a list via token generation is far more expensive than running a sort"); pick the right degrees of freedom (prose for open tasks → exact scripts for brittle ones); and build evals first, testing across model sizes.

Plugins & marketplaces. A plugin bundles skills + MCP servers + slash commands + subagents + hooks, installed from a marketplace — the distribution unit for capability, and how a team ships a coherent set (skills + connections + commands) as one install.

4.12 Skill libraries & self-authored skills (bridge to self-improvement)

A skill library is external, growing procedural memory, which makes accumulating skills a form of self-improvement without weight updates (§6–§7). The canonical research anchor is ★ Voyager: an LLM agent that writes, stores, retrieves, and composes an ever-growing library of executable-code skills, achieving lifelong learning with no gradient updates and no catastrophic forgetting. Related lines let models create their own tools/skillsCREATOR and LLMs as Tool Makers build reusable tools on the fly, and ADAS has a meta agent program new agents from a growing archive (§7.2). An agent that authors and reuses its own skills sits on the recursion ladder (§7.3, rung 4): it improves capability by editing its scaffold's skill set rather than its weights.

Key

The harness, not the checkpoint, is often the biggest lever: SWE-agent showed a better Agent-Computer Interface beats a bigger model, and Agentless showed a minimal fixed pipeline can rival full agents. 2025–2026 harness trends (★): Agent Skills (progressively-disclosed skill folders), code-execution-over-MCP for token efficiency, context engineering for long-horizon runs, and RL-trained agent harnesses co-designed with the loop.

5. Graph Engineering

5.1 Framing: five loci of graph structure

"Graph engineering" means deliberately imposing graph structure (nodes + typed edges) on part of an LLM/agent system to gain non-linear composition, aggregation, and traversal that flat sequences cannot express. Five places it shows up:

The unifying move: replace sequences with graphs so that structure carries semantics.

5.2 Reasoning topologies as graphs

Chain = one linear path. Tree = branching + search/backtrack, no merging. Graph = arbitrary edges: aggregate multiple thoughts into one, cycles/refinement, reuse.

5.3 Graph RAG / knowledge-graph retrieval

5.4 Knowledge-graph construction with LLMs

Not one paper but a pipeline: LLM-driven entity + relation (triple) extraction → coreference/entity resolution → optional ontology/schema typing → graph assembly + community/embedding indexing. Entity resolution/dedup is the load-bearing step for graph quality. The canonical framing is Unifying LLMs and Knowledge Graphs: A Roadmap (KG-enhanced LLMs, LLM-augmented KGs, synergized); concrete pipelines are GraphRAG's extraction→community step, LightRAG's incremental dedup/merge, and KAG's schema-constrained construction.

5.5 Graph-structured agent memory

Store memory as a temporal / bi-temporal knowledge graph — edges carry validity intervals (event time vs ingestion time), so facts can be superseded/invalidated without deletion and point-in-time queries become possible.

5.6 Agent & workflow graphs

5.7 GNN + LLM fusion / can LLMs reason on graphs?

Key

Match the graph to the failure mode: use thought graphs (ToT/GoT) when a task needs branching + aggregation; GraphRAG when questions are global/multi-hop over a corpus that flat top-\(k\) misses; temporal-KG memory (Zep/Graphiti, Mem0ᵍ) when an agent must remember evolving facts over time; and workflow graphs (LangGraph) or optimizable agent graphs (GPTSwarm, AFlow) when orchestration itself should be explicit or learned. 2025–2026 (★): agentic GraphRAG (the agent traverses the graph), graph memory going mainstream, and graph-of-agents where topology is searched.

6. Self-Improvement & Self-Learning

6.1 Taxonomy

Organizing reference: A Survey of Self-Evolving Agents and A Comprehensive Survey of Self-Evolving AI Agents (a unified System-Inputs / Agent-System / Environment / Optimisers framework bridging foundation models and lifelong agentic systems).

6.2 Inference-time self-correction

6.3 Training-time self-improvement (learn from self-generated data)

6.4 Self-rewarding & self-play alignment

Key

The load-bearing ingredient is a verifier. Where correctness is cheaply checkable (unit tests, math answers, game outcomes), self-generated data + filtering (STaR/ReST-EM) and self-play (Absolute Zero, R-Zero) compound impressively. Where it isn't, self-reward loops risk reward hacking and self-training risks model collapse (Curse of Recursion — recursively training on generated data degrades the distribution's tails over generations). Filtered self-training amplifies what a model can already verify; it rarely creates net-new capability without external signal or exploration.

7. Recursive Self-Improvement (RSI)

7.1 The idea and its theory

RSI is improving the improver: a system that edits its own code, prompts, learning algorithm, or agent scaffold so that improvements compound. Conceptual lineage: I.J. Good's 1965 "intelligence explosion" and the notion of seed AI — a minimal system capable enough to iteratively rewrite itself toward far greater capability. The rigorous theoretical object is the Gödel Machine (Schmidhuber): a self-referential program that rewrites any part of its own code once it can prove the rewrite is beneficial — provably optimal self-improvement, but the proof requirement makes it impractical.

7.2 Practical self-modifying & auto-design systems

7.3 The recursion ladder

Five rungs of increasing self-reference, each a real system today:

  1. Improve outputs — Self-Refine/Reflexion revise this answer (§6.2).
  2. Improve weights from self-data — STaR/ReST-EM/Self-Rewarding update the model (§6.3–§6.4).
  3. Improve the prompt/program — DSPy/GEPA/STOP/Promptbreeder optimize the scaffold text.
  4. Improve the agent design — ADAS/AFlow/GPTSwarm search over agent code/topology.
  5. Improve the self-improver — Gödel Agent / Darwin Gödel Machine / SEAL modify the very mechanism that modifies them.

7.4 Meta-learning & test-time adaptation

7.5 Limits & safety

Key

As of 2026, "recursive self-improvement" in practice means empirical, benchmark-gated self-modification of code and scaffolds (Darwin Gödel Machine, ADAS, AlphaEvolve) and RL-learned weight self-edits (SEAL) — not the provably-optimal Gödel Machine. Every working system is bounded by a verifier and a sandbox. The open question is whether the loop keeps paying off past the base model's ceiling, or plateaus.

8. Putting It Together: The 2026 Self-Improving Agent Stack

A modern capable agent composes all five layers:

Layer Default 2026 approach Frontier (★)
Prompt Direct zero-shot for reasoners; structured outputs; self-consistency Compiled prompts (DSPy, GEPA)
Context Hybrid RAG + rerank; compaction; prompt caching Temporal-KG memory; context-managing agents
Harness ReAct + MCP tools; evaluator-optimizer; sub-agents Code-execution actions; RL-trained harness
Skills SKILL.md procedural skills (progressive disclosure) + bundled scripts; plugins Self-authored, growing skill libraries (Voyager-style)
Graph LangGraph orchestration; GraphRAG for global QA Optimizable agent graphs (GPTSwarm, AFlow)
Self-improve Reflexion/self-refine + verifier; STaR/RLVR offline DGM / SEAL / AlphaEvolve, benchmark-gated

9. Mathematical Deep Dives

This section collects the mathematics behind the techniques above — the derivations worth being able to reproduce, not just cite. Notation: \(\pi_\theta\) is a policy / language model with parameters \(\theta\); \(q\) a query/prompt; \(\sigma(z)=1/(1+e^{-z})\) the logistic function; \(\mathrm{KL}(\cdot\|\cdot)\) the Kullback–Leibler divergence; \(\mathbb{1}[\cdot]\) the indicator; \(\mathbb{E}\) expectation.

9.1 In-context learning as implicit gradient descent

Why do demonstrations in the prompt behave like training? Consider a single linear self-attention layer processing demonstrations \((x_i, y_i)_{i=1}^N\) and a query token \(x_q\). Writing the value/key/query projections so that tokens carry \((x_i, y_i)\), the attention read-out added to the query prediction has the form \(\Delta\hat{y}_q = \big(\sum_i (W_V e_i)(W_K e_i)^\top\big) W_Q e_q\). With the natural choice of projections this equals one step of gradient descent on the in-context least-squares loss \(L(W)=\tfrac12\sum_i \lVert W x_i - y_i\rVert^2\):

\[W_1 = W_0 - \eta \sum_{i=1}^{N} (W_0 x_i - y_i)\,x_i^\top, \qquad \hat{y}_q = W_1 x_q .\]

So the forward pass is a learning algorithm executed on the context, and depth ↔︎ number of GD steps (von Oswald et al.). This "meta-optimizer" view explains why more and cleaner demonstrations help monotonically and why ICL sharpens with scale — the model has learned to implement optimization in-weights.

9.2 In-context learning as Bayesian inference

A complementary view: pretraining learns a mixture over latent tasks/concepts \(\theta\). At inference the prompt \(S=(x_1,y_1,\dots,x_N,y_N,x_q)\) induces a posterior over the task and the prediction marginalizes over it:

\[p(y \mid x_q, S) = \int p(y \mid x_q, \theta)\, p(\theta \mid S)\, d\theta .\]

As \(N\) grows, \(p(\theta\mid S)\) concentrates on the concept \(\theta^\star\) consistent with the demonstrations, so ICL locates a task the model already knows rather than learning a new one (Xie et al.). This is why the demonstration format and input distribution carry most of the signal while individual label correctness matters surprisingly little (Min et al.): the demos act as task selectors for the posterior, not as supervised training pairs.

9.3 Self-consistency: marginalization and an error bound

A chain-of-thought samples a latent reasoning path \(r\) and then an answer \(a\). The quantity we actually want is the marginal over paths:

\[p(a \mid q) = \sum_{r} p(a, r \mid q) = \sum_{r} p(a \mid r, q)\, p(r \mid q).\]

Self-consistency estimates \(\arg\max_a p(a\mid q)\) by sampling \(N\) chains and majority-voting, \(\hat{a} = \arg\max_a \tfrac1N\sum_i \mathbb{1}[a_i = a]\). Why does voting help? Treat a (binary) decision where each sample is independently correct with probability \(p\). The majority is wrong only if at most half the \(N\) votes are correct; by Hoeffding's inequality,

\[\Pr[\text{majority wrong}] \le \exp\!\big(-2N\,(p - \tfrac12)^2\big).\]

For any \(p>\tfrac12\) the error decays exponentially in \(N\) — the Condorcet jury theorem. The load-bearing assumption is independence: correlated failure modes (the model is confidently wrong the same way every time) put a floor under the error that more samples cannot break.

9.4 Decoding distributions: temperature, top-\(k\), top-\(p\)

Given logits \(z\in\mathbb{R}^{|V|}\), temperature-\(T\) sampling uses

\[p_i(T) = \frac{\exp(z_i/T)}{\sum_j \exp(z_j/T)} .\]

As \(T\to 0^+\) this tends to the argmax (greedy; entropy \(\to 0\)); as \(T\to\infty\) it tends to uniform (entropy \(\to \log|V|\)), and the Shannon entropy \(H(p(T))\) is monotonically increasing in \(T\). Truncation then trims the tail: top-\(k\) keeps the \(k\) largest logits; top-\(p\) (nucleus) keeps the smallest set \(V_p\) with \(\sum_{i\in V_p} p_i \ge p\) and renormalizes. Consequence for the methods above: self-consistency and best-of-\(N\) need \(T>0\) to generate diverse samples, whereas single-shot reasoning wants low \(T\) to avoid derailing — the same knob trades exploration against reliability.

9.5 Test-time compute: best-of-\(N\), pass@\(k\), and the verification gap

Sample \(N\) candidates and return the best under a verifier. If a single sample is correct with probability \(p\) and the verifier is perfect,

\[\Pr[\text{success}] = 1 - (1-p)^N \xrightarrow{N\to\infty} 1,\]

i.e. gains geometric in \(N\). With an imperfect verifier the ceiling is bounded by verifier accuracy — the verification gap that limits all self-improvement (§9.15, §9.17). The standard unbiased coverage estimator is pass@\(k\): with \(c\) correct of \(n\) samples,

\[\text{pass@}k = \mathbb{E}\!\left[\,1 - \binom{n-c}{k}\Big/\binom{n}{k}\right].\]

Contrast reliability, pass\(^k = p^k\) (all \(k\) independent attempts must succeed), which decreases in \(k\): coverage and reliability pull in opposite directions, which is why agentic benchmarks report pass\(^k\) (§4.9). Compute-optimal test-time scaling allocates the sampling/search budget to maximize accuracy per FLOP and can beat parameter scaling in some regimes.

9.6 The quadratic-attention budget and KV-cache accounting

Self-attention over \(n\) tokens forms scores \(S = QK^\top \in \mathbb{R}^{n\times n}\): compute is \(O(n^2 d)\) and memory \(O(n^2)\) for the score matrix. This is the formal content of "context is a finite budget" — doubling the context quadruples attention cost. During autoregressive decoding the keys and values are cached; per generated token the cache costs

\[\text{bytes/token} = 2 \cdot L \cdot H \cdot d_h \cdot \text{bytes}_{\text{dtype}},\]

(\(L\) layers, \(H\) KV heads, head dimension \(d_h\); the factor \(2\) is for \(K\) and \(V\)). Total KV memory grows linearly in context length and dominates long-context serving — the reason GQA/MLA and KV compression (§3.5) exist. Because models are trained on sequences shorter than their maximum window and attention mass disperses over many tokens, effective use degrades before the nominal limit — the quantitative face of Context Rot (§3.2).

9.7 Retrieval scoring: dense, BM25, ColBERT, and rank fusion

A dense bi-encoder scores by inner product \(s(q,d) = E(q)^\top E(d)\) (cosine after normalization); retrieval is maximum-inner-product search. BM25, the sparse lexical baseline, scores

\[\text{BM25}(q,d) = \sum_{t\in q} \text{IDF}(t)\cdot \frac{f(t,d)\,(k_1+1)}{f(t,d) + k_1\big(1 - b + b\,\tfrac{|d|}{\text{avgdl}}\big)}, \qquad \text{IDF}(t) = \ln\frac{N - n_t + 0.5}{n_t + 0.5} + 1,\]

with term frequency \(f(t,d)\), document length \(|d|\), corpus size \(N\), document frequency \(n_t\), and tunables \(k_1\in[1.2,2.0]\), \(b\approx0.75\). ColBERT keeps per-token embeddings and scores by late-interaction MaxSim,

\[s(q,d) = \sum_{i\in q} \max_{j\in d} E_{q_i}^\top E_{d_j},\]

retaining fine-grained matching a single pooled vector loses. Hybrid pipelines fuse lexical and dense rankers by Reciprocal Rank Fusion,

\[\text{RRF}(d) = \sum_{r\in R} \frac{1}{k + \text{rank}_r(d)}, \qquad k\approx 60,\]

and a cross-encoder reranker then scores the joint \((q,d)\) pair directly on the top-\(k\) candidates — higher precision at higher cost, the standard two-stage retrieve-then-rerank design (§3.3).

9.8 Prompt compression as an information-budget objective

Hard (extractive) compression selects a subsequence \(\tilde{x}\subseteq x\) that retains the most information under a token budget \(B\). LLMLingua scores each token by its self-information under a small language model,

\[I(x_i) = -\log p(x_i \mid x_{<i}),\]

and drops the most predictable (low-information) tokens first, i.e.

\[\tilde{x} = \arg\max_{|\tilde{x}| \le B} \sum_{x_i \in \tilde{x}} I(x_i),\]

which approximately minimizes the KL divergence between the target model's output distribution on \(x\) versus \(\tilde{x}\). LLMLingua-2 replaces the perplexity heuristic with a supervised keep/drop token classifier distilled from GPT-4, improving faithfulness and speed. Soft compression instead maps \(x\) to \(m \ll n\) learned embeddings — a better ratio at the cost of portability and model access.

9.9 Search harnesses: MCTS / UCT for ToT and LATS

Tree-of-Thoughts and LATS wrap the model in tree search: each node is a partial solution/state \(s\), the LM proposes actions (thoughts, tool calls) and evaluates states. Selection uses the UCT bandit rule to trade exploitation against exploration,

\[a^\star = \arg\max_a \left[\, Q(s,a) + c\sqrt{\frac{\ln N(s)}{N(s,a)}} \,\right],\]

where \(Q(s,a)\) is the mean value of taking \(a\) at \(s\), \(N(\cdot)\) are visit counts, and the square-root bonus inflates rarely-tried actions. LATS obtains \(Q\) from an LM value estimate plus environment / self-reflection feedback and backpropagates values up the tree; the four MCTS phases (select, expand, evaluate, backpropagate) repeat under a compute budget. Self-consistency (§9.3) and best-of-\(N\) (§9.5) are the degenerate breadth-1, no-backpropagation special cases of this same harness.

9.10 Personalized PageRank for graph retrieval (HippoRAG)

HippoRAG builds a knowledge graph, places probability mass on the query's matched entities as a personalization vector \(s\), and spreads relevance by Personalized PageRank with teleport (restart) probability \(\alpha\):

\[\pi = (1-\alpha)\, W\pi + \alpha\, s \quad\Longrightarrow\quad \pi = \alpha\,(I - (1-\alpha)W)^{-1} s,\]

where \(W\) is the column-stochastic transition matrix of the graph. Passages are ranked by the mass their entities accumulate in \(\pi\) — a single-shot approximation of multi-hop retrieval, since relevance flows across relation edges from the seed entities to associated facts (the associative-memory / hippocampal analogy). The power iteration \(\pi^{(t+1)} = (1-\alpha)W\pi^{(t)} + \alpha s\) converges geometrically at rate \((1-\alpha)\).

9.11 Message passing: Graph-of-Thoughts and GNNs

Both Graph-of-Thoughts reasoning and GNN encoders are neighborhood aggregation. A GNN layer updates each node from its neighbors,

\[h_v^{(l+1)} = \phi\!\left(h_v^{(l)},\ \bigoplus_{u\in\mathcal{N}(v)} \psi\big(h_v^{(l)}, h_u^{(l)}, e_{uv}\big)\right),\]

with a permutation-invariant aggregator \(\bigoplus\) (sum / mean / max / attention), message function \(\psi\), and update \(\phi\). GoT specializes this to thought nodes: aggregation edges merge several thoughts into one (in-degree \(>1\)), refinement edges are value-updating self-loops, and generation edges branch one thought into many. This is precisely why a graph strictly generalizes a chain (a path graph) and a tree (in-degree \(\le 1\), no cycles): only a general graph permits aggregation and refinement cycles. Pregel / LangGraph execute the same abstraction as synchronous BSP super-steps — every node receives messages, updates, then sends — which is the computational model under stateful agent graphs (§5.6).

9.12 STaR and ReST-EM as expectation–maximization

Treat the rationale \(r\) as a latent variable and maximize the marginal log-likelihood of the correct answer \(a^\star\):

\[\mathcal{L}(\theta) = \log p_\theta(a^\star \mid q) = \log \sum_{r} p_\theta(a^\star, r \mid q).\]

The EM lower bound uses the posterior \(p_\theta(r\mid a^\star, q)\):

Iterating is (hard) EM on the reasoning marginal, formalized by ReST-EM. Equivalently, with binary reward \(R(r)=\mathbb{1}[\text{answer correct}]\) the update is a reward-weighted / rejection-sampling policy-gradient step,

\[\nabla_\theta\, \mathbb{E}_{r\sim\pi_\theta}[R(r)] = \mathbb{E}_{r\sim\pi_\theta}\big[R(r)\,\nabla_\theta \log \pi_\theta(r)\big].\]

The objective improves monotonically, but only over rationales the model can already sample correctly — the exploration ceiling that bounds all self-training without external signal.

9.13 Alignment objectives: RLHF, DPO, and GRPO

RLHF maximizes a learned reward under a KL leash to the reference policy:

\[\max_{\pi}\ \mathbb{E}_{x,\,y\sim\pi}\big[r(x,y)\big] - \beta\,\mathrm{KL}\big(\pi(\cdot\mid x)\,\|\,\pi_{\text{ref}}(\cdot\mid x)\big).\]

This constrained problem has a closed-form optimum — a reward-tilted reference policy:

\[\pi^\star(y\mid x) = \frac{1}{Z(x)}\,\pi_{\text{ref}}(y\mid x)\,\exp\!\Big(\tfrac1\beta\, r(x,y)\Big).\]

DPO inverts this relation, \(r(x,y) = \beta\log\frac{\pi^\star(y\mid x)}{\pi_{\text{ref}}(y\mid x)} + \beta\log Z(x)\), and substitutes it into the Bradley–Terry preference model \(P(y_w\succ y_l) = \sigma\!\big(r(x,y_w) - r(x,y_l)\big)\). The intractable partition function \(Z(x)\) cancels in the difference, leaving a purely supervised loss with no reward model and no RL loop:

\[\mathcal{L}_{\text{DPO}} = -\,\mathbb{E}_{(x,y_w,y_l)}\,\log\sigma\!\left(\beta\log\frac{\pi_\theta(y_w\mid x)}{\pi_{\text{ref}}(y_w\mid x)} - \beta\log\frac{\pi_\theta(y_l\mid x)}{\pi_{\text{ref}}(y_l\mid x)}\right).\]

GRPO (used to train DeepSeek-R1) removes the value network: for a group of \(G\) sampled outputs with rewards \(\{r_i\}\), it standardizes within the group to form the advantage

\[\hat{A}_i = \frac{r_i - \operatorname{mean}(r_1,\dots,r_G)}{\operatorname{std}(r_1,\dots,r_G)},\]

used in a PPO-style clipped surrogate with a KL penalty to \(\pi_{\text{ref}}\) — cheaper and stable for verifiable-reward RL. Self-Rewarding LMs set the reward \(r\) from the model's own LLM-as-judge scores and then run DPO, closing the loop but capping quality at the judge's reliability (§9.15).

9.14 Self-play fine-tuning as a two-player game (SPIN)

SPIN casts alignment as a game: the current policy \(\pi_\theta\) tries to distinguish human responses from those generated by its previous iterate \(\pi_t\), which is a DPO-style objective with human data as the "winner" and self-generations as the "loser":

\[\mathcal{L}_{\text{SPIN}} = -\,\mathbb{E}_{x,\,y\sim p_{\text{data}},\,y'\sim\pi_t}\,\log\sigma\!\left(\lambda\log\frac{\pi_\theta(y\mid x)}{\pi_t(y\mid x)} - \lambda\log\frac{\pi_\theta(y'\mid x)}{\pi_t(y'\mid x)}\right).\]

The unique fixed point is \(\pi_\theta = p_{\text{data}}\): once the policy matches the data distribution, its samples are indistinguishable from real ones and the gradient vanishes. Self-play more broadly (SPIN, Absolute Zero, R-Zero) works whenever a checker or the data distribution supplies the winner signal for free — no human preferences required.

9.15 Reward hacking, Goodhart's law, and KL control

Let the true objective be \(r\) and the optimized proxy be \(\hat{r} = r + \varepsilon\). Hard optimization of \(\hat{r}\) drives the policy into regions where the error \(\varepsilon\) is large — and where the true \(r\) may actually fall: Goodhart's law, "when a measure becomes a target it ceases to be a good measure." The KL term in RLHF (§9.13) is the brake: at the optimum \(\mathrm{KL}(\pi^\star\|\pi_{\text{ref}})\) grows as \(\beta\) shrinks, so a smaller \(\beta\) permits more over-optimization. Empirically the true reward traces an over-optimization curve

\[r(\text{KL}) \approx \sqrt{\text{KL}}\,\big(\alpha - \gamma\,\text{KL}\big)\]

(rising, then falling as the proxy diverges from truth; Gao et al.). Controls: KL penalty / early stopping, reward-model ensembles, and stronger verifiers. The self-reward setting is the most exposed, because the policy can learn to fool its own judge — the formal reason Meta-Rewarding adds a meta-judge and why RSI loops need an external, hard-to-game verifier.

9.16 Model collapse: variance contraction under recursive training

Suppose generation \(t{+}1\) is trained on \(n\) samples drawn from the model fit at generation \(t\). Even in the ideal Gaussian case with an unbiased mean, the maximum-likelihood variance estimator is biased downward, and iterating shrinks variance in expectation:

\[\mathbb{E}[\sigma_{t+1}^2] = \Big(1 - \tfrac1n\Big)\,\mathbb{E}[\sigma_t^2] \quad\Longrightarrow\quad \mathbb{E}[\sigma_t^2] = \Big(1 - \tfrac1n\Big)^{t}\sigma_0^2 \xrightarrow{t\to\infty} 0.\]

Variance decays geometrically; the distribution's tails vanish first and its support contracts toward a point mass — the "curse of recursion" (model collapse). With finite \(n\) per generation the process is a supermartingale drifting to degeneracy. This is the quantitative danger in self-training (§6.3) and RSI (§7): recursively self-generated data erodes diversity and rare modes. Mitigations reintroduce external signal — mixing in fresh real data (anchoring), larger \(n\), and reward/verifier filtering.

9.17 Recursive self-improvement as a dynamical system

Let \(x_t\) be capability at round \(t\) and \(F\) the (self-)improvement operator, \(x_{t+1} = F(x_t)\). Local behavior near a fixed point \(x^\star = F(x^\star)\) is governed by the gain \(|F'(x^\star)|\):

In continuous time, writing the improvement rate as a power of current capability, \(\dot{x} = c\,x^{\,p}\), the exponent \(p\) decides the fate:

\[p < 1:\ \text{polynomial (no explosion)}; \qquad p = 1:\ x(t) = x_0 e^{ct}\ \text{(exponential)}; \qquad p > 1:\ x(t)\to\infty \ \text{as}\ t\to t^\star = \frac{x_0^{\,1-p}}{c\,(p-1)}.\]

The \(p>1\) case is a finite-time singularity — the precise mathematical shape of an "intelligence explosion" (I.J. Good's runaway). Which regime actually holds is empirical and, crucially, verifier-bounded: \(F\)'s signal comes from a checker, so capability can only be pushed as far as the verifier is correct (§9.5, §9.15). When verification is cheap and reliable (code, math, games) the loop can compound; in open-ended domains \(|F'|<1\) and it saturates — exactly why the 2025–2026 systems (Darwin Gödel Machine, AlphaEvolve, SEAL) pair self-modification with a hard automated evaluation gate.

9.18 The Gödel machine: provably beneficial self-modification

Schmidhuber's Gödel Machine holds its own program \(p\) (including a proof searcher) and a utility \(u\), and rewrites \(p\to p'\) only upon finding, within its axiomatic system \(\mathcal{A}\), a proof that the rewrite raises expected future utility:

\[\mathcal{A}\ \vdash\ \mathbb{E}\big[U(p')\big] \;>\; \mathbb{E}\big[U(p)\big].\]

Because any beneficial self-rewrite of the proof searcher itself is likewise gated by a proof, the improvements are globally optimal given \(\mathcal{A}\) — no myopic local edit can be provably better than the best provable rewrite. The catch is tractability: useful proofs are astronomically hard to find, so the Gödel machine is a theoretical ideal rather than a runnable system. The Darwin Gödel Machine (§7.2) is its practical relaxation — replace "prove it helps" with "empirically show it helps on a benchmark," trading provable optimality for open-ended, verifier-gated exploration.

Key

One skeleton recurs at every layer: a verifier or target distribution supplies signal, a KL or budget constraint bounds drift, and iteration either contracts to a ceiling or (rarely, when the verifier is reliable and returns super-linear) compounds. Self-consistency (§9.3), best-of-\(N\) (§9.5), EM self-training (§9.12), DPO/GRPO (§9.13), self-play (§9.14), and recursive self-improvement (§9.17) are the same mathematical object instantiated at the output, weight, and scaffold levels. The binding constraint is almost always the verifier.

9.19 Progressive disclosure as a context-budget optimization

Skills (§4.10) come with a clean piece of budget math. A library of \(M\) skills would cost \(\sum_{i=1}^M c_i\) tokens if every full body were resident (\(c_i\) = body size). Progressive disclosure keeps only metadata (\(d_i \ll c_i\), ~100 tokens) resident and loads a body only when the skill is selected. If skill \(i\) is triggered with probability \(\pi_i\), the expected resident cost is

\[\mathbb{E}[\text{tokens}] = \sum_{i=1}^{M} d_i + \sum_{i=1}^{M}\pi_i\,c_i \ \ll\ \sum_{i=1}^{M} c_i,\]

so a library can grow almost for free in metadata while paying a full body only for the few skills a task triggers — the same "smallest set of high-signal tokens" logic as context engineering (§3.1). Skill routing is retrieval: the model scores the task against each description and loads the top matches, so the description is the index key and its precision/recall governs both the hit rate and the false-load cost — exactly the scoring problem of §9.7. This is why authoring guidance obsesses over the description: it is the query-time relevance signal, and a mis-scoped one is either a retrieval miss (the skill never loads) or a false positive (wasted body tokens + distraction, §3.2). Self-authored skill libraries (§4.12) make \(M\) itself grow over time — capability accumulating as procedural memory rather than weights.

Appendix A: Thirty-One Things to Memorize

  1. The stack: prompt ⊂ context ⊂ harness, with graph cutting across and self-improvement wrapping all.
  2. Same model, different harness → large capability delta.
  3. Chain-of-Thought and Zero-shot CoT ("let's think step by step").
  4. Self-Consistency: majority vote over sampled chains; highest-ROI CoT add-on.
  5. Chain → Tree (ToT) → Graph (GoT) of thoughts.
  6. ReAct = reason + act + observe; the canonical agent loop.
  7. Don't over-prompt reasoning models — budget reasoning, don't scaffold it.
  8. Test-time compute: PRMs, compute-optimal scaling, DeepSeek-R1.
  9. Programmatic prompting: DSPy (signatures/compilers), TextGrad, ★ GEPA (reflection beats RL at fewer rollouts).
  10. ICL theory: induction heads, Bayesian inference, implicit GD; label correctness matters less than format/distribution.
  11. Instruction hierarchy + spotlighting; indirect prompt injection is the top agent risk.
  12. Context engineering = managing the whole dynamic window as a finite budget.
  13. Lost in the Middle and ★ Context Rot: bigger window ≠ solved.
  14. NoLiMa: literal needle-in-haystack overstates long-context reasoning.
  15. RAG: original, HyDE, hybrid + ColBERT rerank, ★ Contextual Retrieval.
  16. Adaptive RAG: Self-RAG, CRAG, FLARE.
  17. Agent memory: MemGPT, Mem0, ★ Zep/Graphiti temporal KG.
  18. Compaction, note-taking, JIT retrieval, sub-agent isolation for long horizons.
  19. Prompt compression: LLMLingua/-2; prompt caching for stable prefixes.
  20. Harness patterns (Anthropic): chaining, routing, parallelization, orchestrator-workers, evaluator-optimizer.
  21. MCP standardizes tools; CodeAct uses code as the action space.
  22. SWE-agent: the Agent-Computer Interface can matter more than the model.
  23. GraphRAG: Microsoft GraphRAG, LightRAG, HippoRAG, PathRAG.
  24. Optimizable agent graphs: ★ GPTSwarm, ★ AFlow; orchestration via LangGraph.
  25. Inference-time self-correction: Self-Refine, Reflexion, CRITIC.
  26. Caveat: LLMs can't self-correct reasoning without external feedback.
  27. Self-training: STaR, ReST-EM; self-reward: Self-Rewarding LMs, Constitutional AI.
  28. Self-play from zero: ★ Absolute Zero, ★ R-Zero; ★ TTRL.
  29. RSI: Gödel Machine (theory) → STOP, ADAS, ★ Darwin Gödel Machine, ★ AlphaEvolve, ★ SEAL.
  30. Every self-improvement loop is bounded by a verifier and a sandbox; beware model collapse and reward hacking.
  31. Agent Skills: packaged procedural knowledge (SKILL.md) via progressive disclosure; the description is the routing key; self-authored skill libraries (Voyager) are weight-free self-improvement.

Appendix B: Decision Guide — "Which Technique?"

  1. One-shot factual/format task? → Clear zero-shot instruction + structured outputs.
  2. Multi-step reasoning on a non-reasoning model? → CoT + Self-Consistency.
  3. Using a reasoning model? → Direct instructions; skip manual CoT; add a verifier for best-of-\(N\).
  4. Have eval data and want a better prompt? → Compile with DSPy / ★ GEPA.
  5. Answer needs private/fresh knowledge? → RAG (hybrid + rerank; ★ Contextual Retrieval).
  6. Global/multi-hop questions over a corpus? → GraphRAG / HippoRAG.
  7. Long-horizon agent losing the thread? → Compaction + note-taking + sub-agent isolation; temporal-KG memory (Zep).
  8. Context too big / expensive? → LLMLingua compression + prompt caching.
  9. Building an agent? → Simplest pattern that works; ReAct + MCP tools; add verification.
  10. Need explicit/loopy control flow? → LangGraph; to learn the flow → AFlow/GPTSwarm.
  11. Want the agent to improve at runtime? → Reflexion + a real verifier (never rely on intrinsic self-correction).
  12. Want the model to improve offline? → STaR/ReST-EM on verifiable tasks; self-play (Absolute Zero) where a checker exists.
  13. Want the scaffold to improve itself? → ADAS / ★ Darwin Gödel Machine, benchmark-gated + sandboxed.
  14. Want reusable, shareable procedural capability with no fine-tuning? → Author an Agent Skill (crisp description, progressive disclosure, bundled scripts); ship it in a plugin. Let the agent grow its own library (Voyager) for weight-free self-improvement.

Appendix C: Glossary

Appendix D: Year-by-Year Milestones