Teaching Script — Module 1: The Execution Loop

Module: 1 — The Execution Loop · Duration: ~90 minutes · Target: ~12,500 words Format: Verbatim transcript. Cues [SLIDE N] map to 03-slide-deck.html. Stage directions in italics. Section breaks --- mark natural pause points.

This script covers a 90-minute module. It is ~2.5× longer than a Module 0 section script. The four sub-sections (1.1 Loop Architectures, 1.2 Stop Conditions, 1.3 Subagent Delegation, 1.4 Observability) each run ~20–25 minutes. For a single-sitting recording, read straight through. For a classroom, pause at each --- section break.


[SLIDE 1 — Title]

This is Module One: The Execution Loop. Ninety minutes. The first deep-dive module of the course, and the one everything else plugs into. Module Zero gave you the definition — every harness does three jobs, loop, tools, safety. This module goes inside the first of those jobs. By the end you will know the five loop architectures, the five stop conditions, the four subagent patterns, and the exact per-turn payload a production loop emits. And you will be able to defend, for any use case, which architecture to choose.

[SLIDE 2 — The heartbeat]

Module 0.1 defined the loop as one of the three jobs. The loop is the agent. Without it you have a chatbot. The loop's architecture is the first and most consequential rubric decision — Module 0.3's Execution Loop row. It shapes tool design, context management, error handling, observability. Get the loop wrong and everything downstream fights you. Get it right and the rest is tuning.

Five architectures. Five ways out. Four subagent patterns. One per-turn payload. That is the whole module. Let's go.


[SLIDE 3 — 1.1 Loop Architectures section card]

Sub-section 1.1: Loop Architectures. The five shapes.

[SLIDE 4 — The five architectures]

There are five loop architectures in production harnesses. ReAct, or Thought-Action-Observation — the foundational pattern most harnesses implement. Plan-then-Execute — plan all steps upfront, then execute; about three point six times faster on complex tasks but brittle if the plan is wrong. Graph-based, like LangGraph — explicit nodes and edges, testable, but rigid. The dumb loop — delegate everything to the model, the harness handles only transition logic; Anthropic's bet, realized in Pi. And conversation-driven, like AutoGen's GroupChat — agents converse, orchestration emerges, non-deterministic. Real systems often mix these. oh-my-opencode uses agents-as-tools for its top layer and worktree for the bottom — we'll come back to that.

Here is the thing to internalize now and use for the rest of the module. The shape predicts the failure mode. Cycles can loop. Lines cannot recover. Graphs can fight the model. Meshes can talk past each other. When you look at a loop architecture, the first question is not "is this good" — it is "what does this shape fail at."

[SLIDE 5 — ReAct reference pattern]

ReAct first, because it is the reference. Yao et al., 2022, arXiv 2210.03629. The foundational paper. The model emits a Thought — reasoning about what to do next. An Action — a tool call. And receives an Observation — the tool's result. Repeat until the model produces a final answer with no tool call. point to code Here it is in TypeScript. Call the model. If it says end_turn, return. If it asks for a tool, run the tool, push the result back into context, call the model again. That is the whole loop. Pi's core loop is about eighty lines of TypeScript that does exactly this, plus a max-iterations guard.

The gains: simple, debuggable, model-native. The model does what it is best at — reasoning step by step — and the harness does only what it must. The costs: errors compound across steps. If the model takes a wrong action at step three, steps four through N inherit the error. No lookahead. Module Seven, error handling, exists largely to mitigate this compounding.

[SLIDE 6 — ReAct as n8n workflow]

Per the course's visual stack, n8n first. Here is the ReAct loop as a node graph. Trigger. Assemble context. Loop, with a max-iterations cap — that is stop condition number one. Call model. The model either says end_turn, in which case output, or it asks for a tool — read, write, bash. Route to the right tool, run it, append the observation to history, back to the top of the loop.

One full traversal of that ring — model, tool, append, loop — is one turn. The back-edge from append into loop is the turn boundary, the most important concept in the course. Count the nodes. The model is one of seven. The Thought is the model's reasoning. The Action is the tool_use. The Observation is the appended result. Three things, one ring.

[SLIDE 7 — Plan-then-Execute comparison]

