← Harness Engineering From First Principles

Typed Transitions and Deterministic Gates

Require a reproduced failure and verified passing patch before entering the review state.

Project 01’s latest independent review found a run that ended VERIFIED_CORRECT with trace verdict COMPLETE and cleanup CONFIRMED, in which the model called no tools at all. The reviewer used the supported scripting path to have the real Pi loop return a pre-authored, correct T1 answer, digest included, in a single turn. Zero tool starts. Zero tool results. No detections. The unchanged bundle then replayed with verdictMatch: true (HARNESS-PROJECT-01-REVIEW-02/P01-REVIEW-02-REPORT.md, P01R-02; OBSERVED). The reviewer’s diagnosis: “a correct pre-authored answer/hash satisfies the evaluator from the frozen store without any observed tool information flow.” The disposition was NOT CLOSED — blocking verified defect, and it was one of the reasons for the REJECT verdict.

Read as a workflow problem, this is a defective gate. The transition into “accepted” checked that the destination was right: the answer matched the oracle and the lifecycle events were well formed. It did not check that the run had travelled the path the task required: that the evidence for the answer had been obtained through the admitted tools. Looking at the candidate’s lifecycle witness for the Pi adapter shows why:

// examples/pi-harness-lab/src/witnesses.ts (working tree, rejected candidate) — excerpt
export function piWitness(): WitnessExpectation {
  return {
    lifecycle: "pi-v2",
    mode: "milestones",
    transcript: [
      { family: "startup", type: "startup.config" },
      { family: "admission", type: "admission.accepted" },
      { family: "host", type: "session.created" },
      { family: "model", type: "model.request" },
      { family: "model", type: "model.response" },
      { family: "host", type: "pi.agent_settled" },
      { family: "model", type: "agent.answer" },
      { family: "final", type: "attempt.settled" },
      { family: "host", type: "canonical.finalized" },
      { family: "host", type: "session.disposed" },
    ],
  };
}

There is no tool family in the required transcript. The review notes that the recorder checks tool start/result pairs if they occur but “never requires calls.size > 0”. The first blocking item on the review’s correction list is exactly this: “Make tool start/result mandatory event families for every Pi task contract that claims fixture inspection”.

This chapter generalizes the lesson to Project 06, where the stakes are higher. The brief asks for a gate that requires a reproduced failure and a verified passing patch before a run may enter the review state. Both are claims about the path. The failure must have been observed on the base version, and the pass on the patched version, through the harness’s own execution and not through anyone’s report. The chapter then runs the representation question from Chapter 13 to ground. It registers a comparison of a linear workflow, an explicit state machine and a dependency graph on exactly this kind of task.

Evidence status. Draft manuscript. Formal Project 06 (Issue-to-Patch) and the representation study (§14.6) have not run. The educational typed-transition demonstration D14-GATE-01 is implemented and executed (examples/pi-harness-lab/src/gates.ts; test/gates.test.ts, 12/12 pass offline). Project 01 evidence is OBSERVED in REVIEW-02, whose verdict on the candidate is REJECT. The zero-tool witness excerpt below is from the rejected working-tree candidate, quoted to show the defect, not as a recommended pattern. SWE-bench’s evaluation definition is DOCUMENTED via R05. The formal arm comparison and live-model phase are PROPOSED and remain EXPERIMENT PENDING.

14.1 Endpoint gates and path gates

A transition gate is a condition that must hold before a workflow changes state (Chapter 13). Gates come in two kinds, and P01R-02 is what happens when only the first kind exists.

An endpoint gate checks a property of the artifact at the moment of transition: the answer is correct, the tests pass, the file is well formed. Endpoint gates are necessary. They are also satisfiable by artifacts that did not come from the work. A correct answer can be pre-authored, and a passing test suite can pass because the bug was never exercised.

A path gate checks that the evidence the transition relies on was produced by the required prior transitions, through the harness’s own observation. “The answer cites lines 12–16 of worker, and the trace contains a fixture_read of worker covering 12–16 whose result carried that digest” is a path gate. “A test fails on the base commit” is an endpoint claim. “The harness executed this test on this base commit in the isolated runner, observed this failure signature, and recorded it under this run” is a path gate.

The distinction matters because agents are very good at producing plausible endpoints. A model that “knows” the answer, a test the agent wrote to pass, and a summary that asserts a reproduction all satisfy endpoint gates. Only path gates bind progress to work the harness actually witnessed.

14.2 What makes a gate deterministic, and why that is not enough

