← Harness Engineering From First Principles

Plans, Workflows, and the Agent Loop

Compare free-form execution with named workflow gates while retaining the Pi agent loop.

An agent is given a bug report: “Retries are not attempted for transient failures.” It reads the scheduler, edits execute_with_retry to add a loop, runs the test suite, sees green, and reports: “Fixed. All tests pass.” The tests did pass. They had passed before the edit too, because no test exercised a transient failure. The agent never reproduced the bug, so it cannot know whether it fixed it. Nothing in its loop asked it to.

A second agent on the same report reproduces the failure with a new test, tries a fix, fails, tries another, fails, and continues for forty turns, rewriting the same function in slightly different ways until its budget runs out. Its last message is a confident summary of progress.

Both agents ran a capable model inside a correct agent loop. What both lacked was structure above the loop. The first had no point at which “reproduce the failure” was a precondition for “claim a fix”. The second had no point at which “two failed fixes” became “stop and report”. Chapter 2 named this gap: free-form looping “has no place to say ‘reproduction failed, stop and report’”. This chapter asks what goes in that place, and it pays particular attention to a question the book has deferred since Chapter 3. When people propose graphs as the structure, what exactly would a graph add?

Evidence status. Draft manuscript. The host-owned workflow demonstration D13-WORKFLOW-01 is implemented and executed (examples/pi-harness-lab/src/workflow.ts; test/workflow.test.ts, 12/12 pass, plus a file-backed Inspect → Propose → Validate → Apply → Verify scenario through the D06 edit gate). Dependency ordering, preconditions, authority, evidence-gated acceptance, bounded retry, stale-base refusal, cycle rejection and journal reconstruction all run with scripted effects. The free-form versus gated comparison (§13.8) and the sequential-versus-DAG study seed (§13.10) remain PROPOSED and EXPERIMENT PENDING — they need scripted-provider arms, live runs and isolation. Projects 02–05 and formal Project 06 have not started as formal projects. Project 01’s latest independent review returned REJECT (HARNESS-PROJECT-01-REVIEW-02). Pi seam facts come from R02 source inspection (Established for the inspected 1.6.0 artifact; TEST NOT RUN). Agent Framework and DeepSeek references are DOCUMENTED architecture descriptions only. One formal-methods source is DOCUMENTED (verified).

13.1 Three things called “a plan”

The word plan covers three different objects, and confusing them is the root of most bad workflow designs.

A model plan is text the model writes about what it intends to do: a numbered list, a todo list, a “first I will… then I will…”. It is a proposal, with the same standing as any other model output. It can be useful, as context for the model’s later turns and as a signal to a human, and it can also be wrong, abandoned or silently revised. Microsoft’s Agent Framework documents built-in todos and modes as harness features (R01-MICROSOFT.md R01-C02; DOCUMENTED). R01 notes, though, that “configuration is not proof of active enforcement”. A todo list the model maintains is still the model’s own list.

A workflow is a structure the harness owns. It is a set of named states, the transitions allowed between them, and the conditions (gates) that must hold for each transition. A workflow is a constraint. It decides what the run may do next, whatever the model proposes.

A control policy is the rule that chooses among the transitions a workflow allows. “If verification fails, retry the fix at most twice, then escalate” is a control policy. So is “choose the cheapest model that has passed this task family before” (Chapter 27), and so, eventually, is an ECK-style learned selection (Chapter 25). A workflow says what is possible. A policy says what is chosen.

The model plan, the workflow and the policy can coexist. A model may propose a plan inside a workflow state, and the host may check that plan against the workflow, or ignore it. But only the workflow and the policy constrain the run. A harness that turns the model’s plan into its workflow, executing whatever steps the model listed, has given the model control of its own gates. That is Chapter 1’s “second loop” problem arriving from the other direction.

13.2 Where the agent loop sits

Pi’s agent loop iterates model calls and tool calls until the session settles (Book I; R02-PI.md C08). A workflow does not replace that loop. The blueprint proposes the authoring constraint (PROPOSED): never fork or replace Pi’s loop for a feature that belongs at a host or tool seam. This input is a design rule, not a verified external result. The workflow sits around the loop, and its transitions happen at a coarser grain. R02’s mapping for Project 06 states the intended seam: “Existing boundary/custom tools; deterministic host transition gate independent of model continuation” (R02-PI.md, checkpoint implications).

There are two ways to nest them.