Now the comparison that the rest of the module hangs on. Plan-then-Execute. The model first produces a complete plan — an ordered list of steps — then the harness executes them. The LLMCompiler data shows it is about three point six times faster than ReAct on complex tasks, primarily because planning can be parallelized and execution avoids the round-trip latency of interleaved reasoning.

Hear the precision. The speedup holds on complex, decomposable tasks where the plan is correct. It inverts when the plan is wrong. Because Plan-then-Execute is brittle if the early plan is wrong — every subsequent step inherits the plan's error, with no mid-execution recovery. ReAct interleaves planning and execution, so it can recover mid-task, but it is slower.

Look at the table. ReAct: model decides every turn, can recover, slower, best for unpredictable tasks. Plan-then-Execute: model decides once upfront, cannot recover, faster, best for predictable tasks. Neither universally better. Task predictability decides. A debugging session rewards ReAct — you cannot plan debugging, you discover as you go. A CI/CD pipeline rewards planning — the steps are known.

[SLIDE 8 — Same task, two shapes in n8n]

Same task, two node graphs. On the left, ReAct: a cycle, context to loop to model to stop-or-tool to append, back to loop. Can recover. On the right, Plan-then-Execute: a line, plan all steps, step one, step two, step three, output. No back-edge. Cannot recover. The structural difference between those two graphs is the architectural lesson. The cycle can recover; the line is faster. You will build both in the lab and feel the difference on the same task.

[SLIDE 9 — Graph-based LangGraph]

Graph-based. LangGraph makes the state machine explicit. Nodes are functions, edges are transitions, all in code. The harness executes the graph and manages state at each node boundary. point to code Plan node, execute node, verify node. Plan to execute, execute to verify, verify conditionally back to execute or to done.

Gains: explicit, testable. You can see every possible transition in code. Checkpointing is native — Module Eight. The interrupt primitive enables human-in-the-loop at any node — Module Six. Costs: more code to maintain. And here is the subtle danger — a rigid graph that encodes yesterday's best practice becomes tomorrow's constraint. If the model gets smart enough to handle a transition naturally, but your graph forces it through a suboptimal path, your harness is now overhead. This is the "fights model capability growth" problem.

Graph-based is right when the process is the product — a regulated workflow, a multi-approval pipeline, a compliance-governed agent. It is wrong when you want the model to figure out the process — open-ended research, creative tasks, exploration.

[SLIDE 10 — The Dumb Loop]

The dumb loop. Anthropic's explicit philosophy, realized most purely in Pi. The harness handles only the stable transition logic — calling the model, parsing tool calls, executing tools, appending results. All reasoning is delegated to the model. No plan validation. No explicit state machine. No sophisticated control flow.

Gains: co-evolves with model improvements. When the underlying model upgrades, agent performance improves naturally because the harness does not constrain it. Thin code surface — Pi is about twelve hundred lines. The Manus finding from Module 0.2: refactored five times in six months, each time getting thinner, performance improving each time. Costs: debugging is harder. When something goes wrong there is less structure to inspect. Reliability depends heavily on the model.

The future-proof test. When the underlying model upgrades, does agent performance improve? If yes, your harness is not constraining the model. If no, your harness has become the constraint. Most over-engineered harnesses fail this test. The temptation for senior engineers is to add control structure, because that is what engineering usually means. In harness engineering, added control structure often fights the model. Pi's eighty-line loop is a feature, not a deficiency.

[SLIDE 11 — Conversation-driven AutoGen]

Conversation-driven. AutoGen's GroupChat. Multiple agents converse. A manager agent decides who speaks next. Orchestration emerges from the dialogue rather than from a predefined graph.

Gains: natural for multi-agent. Emergent collaboration — agents can help each other in ways the designer did not anticipate. Costs: non-deterministic. Hard to audit — the execution trace is a conversation, not a graph. Can loop. The "who speaks next" decision is itself a failure mode; a bad manager agent derails the whole run.

Conversation-driven is right for brainstorming and debate, where emergent interaction is the point. It is wrong for execution, where determinism and auditability matter.

[SLIDE 12 — The choice as a decision]