Chapter 13 required gates to be decided by host code. A deterministic gate has five properties. Each one comes from a failure earlier in this book.

  1. Computed by host code, not by a model. A model can advise a human at a gate. It cannot be the gate (Chapter 11’s “model as checker”).
  2. Inputs observed or recomputed, never reported. The gate reads the harness’s own records: the journal, raw events, artifact digests and test-runner outputs. It never reads a component’s summary of them. Project 01’s RER-02 history shows why: worker summaries claiming 0.5 model calls and zero bytes were accepted until reconciliation was added, and REVIEW-02 still found replay comparing only evaluation verdicts and not the full recomputed record (RER-02, NOT CLOSED).
  3. Same inputs, same decision, in every context. The gate is one pure function, used identically by live execution, replay and audit. RER-01 arose because live supervision and replay applied different acceptance rules (Chapter 4). REVIEW-02 found that specific divergence corrected.
  4. Fails closed. Missing, malformed or unexpected evidence yields “not satisfied”, with a reason. It never yields a default pass.
  5. Records its decision with evidence references. The gate’s output names the records it relied on, so the decision itself becomes part of the evidence graph (Chapter 4 §4.2; Chapter 8).

All five properties held in the essentials of the P01R-02 path. The witness was host code, deterministic, shared by live execution and replay, and failing closed on what it checked. It was still wrong, because it checked the wrong thing. Determinism makes a gate reproducible, not correct. The content of the predicate, what it demands about the path, is a separate design decision that needs its own adversarial test.

14.3 Reproduction and verification as evidence

What should Project 06’s two gates demand?

The evaluation literature supplies a well-defined starting point. SWE-bench scores a patch by running tests designated FAIL_TO_PASS, which must fail before the fix and pass after it, and PASS_TO_PASS, which must pass both before and after. A missing or non-passing required test fails the instance (R05-EVALUATION.md R05-C01; DOCUMENTED). R05 adds the important qualification that this is a “benchmark operational definition, not universal correctness”. It is a good shape for a gate, not a guarantee that a gated patch is right.

A reproduction record (PROPOSED) for the REPRODUCE → FIX gate contains:

  • the base revision digest, the test identifier, and the test file’s digest;
  • the runner’s execution record: environment identity (Chapter 12’s pinned configuration), argument vector, exit status, and a digest of the captured output;
  • a failure signature, a predicate over the output that ties the failure to the reported bug and not to an unrelated error such as an import failure or a missing fixture;
  • the repetition outcome, k failures out of n runs, because a flaky test that fails once is not a reproduction.

The gate passes when the record exists in the journal, was produced by the harness’s runner under this run (a path condition), the signature matches, and k/n meets the registered threshold.

A verified-patch record for the VERIFY → REVIEW gate contains the patch digest and its base digest (Chapter 6), the same test now passing n/n in the same environment, every PASS_TO_PASS test still passing, and a changed-file set within the admitted scope (Chapter 6 §6.5).

One subtlety turns this from a checklist into engineering. If the agent writes the reproduction test, the gate is checking a test that the agent chose. A test can fail on the base version for the wrong reason, or be trivially satisfiable by a patch that changes nothing important. The signature predicate helps, but it does not close the loop. Three mitigations, all PROPOSED:

  • Revert check. Apply the patch, confirm the pass, revert it, and confirm that the failure returns. This shows the patch is what makes the test pass. It does not show the test is meaningful.
  • Independent test review at the gate. A human, or a separate reviewer under Chapter 16’s rules, examines the reproduction test before FIX.
  • Oracle tests the agent never sees. For a study fixture, sealed FAIL_TO_PASS tests exist outside the agent’s view, as SWE-bench’s do. The agent’s own test gates the workflow, and the sealed tests evaluate the outcome. The two must never be the same tests.

14.4 Typed transitions

A typed transition is a transition whose required input is a value of a specific evidence type, produced by the source state, and whose output is a value of the type the destination state requires. In a TypeScript host, discriminated unions make illegal transitions unrepresentable in host code. The types below are excerpted from the executed demonstration D14-GATE-01 (examples/pi-harness-lab/src/gates.ts), which implements them with pure gate functions over journal-observed evidence — not a Pi API.

// Excerpted from examples/pi-harness-lab/src/gates.ts (D14-GATE-01, executed).
type Digest = string;

interface ReproductionRecord {
  kind: "reproduction";
  taskId: string; baseDigest: Digest; testId: string; testFileDigest: Digest;
  runnerEnv: Digest;            // pinned isolated environment (Ch 12)
  failures: number; runs: number;
  signatureMatched: boolean;    // computed by the gate, not supplied
  journalSeq: number;           // harness-observed execution, not a report
}