One session, gated from inside. A single long Pi session runs the whole task, and the host intervenes at boundaries using Pi’s extension seams. R02 records that blocking and mutating tool-call hooks, context transforms and boundary continuation exist (C12), and that agent_before_settle already exists in the 1.0.4 artifact (R02 drift section). This keeps conversational continuity. Its weakness is the one Chapter 11 identified: hooks run in-process with host privileges, so a gate implemented as a hook is control, not authority. And the model’s context accumulates everything from every phase (Chapter 7).

One episode per state, gated from outside. Each workflow state runs its own Pi episode: a fresh session, or a continued one with a host-corrected history (Chapter 9 §9.6). The episode runs with that state’s tools, budget and context. When it settles, the host evaluates the gate and chooses the next state. The model never decides a transition. It produces evidence that the gate inspects. This costs continuity and needs a context projection per state, which is a Chapter 7–8 problem. In return it puts every transition decision in host code, at a settlement boundary that R02 has characterized.

This book’s proposed default is the second: transitions at settlement, decided by the host (PROPOSED). The reasoning follows the earlier chapters. Settlement is the boundary where the host’s evidence is reconcilable (Chapter 4). Per-state tool surfaces give least capability per phase (Chapters 11–12). A per-state budget turns “forty turns of retries” into a bounded failure. The first design remains a legitimate alternative, and the study in §13.8 is the place to compare them, not this paragraph.

13.3 Seven structures often conflated with graphs

Arguments for graph-based harnesses often go wrong because “graph” names several different structures with different jobs. A finite-state machine is already a graph in the mathematical sense, since its transition diagram is a directed graph. So “using a graph” cannot by itself be the improvement. The useful question is which structure, used for what. Seven are worth separating.

Structure Nodes and edges Cycles? Executed or recorded? Question it answers
Sequential workflow Steps; “then” No (fail-stop only) Executed In what order do steps run?
Finite-state machine (FSM) States; guarded transitions Yes (retries, loops) Executed What may happen next, from here?
Dependency DAG Tasks; “must finish before” No, by definition Executed (scheduled) What can run now, and what is invalidated by a change?
General execution graph Steps; control flow, including cycles and runtime-created nodes Yes Executed Effectively a program: a workflow with loops and dynamic fan-out
Evidence / provenance graph Records; “derived from”, “supports”, “cites” No (in time) Recorded What supports this outcome? (Chapters 4, 8)
Knowledge graph Entities; claimed relations Any Recorded (content) What does the system believe about the world?

The seventh item, adaptive control policy, is not a graph representation: it is a function from state/history to an allowed choice. It decides which transition to take, while the six structures above represent execution or recorded relationships. Keep that function separate from its representation.

Three distinctions in the table carry the rest of the chapter.

Executed versus recorded. The first four structures drive execution. The evidence graph and the knowledge graph are records. They describe what happened and what is believed, and they do not decide anything. A system can have a rich evidence graph and a trivial sequential controller, or the reverse. Chapter 4’s insistence that a trace is not an outcome has a structural counterpart here: an evidence graph is not a workflow.

Representation versus policy. An FSM says that VERIFY → FIX is allowed. It does not say whether to take it now. That choice is the policy’s. Two harnesses with identical FSMs and different retry policies behave differently. Two harnesses with different representations and the same effective policy can behave identically.

Representation versus execution semantics. What actually happens when a transition fires is a separate matter again. Is it atomic? What if it fails halfway? Can two transitions run concurrently, and what happens to a join when one branch fails? Is the state durable before the next step begins? Those are execution semantics, and Chapters 9–10 showed that they decide recovery correctness. A dependency DAG executed by a scheduler that loses state on crash is less recoverable than a sequential workflow backed by a write-ahead journal.

13.4 What richer representations actually provide

If FSMs are already graphs, and any finite controller can be written as one, what could a richer representation offer? Classical formal methods have a precise answer for one family of extensions. Harel’s statecharts extend conventional state-transition diagrams with hierarchy and concurrency (orthogonal components). The motivation was that flat state diagrams for complex reactive systems become unstructured and grow exponentially in the number of states (D. Harel, “Statecharts: A visual formalism for complex systems”, Science of Computer Programming 8(3):231–274, 1987, doi:10.1016/0167-6423(87)90035-9; DOCUMENTED). The point to take from it is that, for finite control, these extensions buy compactness and modularity, not new expressive power. A statechart with two independent orthogonal regions describes the same behaviour as a flat FSM over the product of their states, but without writing out the product.