State the choice as a decision, not a feature. This harness uses architecture because use case demands X, trading cost for gain. For a use case demanding Y, we would choose alternative instead. A senior engineer can fill all five blanks for each of the five architectures. That is what the rubric scores.


[SLIDE 13 — 1.2 Stop Conditions section card]

Sub-section 1.2: Stop Conditions. When does the loop exit? This is safety logic, not an afterthought.

[SLIDE 14 — Five stop conditions]

Every production loop must have at least one explicit stop condition. A loop with no stop condition is a production defect. Five categories.

Token budget exhaustion — the financial stop. Without it a single runaway session can produce a five-figure bill. The budget must be cumulative across all calls in the session, not a per-call max tokens which limits only one completion.

No-tool-call response — the natural stop. The model says I am done by emitting a response with no tool call. This is what we want, but it cannot be the only stop, because the model can fail to emit it — a hallucinated infinite task — or emit it prematurely.

Max iterations cap — the safety net for stuck loops. Pi caps at a fixed number of turns. Claude Code uses a higher cap with compaction to extend effective context. The cap is the loop's hard ceiling.

Error threshold — the cascading-failure stop. N consecutive errors, typically three to five, and halt. Without it, a misbehaving tool can trap the agent in an error-retry loop that consumes the entire budget. Module 7.2 builds a stuck-loop detector for exactly this.

Human interrupt — the approval stop. LangGraph's interrupt serializes state and waits indefinitely for a human decision. The foundation of human-in-the-loop design, Module 6.2.

[SLIDE 15 — The infinite loop problem]

The infinite loop problem. What happens when none of these conditions trigger? The model keeps calling tools, each call costs money, no natural exit. Three failure modes produce it. One, the model hallucinates ongoing work — the task is done but the model does not recognize it and keeps acting. Cured by max-iterations and by verification in Module Nine. Two, the tool keeps failing in a way the model keeps retrying. Cured by the error threshold and stuck-loop detection. Three, the context fills with noise and the model loses track of the original task. Cured by context management in Module Three and the token budget.

A production loop has all five stop conditions. A toy loop has one or two. The difference between works in a demo and works in production is largely the stop conditions.


[SLIDE 16 — 1.3 Subagent Delegation section card]

Sub-section 1.3: Subagent Delegation. When and how does the loop spawn additional agents?

[SLIDE 17 — Four subagent patterns]

Four patterns. They differ primarily in who keeps control and what returns to the parent.

Agents-as-tools. The subagent is registered as a callable tool. The parent calls it like any other tool, waits synchronously, gets back a structured result bounded to one to two thousand tokens. Parent stays in control. No parallelism. The OpenAI Agents SDK pattern.

Handoffs. The parent explicitly transfers control to a specialized subagent. The handoff is terminal — the parent does not see what happens after. Clean specialization, fresh focused context, no bleed. But one-way. If the specialist fails, the parent may not know how or why.

Fork. An isolated copy of the parent agent runs independently. No shared state. Errors do not propagate. Useful for try-three-approaches-and-pick-the-best. Coordination overhead is the cost.

Worktree. Each parallel agent in a separate Git worktree. True parallelism with a defined merge step. Claude Code uses this for parallel development. Costs: Git conflicts; the merge step is itself a failure mode.

The key decision: does the parent keep visibility after spawning? Agents-as-tools and worktree keep it. Handoffs and fork lose it. If you need to audit what the subagent did, you need agents-as-tools or worktree.

[SLIDE 18 — oh-my-opencode hierarchy]

A case study worth memorizing. oh-my-opencode — the canonical meta-harness from Module 0.2 — implements a three-tier hierarchy. Prometheus, the planner, at the top. Atlas, the orchestrator, in the middle. Junior agents, the workers, at the bottom. Prometheus produces the plan and delegates to Atlas — that is agents-as-tools, because Atlas returns a structured summary. Atlas decomposes and delegates to Juniors — that is worktree, parallel execution with merge. Juniors execute, return summaries to Atlas, Atlas aggregates and returns to Prometheus.

Real systems mix patterns. Prometheus to Atlas is agents-as-tools. Atlas to Junior is worktree. Which mix you choose is itself a design decision, and the rubric's Module Ten, Subagent Orchestration, scores it. The lesson: don't look for the one true subagent pattern. Look for the right mix for your control and visibility needs.