interface VerifiedPatchRecord {
  kind: "verified-patch";
  taskId: string; baseDigest: Digest; patchDigest: Digest;
  failToPass: { testId: string; passes: number; runs: number }[];
  passToPass: { testId: string; passes: number; runs: number }[];
  revertReproducesFailure: boolean;
}

type WorkflowState =
  | { s: "INVESTIGATE"; taskId: string; baseDigest: Digest; version: number }
  | { s: "REPRODUCE"; taskId: string; baseDigest: Digest; version: number }
  | { s: "FIX"; taskId: string; baseDigest: Digest; version: number; repro: ReproductionRecord }
  | { s: "VERIFY"; taskId: string; baseDigest: Digest; version: number; repro: ReproductionRecord; patchDigest: Digest; attempt: number }
  | { s: "REVIEW"; taskId: string; baseDigest: Digest; version: number; repro: ReproductionRecord; verified: VerifiedPatchRecord }
  | { s: "UNREPRODUCIBLE"; taskId: string; baseDigest: Digest; version: number; reason: string }
  | { s: "NEEDS_HUMAN"; taskId: string; baseDigest: Digest; version: number; reason: string };

// A gate is a pure function of journal-observed evidence; it never trusts a summary.
export const TRANSITIONS: Record<string, string[]> = {
  INVESTIGATE: ["begin-reproduce", "escalate"],
  REPRODUCE: ["record-reproduction", "declare-unreproducible", "escalate"],
  FIX: ["stage-patch", "escalate"],
  VERIFY: ["record-verification", "escalate"],
  REVIEW: [], UNREPRODUCIBLE: [], NEEDS_HUMAN: [],
};

Twelve offline tests drive this machine through every required case: allowed and verified end-to-end transition to REVIEW (with a separate release-captain approval via the Batch 01 authority gate); illegal source state; missing verification evidence; missing or self-issued approval; task-identity mismatch; stale base digest; conflicting patch rejected after a staged one; failing tests held in VERIFY; an unobserved (reported-but-not-journaled) reproduction refused; and a no-work adversary — a correct-looking artifact with no path — rejected at the gate. Run them with npm --prefix examples/pi-harness-lab test.

The type { s: "REVIEW"; … verified: VerifiedPatchRecord } cannot be constructed in host code without a VerifiedPatchRecord, and the only producer of that record is the verification gate. That is a real guarantee, but a narrow one. It constrains the host’s code paths at compile time. It does nothing about the model, which never sees these types. It does nothing about forged records: a function that fabricates a VerifiedPatchRecord type-checks perfectly. And it does nothing about runtime data that bypasses the types, such as deserialized bundles, which is exactly where REVIEW-02’s replay forgeries lived. Types are a design aid that removes one class of host bug. Path gates over journal evidence, and recomputation in replay, are what remove the others.

14.5 The representation question, made concrete

Chapter 13 separated representation, control policy and execution semantics, and listed hypotheses H-R1 to H-R5 against a null hypothesis. Issue-to-Patch is a good test bed, because it contains each feature that could separate the representations: a retry cycle, independent checks that can run in parallel, a stale base mid-run, and crashes.

Retry cycle (VERIFY fails, back to FIX). A linear workflow expresses this either by restarting the whole sequence or by an ad-hoc loop around two steps. An FSM expresses it directly as VERIFY → FIX with a guard on the attempt counter (Chapter 13 §13.6). A DAG cannot contain the cycle at all. A DAG executor handles retries either inside a node (the node retries internally) or by unrolling, instantiating FIX₂ and VERIFY₂ as new nodes. Unrolling is legitimate and has a side benefit: every attempt becomes a distinct node in the record. But “the workflow” is then a generator of graphs, not a fixed graph.

Independent checks (tests, lint, type-check). A linear workflow runs them in sequence. An FSM either sequences them or needs product states, or orthogonal regions in statechart terms (Chapter 13 §13.4), to express “all three running, any one may fail”. A DAG expresses the fan-out and join naturally:

    flowchart LR
    P[patch staged] --> T[run FAIL_TO_PASS]
    P --> R[run PASS_TO_PASS]
    P --> L[lint and type-check]
    P --> V[revert check]
    T --> J{verified-patch gate}
    R --> J
    L --> J
    V --> J
  

The DAG’s advantage here is real, but it is about concurrency and compactness (H-R1), not about correctness. Run sequentially, the same four checks give the same gate decision, more slowly.