That gives a disciplined way to state what a graph-structured harness might provide. Each item below is a hypothesis, with the cost it carries:

  • H-R1, compactness under concurrency. When independent activities run in parallel (lint, type-check and test; or several files processed independently), a dependency DAG or orthogonal regions avoid the product-state blow-up of a flat FSM. Cost: join semantics must be defined (what if one branch fails?), and concurrency introduces interleavings to test.
  • H-R2, incremental invalidation. When an input changes (Chapter 6’s stale base), explicit dependency edges let the executor recompute only the affected downstream work, as incremental build systems do. A flat FSM needs an explicit transition for every invalidation case. Cost: the edges must be complete. A missing edge silently leaves stale results marked as fresh.
  • H-R3, partial recovery. After a crash, completed nodes whose inputs have not changed need not be redone. Cost: this is only as good as the execution semantics. Node completion must be durable and confirmed (Chapters 9–10), or “completed” is a claim.
  • H-R4, traceability. If the execution representation and the evidence graph share node identities, “which steps and evidence support this outcome?” becomes a graph query. Cost: coupling the controller to the record. A plain FSM plus a journal with step IDs can answer the same question with a join, so the advantage may be ergonomic, not fundamental.
  • H-R5, modifiability. Adding a state or gate may be cheaper in a hierarchical or graph representation. Cost: it is hard to measure without bias (Chapter 14 §14.6).

The null hypothesis deserves equal standing. For single-agent tasks that are mostly sequential with bounded retries, an explicit FSM plus a durable journal matches a graph-based workflow on correctness, recovery and traceability, at lower implementation complexity. If that is true, it is a valuable negative result. It would tell readers not to adopt graph machinery for the kind of task most agent harnesses actually run. Chapter 3 recorded the honest prior that, for a single run, the state machine already is the graph. This chapter extends it: the graph begins to earn its keep, if it does at all, only where H-R1 or H-R2 conditions actually arise.

One further point is easy to overlook, and it shapes how the question can be tested. The model does not see the transition table. Unless the host projects the workflow into the model’s context, a sequential workflow, an FSM and a DAG that impose the same gates and the same per-state context present identical inputs to the model. What the model does see is everything the host constructs per state — tool surfaces, budgets, context projections — and any host-authored history corrections (Chapter 9 §9.6). The G-text arm shows gate rules can also be made visible deliberately. The identical-inputs claim therefore holds exactly when per-state context is held equal across arms, which the proposed §14.6 design would enforce if built. Representation differences can therefore affect outcomes only through what the host does: ordering, parallelism, recovery and invalidation. They cannot affect them through model reasoning. That makes most of the comparison testable deterministically, with a scripted provider, without paying for live model variance (Chapter 14 §14.6).

13.5 What a gated workflow adds, and what it costs

Set graphs aside, and compare a free-form agent with an agent inside any host-owned workflow. The workflow adds four things that the loop alone cannot provide:

  1. Stop conditions the model cannot talk past. “Two failed fixes, then escalate” is enforced by a counter in host code, not by a sentence in the prompt.
  2. Evidence requirements for progress. A transition to FIX requires a reproduction record. A transition to REVIEW requires a verified patch. Chapter 14 makes these typed and deterministic.
  3. Per-state capability. INVESTIGATE gets read tools only, FIX gets the guarded edit tool (Chapter 6), and REPRODUCE and VERIFY get isolated test execution (Chapter 12). Least capability becomes a property of the phase, not a hope about the model.
  4. Per-state budget. A runaway phase fails inside its own budget instead of consuming the whole run’s.

It also costs things that advocates tend to omit:

  • Rigidity. Real tasks deviate. The bug cannot be reproduced. The “failing” test fails for an unrelated reason. The fix requires a dependency upgrade that is out of scope. A workflow without exits (UNREPRODUCIBLE, BLOCKED, NEEDS_HUMAN) forces the model to fabricate progress to satisfy a gate. A workflow is only as honest as its exits.
  • Context fragmentation. Per-state episodes lose the model’s earlier reasoning unless it is projected forward, with all of Chapter 8’s provenance concerns.
  • Gate design is engineering. A badly chosen gate is worse than none. It produces confident, gated, wrong results. Chapter 14 is about doing gates well.