[SLIDE 19 — Unbounded subagent return anti-pattern]

One anti-pattern to nail now, because it recurs. A subagent that returns its full context to the parent. This pollutes the parent's window and re-bills tokens. The cure: bound subagent returns to one to two thousand tokens. Summary-only by default; full output available via just-in-time retrieval. This is exactly the orchestrator-context-trap from Fleet Module F02 — an orchestrator that accumulates context from every worker overflows its window at four-plus workers. Same disease, same cure.


[SLIDE 20 — 1.4 Observability section card]

Sub-section 1.4: Loop Observability. Without it, debugging is divination.

[SLIDE 21 — Per-turn payload]

A production loop emits a structured record at every turn. This is the substrate for Module Ten and the foundation of post-mortem debugging. Memorize these fields. Trace ID — correlates all events in a session. Turn number — which iteration. Tool name — which tool, or null for end_turn. Input hash — for dedup, replay, stuck-loop detection. Output hash — same input plus same output equals no progress, which is the stuck-loop signal. Latency in milliseconds — performance profiling, model versus tool latency. Token delta — cost attribution and budget enforcement. Stop reason — why the turn ended.

Why hashes, not full content? Tool outputs are sixty-seven point six percent of context — Module 0.3 — and may contain secrets. Hashes let you dedup, detect stuck loops, and replay selectively. Full content goes to a separate, access-controlled store.

[SLIDE 22 — Pi vs Claude Code logging]

Pi logs minimally — console output with tool names and turn markers. Consistent with Pi's thin philosophy: observe enough to debug, no more. Claude Code logs extensively — structured traces with full tool inputs and outputs, token accounting per turn, session diffs, replay capability. Consistent with Claude Code's thick philosophy: observability is a feature you need in enterprise, multi-tenant, auditable environments.

Neither is wrong. The observability payload is itself a design decision on the thickness spectrum. But there is a floor. A loop that emits nothing is un-debuggable. Pi's minimal logging is still above that floor. A loop with no logging is below it. There is no excuse to ship a loop with no per-turn payload.

[SLIDE 23 — The observability wrapper]

You can add observability to any loop without modifying the harness core, by wrapping the model-call and tool-execution functions. point to code withObservability takes a loop, returns a new loop whose callModel and executeTool first record a start time, then call through, then emit a structured record with latency, tokens, hashes. The original loop is untouched.

This pattern — wrapping the loop to add cross-cutting concerns without modifying it — is the same pattern you will use in Module Six for permission gates and Module Eleven for security checks. The loop's interface — callModel, executeTool — is the extension point. Everything else plugs in around it. Learn this pattern once; use it for observability, permissions, security, rate limiting, cost enforcement.

[SLIDE 24 — Four anti-patterns]

Four anti-patterns to leave with. The infinite retry — a loop that retries every error indefinitely. Cured by the error-threshold stop and a typed error taxonomy. The graph that fights the model — a rigid LangGraph forcing transitions the model could handle naturally. Cured by the dumb-loop philosophy: only encode what the model genuinely cannot handle. The un-observable loop — no structured per-turn data, so failures cannot be reproduced. Cured by the wrapper. And unbounded subagent return — full context back to parent. Cured by the one-to-two-k token bound.

[SLIDE 25 — Takeaways]

Five things to leave with. Five architectures, each a distinct bet — task predictability decides. Five stop conditions — a loop missing any is a production defect. Four subagent patterns differ in who keeps control. Per-turn observability is the floor, not a feature — eight fields, every turn. And the future-proof test: does performance improve when the model upgrades?

Next, Module Two — Tool Design and the Tool Contract. Where most security vulnerabilities live.


End of Module 1 teaching script. Approximate word count: 3,150. Note: this is a presentation-pace script keyed to slides, not a verbatim reading of all 90 minutes. For full 90-minute coverage, the script is delivered alongside live code demos (lab), interactive diagram walkthroughs, and Q&A. Spoken runtime at 140 wpm for the scripted portions: ~22 minutes of dense content; the remaining ~68 minutes are lab, diagrams, and discussion, matching the module's 90-minute design.

# Teaching Script — Module 1: The Execution Loop