Stale base mid-run. Suppose the base revision changes during VERIFY (Chapter 6). A DAG with an edge from “base” to every check invalidates all of them, together with the reproduction record that cites the old base, and recomputes them (H-R2). An FSM needs an explicit transition, for example VERIFY → REPRODUCE on base change, which someone must remember to write. A linear workflow typically does not notice the change unless a precondition check (Chapter 6) aborts it. The DAG’s advantage depends entirely on the edge being present. A missing dependency edge is the DAG’s characteristic silent failure: stale results marked fresh.

Crash and resume. All three can resume correctly if their execution semantics include a write-ahead journal and settled-only checkpoints (Chapters 9–10). The DAG can additionally skip completed nodes whose inputs have not changed (H-R3). For a sequence of five or six states with a small number of retries, the work saved is small. For a fan-out over many independent items it could be large.

Traceability. All three can link every terminal outcome to its evidence, provided gates record their evidence references (§14.2, property 5). The DAG makes that a single graph traversal (H-R4). The FSM plus journal makes it a join over journal entries. Which is simpler to get right is an empirical, not a theoretical, question.

The pattern across the five cases is the chapter’s tentative thesis, still a hypothesis. Representations differ mainly in how compactly and how safely they express concurrency, invalidation and partial reuse, and they differ hardly at all in correctness when execution semantics and gates are held equal. If that is right, the choice between them is about the shape of the task. Fan-out-heavy tasks with changing inputs favour a dependency graph. Mostly sequential tasks with bounded retries favour a plain FSM. A “graph-first” architecture for every harness would then be over-engineering, and the book should say so.

14.6 Registered study: three representations, one task family

This is the study first registered as a candidate in Chapter 3 §3.10, now specified. It is PROPOSED; EXPERIMENT PENDING. Its design rests on a point made in Chapter 13. The model does not see the transition table; with gates and per-state context held equal, the arms present identical model inputs. That allows the study to run largely offline, with a scripted Pi provider, which removes live-model variance from comparisons that are about host behaviour.

Arms. These are three implementations of the same Issue-to-Patch workflow:

  • L, a linear workflow with ad-hoc retry;
  • S, an explicit FSM (the Chapter 13 §13.6 diagram) with a transition table;
  • D, a dependency-graph executor with unrolled retries and the §14.5 fan-out.

Held constant.

  • Gate functions: byte-identical shared code.
  • Per-state tool surfaces, context projections and budgets.
  • The journal and its durability configuration.
  • The scripted provider scripts, for the offline phase.
  • The isolated test runner (Chapter 12).
  • The oracle, with sealed FAIL_TO_PASS and PASS_TO_PASS tests.

Only the representation and its executor vary.

Fixtures. The fixtures are disposable repositories in which each task exercises at least one separating feature. Some tasks need k fix attempts. Some have four or more independent checks. Some have a base change injected at a registered point. Some have crashes injected at each journal boundary (Chapter 10). Some include a missing-dependency fault: the base-to-check edge is deliberately omitted in arm D, to measure its characteristic failure. A task with none of these features is a control task, where all arms are predicted to tie.

Dependent variables.

  • Correctness: the oracle’s verdict, with false REVIEW entries counted separately.
  • Recovery correctness: after each injected crash, compare the final state with a crash-free reference and count duplicated or skipped work.
  • Staleness handling: whether stale results were ever used by a gate.
  • Traceability: the fraction of terminal outcomes for which an automated query returns a complete evidence chain to sealed-oracle inputs.
  • Implementation complexity: lines of non-test code, number of concepts the developer must define, and the change cost of a registered modification: adding a SECURITY_REVIEW state between VERIFY and REVIEW, specified in advance and implemented in all three.
  • Resources: wall time (where concurrency matters), host CPU and journal size. Tokens, in the live phase only.

Hypotheses and acceptance criteria, frozen before implementation:

ID Prediction Accept if Reject if
R-0 (null) On control and sequential-retry tasks, S ≈ D on correctness and recovery, and S < D on complexity No correctness difference; S smaller D shows a correctness advantage on these tasks
R-1 On fan-out tasks, D < S < L in wall time at equal correctness Ordering holds across fixtures No wall-time difference, or a correctness difference appears
R-2 On base-change tasks, D (with complete edges) never uses stale results; S uses them only where a transition was omitted Zero stale-use for D-complete D-complete stale-uses
R-2f D with the missing edge uses stale results Stale use observed Not observed (the injection is ineffective, so the fixture is invalid)
R-3 All arms with the shared journal recover correctly; D re-executes fewer nodes Zero duplicated effects in all; fewer re-executions in D Any arm duplicates effects. That is an execution-semantics defect, not a representation result
R-4 Traceability is complete in all three arms 100% chains in all Any gap. Locate it, then attribute it to representation or to logging
R-5 The registered modification costs less in S than in L, and S ≈ D Measured change sizes — (descriptive)