Could ordinary deterministic software do this? Yes, and that is the recommendation. An FSM is an enum, a transition table and a journal. A few hundred lines of host code, which this book can test exhaustively, should precede any workflow framework. Before building even that, a project should check whether an existing system in the author’s ecosystem already provides it. R06 found real Writer runtime and domain code and a Praxis adapter, but characterized their retrieval, selection and promotion paths, not any workflow machinery (CLAIM-LEDGER.md H01-C14, H01-C15). Whether Writer, Worker or Mission Control already own a workflow engine suitable for Project 06 is an open question, not an assumption in either direction.

13.6 Worked example: the bug report, free-form and gated

The task is the bug report from the opening, applied to a disposable copy of a fixture descended from repo-scout-v1 (Chapter 7 §7.8’s versioning rule). The gated design below is executed (D13-WORKFLOW-01 with the D14 gates and the D06 edit gate); the free-form arm is the unbuilt comparison baseline, and the model loop itself is scripted out — transitions, not model behaviour, are what is tested.

Free-form. One Pi session, with all tools (read, edit, run tests) and an instruction listing the steps “reproduce, fix, verify”. The loop proceeds as in the opening. The agent edits, runs the suite, sees green and reports success. The trace contains a test run that passed. Nothing in it shows a failure that the edit turned into a pass. An outcome evaluator with a FAIL_TO_PASS oracle (Chapter 14 §14.3) would mark the run as not resolved. The run looked complete at every step.

Gated. The host runs the following FSM, with one Pi episode per active state and the transitions decided by host code at settlement:

    stateDiagram-v2
    [*] --> INVESTIGATE
    INVESTIGATE --> REPRODUCE: hypothesis recorded
    REPRODUCE --> FIX: reproduction evidence passes gate
    REPRODUCE --> UNREPRODUCIBLE: k attempts, no valid reproduction
    FIX --> VERIFY: patch staged (Ch 6 preconditions)
    VERIFY --> REVIEW: verified-patch evidence passes gate
    VERIFY --> FIX: gate fails, retries below 2
    VERIFY --> NEEDS_HUMAN: gate fails, retries reached 2
    REVIEW --> [*]: human decision
    UNREPRODUCIBLE --> [*]
    NEEDS_HUMAN --> [*]
  

Run the two failure modes from the opening through it. The first agent’s shortcut is impossible. FIX is reachable only after REPRODUCE produces evidence that a test fails on the base version for the reported reason, and REVIEW is reachable only after VERIFY shows that same test passing. The second agent’s spiral is bounded. After two failed verifications the policy takes VERIFY → NEEDS_HUMAN, and the run ends with an honest status and the evidence collected so far.

Notice what the diagram does and does not contain. It contains states, transitions and the names of gates. It does not contain the retry policy, which is the guard “retries below 2”, evaluated by host code. It does not say whether VERIFY’s checks run in parallel. And it does not say what happens on a crash between FIX and VERIFY. Those are policy and execution semantics, and the diagram is silent on both. That silence is why diagrams are not specifications. The executed counterpart is explicit: Workflow holds the transition table and the retry policy in host code, every admitted/executed/accepted/rejected step is journaled, and the two failure modes from the opening are scripted adversaries — the shortcut (no reproduction evidence → never admitted past its gate; no false REVIEW) and the spiral (bounded retries, then an honest terminal status instead of a fabricated fix).

13.7 Pi seams for a host-owned workflow

What the design needs from Pi, and what R02 supports:

  • A settlement boundary to transition on. agent_settled exists in 1.6.0 with an aborted field. Settlement is not task success (C08), which is exactly why the host’s gate, not settlement itself, decides the transition.
  • Per-state tool surfaces. Sessions accept explicit tool selection, with literal names rather than modifiers (C01, C02). The host constructs each episode with that state’s tools only.
  • Per-state context. Sessions accept an explicit runtime, settings and resources (C01). The host supplies each episode’s starting context. Building that projection is Chapter 8’s problem.
  • No hidden continuation. Compaction, retry and cache warming are defaults (C13). The workflow’s budget accounting must either disable them or count them (Chapter 10).

What R02 does not establish is how these seams behave under the workflow’s actual usage: many short sessions, tool surfaces switched between episodes, and host-corrected histories. That is TEST NOT RUN, and it is part of the Project 06 qualification in Chapter 14.

13.8 Study: free-form versus gated

The chapter brief asks for this comparison, with the Pi loop retained in both. The comparison is PROPOSED; EXPERIMENT PENDING. It depends on scripted-provider arms for F/G/G-text/G-1s, on the D06 edit and D12 isolation work for test execution, and on live runs for the model behaviour half. What is executed is the G mechanism itself: D13-WORKFLOW-01 runs the gated FSM with deterministic gates and exits, and D14-GATE-01 enforces the reproduction/verification gates with the no-work adversary refused.