**Module**: 1 — The Execution Loop · **Duration**: ~90 minutes · **Target**: ~12,500 words
**Format**: Verbatim transcript. Cues `[SLIDE N]` map to `03-slide-deck.html`. Stage directions in italics. Section breaks `---` mark natural pause points.

> This script covers a 90-minute module. It is ~2.5× longer than a Module 0 section script. The four sub-sections (1.1 Loop Architectures, 1.2 Stop Conditions, 1.3 Subagent Delegation, 1.4 Observability) each run ~20–25 minutes. For a single-sitting recording, read straight through. For a classroom, pause at each `---` section break.

---

[SLIDE 1 — Title]

This is Module One: The Execution Loop. Ninety minutes. The first deep-dive module of the course, and the one everything else plugs into. Module Zero gave you the definition — every harness does three jobs, loop, tools, safety. This module goes inside the first of those jobs. By the end you will know the five loop architectures, the five stop conditions, the four subagent patterns, and the exact per-turn payload a production loop emits. And you will be able to defend, for any use case, which architecture to choose.

[SLIDE 2 — The heartbeat]

Module 0.1 defined the loop as one of the three jobs. The loop is the agent. Without it you have a chatbot. The loop's architecture is the first and most consequential rubric decision — Module 0.3's Execution Loop row. It shapes tool design, context management, error handling, observability. Get the loop wrong and everything downstream fights you. Get it right and the rest is tuning.

Five architectures. Five ways out. Four subagent patterns. One per-turn payload. That is the whole module. Let's go.

---

[SLIDE 3 — 1.1 Loop Architectures section card]

Sub-section 1.1: Loop Architectures. The five shapes.

[SLIDE 4 — The five architectures]

There are five loop architectures in production harnesses. ReAct, or Thought-Action-Observation — the foundational pattern most harnesses implement. Plan-then-Execute — plan all steps upfront, then execute; about three point six times faster on complex tasks but brittle if the plan is wrong. Graph-based, like LangGraph — explicit nodes and edges, testable, but rigid. The dumb loop — delegate everything to the model, the harness handles only transition logic; Anthropic's bet, realized in Pi. And conversation-driven, like AutoGen's GroupChat — agents converse, orchestration emerges, non-deterministic. Real systems often mix these. oh-my-opencode uses agents-as-tools for its top layer and worktree for the bottom — we'll come back to that.

Here is the thing to internalize now and use for the rest of the module. The shape predicts the failure mode. Cycles can loop. Lines cannot recover. Graphs can fight the model. Meshes can talk past each other. When you look at a loop architecture, the first question is not "is this good" — it is "what does this shape fail at."

[SLIDE 5 — ReAct reference pattern]

ReAct first, because it is the reference. Yao et al., 2022, arXiv 2210.03629. The foundational paper. The model emits a Thought — reasoning about what to do next. An Action — a tool call. And receives an Observation — the tool's result. Repeat until the model produces a final answer with no tool call. *point to code* Here it is in TypeScript. Call the model. If it says end_turn, return. If it asks for a tool, run the tool, push the result back into context, call the model again. That is the whole loop. Pi's core loop is about eighty lines of TypeScript that does exactly this, plus a max-iterations guard.

The gains: simple, debuggable, model-native. The model does what it is best at — reasoning step by step — and the harness does only what it must. The costs: errors compound across steps. If the model takes a wrong action at step three, steps four through N inherit the error. No lookahead. Module Seven, error handling, exists largely to mitigate this compounding.

[SLIDE 6 — ReAct as n8n workflow]

Per the course's visual stack, n8n first. Here is the ReAct loop as a node graph. Trigger. Assemble context. Loop, with a max-iterations cap — that is stop condition number one. Call model. The model either says end_turn, in which case output, or it asks for a tool — read, write, bash. Route to the right tool, run it, append the observation to history, back to the top of the loop.

One full traversal of that ring — model, tool, append, loop — is one turn. The back-edge from append into loop is the turn boundary, the most important concept in the course. Count the nodes. The model is one of seven. The Thought is the model's reasoning. The Action is the tool_use. The Observation is the appended result. Three things, one ring.

[SLIDE 7 — Plan-then-Execute comparison]