The study has known threats, and they are stated here so they are not discovered later:

  • Author bias. The same team implements all three arms, and knows the hypotheses. Mitigations: the modification task is fixed in advance; the implementations are reviewed against a written specification; and an independent implementer is used for at least one arm where possible.
  • Fixture selection. Fixtures can be chosen to favour a representation. Mitigation: fixtures are registered with their feature labels before any arm runs, and the control tasks are kept.
  • Lines of code is a crude measure of complexity. It is reported together with concept counts and change cost, never alone.

A live phase, with real models in the per-state episodes, follows only if the offline phase shows differences worth testing under model variance. Even then it is predicted to show no representation effect on model behaviour. That prediction is itself testable: a representation effect on model outputs would mean that the representation leaked into the context.

14.7 Project 06 checkpoint: Issue-to-Patch

Blueprint requirement: investigate, reproduce, fix, test and prepare a patch. The new mechanisms are typed workflow states, bounded planning and retries, and an explicit human gate. The verification is to show a reproducible test failure becoming a verified passing patch, and never to merge or push without authority.

Status: not started. The dependency chain is long, and the chapter should not hide it:

  • Isolated test execution, because running a repository’s tests runs its code (Chapter 12 §12.4; Project 05).
  • Guarded edits (Chapter 6; Project 02).
  • A journal with settled-only checkpoints (Chapters 9–10; Project 04).
  • An accepted evidence pipeline (Project 01, REJECT as of REVIEW-02).

The human gate at REVIEW is an approval in Chapter 12’s sense, bound to the exact patch digest and base. The “never merge or push without authority” requirement means that no tool in any state can push. Merging is outside the workflow entirely, and is a separate effect requiring its own authority.

14.8 Failure modes

  • Endpoint-only gate. The artifact is right and the path is unverified (P01R-02, OBSERVED). Defence: path conditions over journal evidence, plus adversarial no-work tests.
  • Reported evidence. The gate reads a summary (RER-02 history). Defence: recompute from raw records.
  • Divergent gate functions. Live and replay decide differently (RER-01 history). Defence: one pure gate function, shared everywhere.
  • Agent-authored oracle. The reproduction test both gates the workflow and scores the outcome. Defence: sealed oracle tests the agent never sees, a revert check, and independent test review.
  • Flaky reproduction. A single failure is accepted. Defence: a k/n threshold and a failure signature.
  • Types mistaken for security. Discriminated unions are treated as preventing forged records. Defence: types constrain host code paths only; path gates and recomputation are still required.
  • Missing dependency edge. A DAG marks stale work fresh. Defence: edges derived from declared inputs, plus a missing-edge fault test (R-2f).
  • No exit. The gate can only pass or loop. Defence: UNREPRODUCIBLE and NEEDS_HUMAN (Chapter 13).

14.9 What you can build and test now

D14-GATE-01 already implements the core loop: the §14.4 types, both gates as pure functions over journal-observed evidence, and a no-work adversary test (a correct-looking artifact with no path, rejected at the gate — the P01R-02 pattern). Extend it with the §14.6 fixture registry (task, separating features, injected faults) before writing any of the three representation executors (linear, FSM, dependency graph).

14.10 What remains unverified

  • Formal Project 06 acceptance and the §14.6 representation comparison (L vs S vs D with shared gates, journal, tools and oracle). D14-GATE-01 demonstrates one gated workflow, not the three-way comparison.
  • The tentative thesis in §14.5. It is a hypothesis with registered falsifiers (R-0 to R-5).
  • Whether Pi episodes per state behave as assumed under switched tool surfaces and host-projected context (Chapter 13 §13.7; TEST NOT RUN).
  • Project 01’s zero-tool gate defect is open as of REVIEW-02. The correction belongs to the implementation stream, and this chapter’s description must be updated once a corrected candidate is independently re-reviewed.

EXPERIMENT PENDING. The formal Project 06 study and representation comparison have not run; D14-GATE-01 is an executed educational demonstration of the gate mechanism, not those studies.

A gate is a small evaluator placed at a transition. Chapters 13 and 14 have treated it as a single predicate, but most real judgments about a run are not single predicates. Some properties a deterministic check can settle. Some need a model’s reading, some need a human’s, and the three can disagree. Chapter 15 turns from gates to evaluation in general, and asks how to keep outcome, process and evidence judgments separate, and what to do when evaluators disagree.

Previous: Chapter 13: Plans, Workflows, and the Agent Loop.

Next: Chapter 15: Evaluation: Outcome, Process, and Evidence.