Arm Structure Purpose
F Free-form: one session, all tools, the step list in the prompt Baseline
G Host-gated FSM (§13.6), one episode per state, deterministic gates, exits Treatment
G-text Same as F, plus the full gate rules as text in the prompt, unenforced Ablation. Separates the effect of enforcement from the effect of the instructions
G-1s Gated, but all states in one session with in-process hook gates Compares the two nesting designs (§13.2)

The tasks are disposable bug-fix fixtures, each with a sealed FAIL_TO_PASS and PASS_TO_PASS oracle (Chapter 14 §14.3). They include deliberately unreproducible reports and reports whose correct fix needs out-of-scope changes. Model, tools and total budget are matched across arms, and analysis is task-grouped and paired (Chapter 3).

Endpoints:

  • Verified resolution rate.
  • False success claims: the run reports success but the oracle says unresolved.
  • Honest exits: unreproducible tasks ending in UNREPRODUCIBLE rather than in fabricated fixes.
  • Budget overruns.
  • Tokens and wall time.

The registered predictions are these. G has fewer false success claims than F and G-text, and more honest exits on unreproducible tasks. G-text sits close to F, because instructions without enforcement do little. That prediction is the weakest, and it is the one most worth testing. G’s verified resolution rate is not predicted to be higher than F’s. Gates are expected to convert false successes into honest failures, not to make the model better at fixing bugs.

The falsifiers are G-text matching G on false success claims, which would mean the instructions did the work and not the enforcement, or G producing false success claims at all, which would mean a gate is broken.

13.9 Failure modes

  • Plan as workflow. The host executes the model’s own step list as its control structure. Defence: host-owned states and gates; model plans remain proposals.
  • Gates without exits. No UNREPRODUCIBLE or NEEDS_HUMAN, so the model fabricates progress. Defence: every gate has a non-success exit.
  • Diagram as specification. A state diagram is approved, and its policy and execution semantics are left implicit. Defence: write down the retry policy, the join rules and the crash semantics separately.
  • Graph by fashion. A graph framework is adopted for a sequential task. Defence: the null hypothesis in §13.4, and the study in Chapter 14.
  • In-process gates mistaken for authority. Hook-based gates in the single-session design. Defence: label them as control (Chapter 11), and keep authority at the broker.
  • Hidden continuation. Default retry or compaction runs inside a state and breaks its budget. Defence: disable them, or count them.

13.10 What you can build and test now

D13-WORKFLOW-01 and D14-GATE-01 already implement the core loop: the §13.6 FSM as a transition table with deterministic gates and a journal; exhaustive tests that no path reaches REVIEW without passing both gates; scripted adversaries trying the opening’s shortcut (no reproduction evidence → refused, no false REVIEW) and repeated failures (bounded retries, honest terminal states, NEEDS_HUMAN escalation path); per-state tools and journaled evidence. Extend it with the §13.8 arms (free-form baseline, G-text ablation, one-session variant) driven by scripted providers, and with the sequential-versus-DAG seed of the Chapter 14 study.

13.11 What remains unverified

  • The free-form versus gated comparison and the §13.8 arms (EXPERIMENT PENDING; needs scripted-provider episodes and isolation).
  • Pi 1.6.0 behaviour under many short per-state sessions with switched tool surfaces (TEST NOT RUN).
  • Whether an existing system in the author’s ecosystem (Writer, Worker, Mission Control, Praxis) already provides suitable workflow machinery. This is unknown, and a question to answer before building.
  • Every hypothesis H-R1 to H-R5 and the null hypothesis. They are registered for Chapter 14.

EXPERIMENT PENDING. The §13.8 comparison has not run; D13-WORKFLOW-01 and D14-GATE-01 execute the gated mechanism with scripted effects, not live episodes.

A gate has appeared throughout this chapter as a named predicate, “the reproduction passes”, without saying what makes such a predicate trustworthy. Project 01 has just supplied a sharp counterexample. Its completion gate accepted a correct answer that no tool had ever retrieved. Chapter 14 makes gates typed and deterministic, asks what evidence a gate must demand about the path as well as the result, and registers the representation study that this chapter has framed.

Previous: Chapter 12: Isolation, Approvals, and Trust Boundaries.

Next: Chapter 14: Typed Transitions and Deterministic Gates.