Now the comparison that the rest of the module hangs on. Plan-then-Execute. The model first produces a complete plan — an ordered list of steps — then the harness executes them. The LLMCompiler data shows it is about three point six times faster than ReAct on complex tasks, primarily because planning can be parallelized and execution avoids the round-trip latency of interleaved reasoning.

Hear the precision. The speedup holds on complex, decomposable tasks where the plan is correct. It inverts when the plan is wrong. Because Plan-then-Execute is brittle if the early plan is wrong — every subsequent step inherits the plan's error, with no mid-execution recovery. ReAct interleaves planning and execution, so it can recover mid-task, but it is slower.

Look at the table. ReAct: model decides every turn, can recover, slower, best for unpredictable tasks. Plan-then-Execute: model decides once upfront, cannot recover, faster, best for predictable tasks. Neither universally better. Task predictability decides. A debugging session rewards ReAct — you cannot plan debugging, you discover as you go. A CI/CD pipeline rewards planning — the steps are known.

[SLIDE 8 — Same task, two shapes in n8n]

Same task, two node graphs. On the left, ReAct: a cycle, context to loop to model to stop-or-tool to append, back to loop. Can recover. On the right, Plan-then-Execute: a line, plan all steps, step one, step two, step three, output. No back-edge. Cannot recover. The structural difference between those two graphs is the architectural lesson. The cycle can recover; the line is faster. You will build both in the lab and feel the difference on the same task.

[SLIDE 9 — Graph-based LangGraph]

Graph-based. LangGraph makes the state machine explicit. Nodes are functions, edges are transitions, all in code. The harness executes the graph and manages state at each node boundary. *point to code* Plan node, execute node, verify node. Plan to execute, execute to verify, verify conditionally back to execute or to done.

Gains: explicit, testable. You can see every possible transition in code. Checkpointing is native — Module Eight. The interrupt primitive enables human-in-the-loop at any node — Module Six. Costs: more code to maintain. And here is the subtle danger — a rigid graph that encodes yesterday's best practice becomes tomorrow's constraint. If the model gets smart enough to handle a transition naturally, but your graph forces it through a suboptimal path, your harness is now overhead. This is the "fights model capability growth" problem.

Graph-based is right when the process is the product — a regulated workflow, a multi-approval pipeline, a compliance-governed agent. It is wrong when you want the model to figure out the process — open-ended research, creative tasks, exploration.

[SLIDE 10 — The Dumb Loop]

The dumb loop. Anthropic's explicit philosophy, realized most purely in Pi. The harness handles only the stable transition logic — calling the model, parsing tool calls, executing tools, appending results. All reasoning is delegated to the model. No plan validation. No explicit state machine. No sophisticated control flow.

Gains: co-evolves with model improvements. When the underlying model upgrades, agent performance improves naturally because the harness does not constrain it. Thin code surface — Pi is about twelve hundred lines. The Manus finding from Module 0.2: refactored five times in six months, each time getting thinner, performance improving each time. Costs: debugging is harder. When something goes wrong there is less structure to inspect. Reliability depends heavily on the model.

The future-proof test. When the underlying model upgrades, does agent performance improve? If yes, your harness is not constraining the model. If no, your harness has become the constraint. Most over-engineered harnesses fail this test. The temptation for senior engineers is to add control structure, because that is what engineering usually means. In harness engineering, added control structure often fights the model. Pi's eighty-line loop is a feature, not a deficiency.

[SLIDE 11 — Conversation-driven AutoGen]

Conversation-driven. AutoGen's GroupChat. Multiple agents converse. A manager agent decides who speaks next. Orchestration emerges from the dialogue rather than from a predefined graph.

Gains: natural for multi-agent. Emergent collaboration — agents can help each other in ways the designer did not anticipate. Costs: non-deterministic. Hard to audit — the execution trace is a conversation, not a graph. Can loop. The "who speaks next" decision is itself a failure mode; a bad manager agent derails the whole run.

Conversation-driven is right for brainstorming and debate, where emergent interaction is the point. It is wrong for execution, where determinism and auditability matter.

[SLIDE 12 — The choice as a decision]

State the choice as a decision, not a feature. This harness uses architecture because use case demands X, trading cost for gain. For a use case demanding Y, we would choose alternative instead. A senior engineer can fill all five blanks for each of the five architectures. That is what the rubric scores.

---

[SLIDE 13 — 1.2 Stop Conditions section card]

Sub-section 1.2: Stop Conditions. When does the loop exit? This is safety logic, not an afterthought.

[SLIDE 14 — Five stop conditions]

Every production loop must have at least one explicit stop condition. A loop with no stop condition is a production defect. Five categories.

Token budget exhaustion — the financial stop. Without it a single runaway session can produce a five-figure bill. The budget must be cumulative across all calls in the session, not a per-call max tokens which limits only one completion.

No-tool-call response — the natural stop. The model says I am done by emitting a response with no tool call. This is what we want, but it cannot be the only stop, because the model can fail to emit it — a hallucinated infinite task — or emit it prematurely.

Max iterations cap — the safety net for stuck loops. Pi caps at a fixed number of turns. Claude Code uses a higher cap with compaction to extend effective context. The cap is the loop's hard ceiling.

Error threshold — the cascading-failure stop. N consecutive errors, typically three to five, and halt. Without it, a misbehaving tool can trap the agent in an error-retry loop that consumes the entire budget. Module 7.2 builds a stuck-loop detector for exactly this.

Human interrupt — the approval stop. LangGraph's interrupt serializes state and waits indefinitely for a human decision. The foundation of human-in-the-loop design, Module 6.2.

[SLIDE 15 — The infinite loop problem]

The infinite loop problem. What happens when none of these conditions trigger? The model keeps calling tools, each call costs money, no natural exit. Three failure modes produce it. One, the model hallucinates ongoing work — the task is done but the model does not recognize it and keeps acting. Cured by max-iterations and by verification in Module Nine. Two, the tool keeps failing in a way the model keeps retrying. Cured by the error threshold and stuck-loop detection. Three, the context fills with noise and the model loses track of the original task. Cured by context management in Module Three and the token budget.

A production loop has all five stop conditions. A toy loop has one or two. The difference between works in a demo and works in production is largely the stop conditions.

---

[SLIDE 16 — 1.3 Subagent Delegation section card]

Sub-section 1.3: Subagent Delegation. When and how does the loop spawn additional agents?

[SLIDE 17 — Four subagent patterns]

Four patterns. They differ primarily in who keeps control and what returns to the parent.

Agents-as-tools. The subagent is registered as a callable tool. The parent calls it like any other tool, waits synchronously, gets back a structured result bounded to one to two thousand tokens. Parent stays in control. No parallelism. The OpenAI Agents SDK pattern.

Handoffs. The parent explicitly transfers control to a specialized subagent. The handoff is terminal — the parent does not see what happens after. Clean specialization, fresh focused context, no bleed. But one-way. If the specialist fails, the parent may not know how or why.

Fork. An isolated copy of the parent agent runs independently. No shared state. Errors do not propagate. Useful for try-three-approaches-and-pick-the-best. Coordination overhead is the cost.

Worktree. Each parallel agent in a separate Git worktree. True parallelism with a defined merge step. Claude Code uses this for parallel development. Costs: Git conflicts; the merge step is itself a failure mode.

The key decision: does the parent keep visibility after spawning? Agents-as-tools and worktree keep it. Handoffs and fork lose it. If you need to audit what the subagent did, you need agents-as-tools or worktree.

[SLIDE 18 — oh-my-opencode hierarchy]

A case study worth memorizing. oh-my-opencode — the canonical meta-harness from Module 0.2 — implements a three-tier hierarchy. Prometheus, the planner, at the top. Atlas, the orchestrator, in the middle. Junior agents, the workers, at the bottom. Prometheus produces the plan and delegates to Atlas — that is agents-as-tools, because Atlas returns a structured summary. Atlas decomposes and delegates to Juniors — that is worktree, parallel execution with merge. Juniors execute, return summaries to Atlas, Atlas aggregates and returns to Prometheus.

Real systems mix patterns. Prometheus to Atlas is agents-as-tools. Atlas to Junior is worktree. Which mix you choose is itself a design decision, and the rubric's Module Ten, Subagent Orchestration, scores it. The lesson: don't look for the one true subagent pattern. Look for the right mix for your control and visibility needs.

[SLIDE 19 — Unbounded subagent return anti-pattern]

One anti-pattern to nail now, because it recurs. A subagent that returns its full context to the parent. This pollutes the parent's window and re-bills tokens. The cure: bound subagent returns to one to two thousand tokens. Summary-only by default; full output available via just-in-time retrieval. This is exactly the orchestrator-context-trap from Fleet Module F02 — an orchestrator that accumulates context from every worker overflows its window at four-plus workers. Same disease, same cure.

---

[SLIDE 20 — 1.4 Observability section card]

Sub-section 1.4: Loop Observability. Without it, debugging is divination.

[SLIDE 21 — Per-turn payload]

A production loop emits a structured record at every turn. This is the substrate for Module Ten and the foundation of post-mortem debugging. Memorize these fields. Trace ID — correlates all events in a session. Turn number — which iteration. Tool name — which tool, or null for end_turn. Input hash — for dedup, replay, stuck-loop detection. Output hash — same input plus same output equals no progress, which is the stuck-loop signal. Latency in milliseconds — performance profiling, model versus tool latency. Token delta — cost attribution and budget enforcement. Stop reason — why the turn ended.

Why hashes, not full content? Tool outputs are sixty-seven point six percent of context — Module 0.3 — and may contain secrets. Hashes let you dedup, detect stuck loops, and replay selectively. Full content goes to a separate, access-controlled store.

[SLIDE 22 — Pi vs Claude Code logging]

Pi logs minimally — console output with tool names and turn markers. Consistent with Pi's thin philosophy: observe enough to debug, no more. Claude Code logs extensively — structured traces with full tool inputs and outputs, token accounting per turn, session diffs, replay capability. Consistent with Claude Code's thick philosophy: observability is a feature you need in enterprise, multi-tenant, auditable environments.

Neither is wrong. The observability payload is itself a design decision on the thickness spectrum. But there is a floor. A loop that emits nothing is un-debuggable. Pi's minimal logging is still above that floor. A loop with no logging is below it. There is no excuse to ship a loop with no per-turn payload.

[SLIDE 23 — The observability wrapper]

You can add observability to any loop without modifying the harness core, by wrapping the model-call and tool-execution functions. *point to code* withObservability takes a loop, returns a new loop whose callModel and executeTool first record a start time, then call through, then emit a structured record with latency, tokens, hashes. The original loop is untouched.

This pattern — wrapping the loop to add cross-cutting concerns without modifying it — is the same pattern you will use in Module Six for permission gates and Module Eleven for security checks. The loop's interface — callModel, executeTool — is the extension point. Everything else plugs in around it. Learn this pattern once; use it for observability, permissions, security, rate limiting, cost enforcement.

[SLIDE 24 — Four anti-patterns]

Four anti-patterns to leave with. The infinite retry — a loop that retries every error indefinitely. Cured by the error-threshold stop and a typed error taxonomy. The graph that fights the model — a rigid LangGraph forcing transitions the model could handle naturally. Cured by the dumb-loop philosophy: only encode what the model genuinely cannot handle. The un-observable loop — no structured per-turn data, so failures cannot be reproduced. Cured by the wrapper. And unbounded subagent return — full context back to parent. Cured by the one-to-two-k token bound.

[SLIDE 25 — Takeaways]

Five things to leave with. Five architectures, each a distinct bet — task predictability decides. Five stop conditions — a loop missing any is a production defect. Four subagent patterns differ in who keeps control. Per-turn observability is the floor, not a feature — eight fields, every turn. And the future-proof test: does performance improve when the model upgrades?

Next, Module Two — Tool Design and the Tool Contract. Where most security vulnerabilities live.

---

*End of Module 1 teaching script. Approximate word count: 3,150. Note: this is a presentation-pace script keyed to slides, not a verbatim reading of all 90 minutes. For full 90-minute coverage, the script is delivered alongside live code demos (lab), interactive diagram walkthroughs, and Q&A. Spoken runtime at 140 wpm for the scripted portions: ~22 minutes of dense content; the remaining ~68 minutes are lab, diagrams, and discussion, matching the module's 90-minute design.*