Skip to main content

Chapter 5. Outcome, Trajectory, and Process Metrics

Outcome Evaluation with Deterministic Graders

Juniper tells a customer, “Your refund is complete.” The sentence sounds convincing, but the refund tool was never called and no transaction occurred. Although a grader that reads only the final message may pass the run, a check against the transaction state tells a different story.

A deterministic grader applies explicit, repeatable rules to evidence such as final state, tool calls, structured output, or constraints, and it is often cheaper and easier to audit than a model judge. Yet repeatability does not make the rule correct: a grader can encode the wrong policy, miss a side effect, or reward a shortcut. The team must therefore connect each claim to evidence and test whether the grader recognizes both genuine success and plausible failures.

That work does not end with the final state, because a refund may have happened even though Juniper skipped a required eligibility check. The second half of this chapter follows the observable path to the outcome, showing what a trace can establish and where interpretation remains uncertain.

After this chapter you will be able to:

  • distinguish outcome checks from trajectory checks and choose the right evidence;
  • validate structured results and tool calls against explicit contracts;
  • award interpretable partial credit without letting a safety failure average away;
  • identify and reduce reward hacking caused by an incomplete grader;
  • test graders with positive, negative, boundary, and mutation cases.

Case study. Harbor & Pine is fictional. Its support agent handles a fictional refund request against an in-memory order system. The example uses no customer data, payment service, external model, or live tool.

5.1 State-based and test-based grading

The first decision is where to look for evidence. Juniper’s message, its tool call, and the order state each answer a different question; none is a complete substitute for the others.

Evidence What it answers Example check Common blind spot
Final response Did the agent communicate an acceptable result? Correct status and order ID are present The claim may not match what happened
Tool-call trace Did the agent take an allowed, well-formed action? One refund call targets the requested order A valid call can fail or affect the wrong state
Final state Did the system reach the requested outcome? The target order is refunded A harmful side effect elsewhere can go unnoticed
Invariants / tests Were important constraints preserved? No other order was refunded An incomplete invariant set leaves gaps

State-based grading is especially useful when several safe trajectories can reach the same goal. An agent might ask a clarifying question before refunding, or look up the order first, so insisting on one exact tool sequence would reject a valid solution. Add trajectory checks when process is part of the requirement: verify shipping status before changing an address, stay within an action limit, or obtain approval before an irreversible operation.

SWE-bench uses executable tests to check whether a proposed change resolves an issue; τ-bench evaluates agent behavior in simulated domains with tools and user interaction [1], [2]. In either setting, make success observable and connect the check to the task. A passing test suite establishes safety or goal completion only when its tests cover those claims.

These evidence surfaces become useful only when the team specifies what each must show. Before inspecting candidate outputs, the grading contract should answer:

  1. Target outcome: Which state or artifact must exist at completion?
  2. Scope: Which entity, user, file, or order is the target?
  3. Required evidence: Which source of state is authoritative?
  4. Invariants: What must not change?
  5. Process constraints: Which actions, approvals, or limits are mandatory?
  6. Completion rule: Which conditions are hard gates, and which can earn partial credit?

For the refund example, refund_status == "complete" somewhere in the database is not enough: the requested order must be refunded, unrelated orders must remain unchanged, and any required transaction record must refer to that same order. The check must therefore account for identity and scope along with status.

State snapshots work when they are authoritative and isolated, but if a snapshot can be stale, compare before and after or query the source of truth after the run. Even then, a final state alone may not establish that the agent caused the change, particularly if the target already had that state or another actor could modify it. Missing or malformed evidence must be surfaced rather than converted into a pass; depending on the contract, it may mean a failed gate or an explicitly inconclusive result.

5.2 Structured output and function-call validation

The final state is not the only evidence with a contract. When a system promises machine-readable output, a JSON object can parse and still be invalid: required fields may be missing, types may be wrong, values unsupported, or the entity incorrect. JSON Schema provides a standard language for describing JSON structure and constraints [3].

Apply the same discipline to tool calls by checking the tool name, argument shape, types, required values, and policy authorization separately. Schema validity asks whether the call is shaped correctly, whereas policy validity asks whether it is allowed here. A well-formed refund call against the wrong order still fails.

For a small fictional contract, the lab’s standard-library checks make the logic visible. Here the candidate supplies a response, a call, and a final snapshot; the grader does not contact a payment system:

from bookkit.graders import EvaluationCase, grade_refund_case

case = EvaluationCase(
    target_order_id="HP-8101",
    protected_order_ids=("HP-8102",),
)
candidate = {
    "output": {"status": "completed", "order_id": "HP-8101"},
    "tool_calls": [
        {"name": "issue_refund", "arguments": {"order_id": "HP-8101"}}
    ],
    "final_state": {
        "orders": {
            "HP-8101": {"refunded": True},
            "HP-8102": {"refunded": False},
        }
    },
    "safety_violations": [],
}
report = grade_refund_case(case, candidate)
print(report)

The lab’s returned report is examined in the hands-on section. Its contract requires exactly one refund call, so it is narrower than the general state-based approach above: other safe paths would be rejected unless the contract and grader changed. For complex or versioned contracts, use a maintained schema validator and a separate authorization check for tool policy. Reject unexpected fields when the contract is closed. If forward compatibility requires extensions, define how extensions work; silently accepting arbitrary keys leaves the contract unclear.

Serialization details are also part of the interface, so specify whether missing differs from null, how to represent numbers and dates, whether identifiers are case-sensitive, and which equivalent values are accepted. Otherwise, permissive string matching can turn malformed output into a pass.

5.3 Partial credit and multi-criteria scoring

A run can satisfy some of those checks while failing others. Binary pass/fail is useful for release gates, but it can hide where an agent is improving, whereas a multi-criteria score can show progress across communication, action, outcome, and side-effect dimensions. Its weights should reflect product priorities, not convenience.

For the lab, the score is:

Criterion Weight Evidence
Structured response is valid 10 Required keys, permitted status, and a non-empty order ID
Completion report matches target 10 Completed status and requested order ID
Tool-call schema is valid 10 Allowed tool name and required argument shape
Tool call targets the requested order 15 Exactly one permitted call with the case target ID
Requested state change occurred 35 Target order is marked refunded
No collateral or policy side effect 20 Protected orders remain unchanged; no safety violation is reported

Use the score to diagnose behavior, not to make the release decision by itself: a candidate can earn points for a valid response and still fail to refund the target. The lab therefore requires all six criteria to pass; a high average cannot make up for a missing outcome or collateral refund. In production, agree on hard gates with policy and risk owners, and show each criterion next to any aggregate.

Avoid double-counting correlated checks. “Tool call says refund” and “response says refund” are not independent evidence that the transaction succeeded. Use authoritative state to establish the outcome; use the response and trace to diagnose how the run got there.

5.4 Reward hacking and grader exploits

Even a detailed scorecard can be gamed if its checks do not capture what the task really requires. Specification gaming happens when a system satisfies the literal grading rule but misses its purpose. For example, a keyword grader could reward “refund completed” even though no refund happened, while a state grader that checks only whether some order was refunded could pass a refund to the wrong customer. No malicious intent is needed; ordinary shortcuts can reveal an underspecified metric. These are familiar forms of reward hacking and specification gaming in AI systems [4], [5].

Treat each grader as a program that could be gamed:

  • List plausible shortcuts that pass the rule but violate the task intent.
  • Check scope and identity at every join: target user, order, file, or account.
  • Include negative side-effect checks, not only positive success checks.
  • Ensure all required evidence comes from the right source and is tied to the same run.
  • Keep some cases or adversarial variants out of the iteration set.
  • Inspect traces and state diffs for suspiciously high scores or repeated patterns.

Development needs an explicit grading contract so the team can debug failures. Held-out cases and labels need protection from tuning, but the metric and its limitations should still be documented. Secrecy cannot repair a flawed grader.

5.5 Testing your graders

Anticipating exploits is only the beginning: the team also needs evidence that its checks catch them. Agent tests ask whether a candidate succeeds; grader tests ask whether the evaluator correctly recognizes success and failure.

Build a compact grader test matrix:

Test type Example Expected grader behavior
Positive control Correct target refunded; protected order unchanged Pass
Negative control Agent claims success; no tool call or state change Fail
Wrong-target case Another order is refunded instead Fail and report collateral effect
Boundary case Required value is missing, null, empty, or wrong-typed Fail schema validation
Partial case Correct call, but final state did not change Show partial score; do not pass
Valid alternative Different safe path reaches the permitted target state Pass if all required invariants and constraints hold
Mutation test Change the grader to ignore target ID or collateral state At least one test must fail

Mutation testing is useful here: deliberately weaken a condition and check whether the suite catches the change. If replacing HP-8101 with HP-8102 still passes every test, the tests have not shown that the evaluator checks target identity. Add a negative case that would fail on the wrong order.

Review surprising failures as well as surprising passes: a grader can reject a safe solution because it expects one tool sequence, one wording, or an outdated policy version. Adjudicate the trace and authoritative state with the domain owner; if the alternate behavior is valid, update the task contract and grader tests. If it violates an invariant, document why it fails. In either case, preserve the original result and version the correction so an evaluator defect is not mistaken for an agent regression.

For a larger suite, review cases near thresholds and break down disagreement by task family, output type, tool, and policy. A deterministic check can still encode the wrong expected state or policy mapping. Validate those assumptions with domain experts and retain the provenance of cases, policies, and grader versions [1], [2].

Trajectory and Process Evaluation

Now consider a different run: Juniper tells a Harbor & Pine customer that the refund is complete, and the order state confirms it. This time, however, the trace shows that Juniper skipped the required eligibility check. The same final state could follow a safe lookup-and-refund sequence—or an action on the wrong order followed by a compensating change. Although a final-state grader records success, the operations team still needs evidence that the process was trustworthy.

An agent trajectory is the ordered record of behavior in an environment: requests, tool calls, observations, retries, state changes, and the final response. Trajectory evaluation adds evidence that outcome evaluation cannot provide, potentially surfacing unsafe or wasteful steps hidden by a correct final answer. That does not justify requiring one exact path or treating private reasoning transcripts as ground truth; instead, evaluate the externally observable behavior that matters to the task.

After this chapter you will be able to:

  • distinguish task outcome from the quality and safety of the process that produced it;
  • define step-level checks for tool choice, arguments, ordering, and side effects;
  • detect repeated actions, dead ends, and error recovery without assuming every retry is bad;
  • choose between exact trajectory matching, policy constraints, and rubric-based review;
  • localize the first observable failure while separating evidence from root-cause hypotheses;
  • design process scores that support diagnosis without hiding outcome failures or rewarding needless steps.

Case study. Harbor & Pine and Juniper are fictional. All traces and state changes in this chapter are synthetic teaching examples. They do not represent a production customer-support system or real agent behavior.

Connections. The evaluation harnesses chapter introduces agent harnesses, and the first half of this chapter introduced deterministic outcome graders. Chapters 7 and 6 develop model judges and human annotation, which can complement the observable process checks discussed here.

5.6 Why outcome-only grading is not enough

Outcome evaluation asks what happened; process evaluation asks how it happened. Neither question makes the other unnecessary when an agent can change external state, handle sensitive information, or operate under policy constraints. The distinction gives the team four possible interpretations:

Final outcome Process Interpretation
Correct Acceptable Desired behavior for this task
Correct Unacceptable Outcome succeeded, but a policy, safety, or reliability constraint was violated
Incorrect Acceptable The process may be compliant but insufficient; investigate capability, tools, or task ambiguity
Incorrect Unacceptable Multiple failures may be present; use the trace to localize them

For Juniper, “the refund is complete” does not settle the evaluation. Check that the request targeted the right order, required eligibility was checked, no protected order changed, and the final response matches environment state. At the same time, keep the outcome check, because a compliant sequence can still leave the task unfinished.

Interactive benchmarks make this distinction concrete. AgentBench evaluates agents across multiple interactive environments and reports weaknesses that appear over multi-step decisions [6]. \(\tau\)-bench combines simulated users, tools, and domain policies, then compares the ending database state with an annotated goal state. Its repeated trials also show why one successful run cannot establish reliability [2]. Preserve both the trace and the authoritative outcome.

The useful process metrics depend on the decision they will support. A team might need to:

  • block a release if an agent can take an irreversible action without authorization;
  • distinguish a tool failure from a bad response to the user;
  • reduce avoidable API calls without penalizing a legitimate recovery;
  • route traces with repeated failures to an engineering review queue.

Give steps the weight their consequences warrant: a harmless extra read and an unauthorized write are both one tool call, but they are not equivalent. Set task-specific safety constraints first, then use softer efficiency metrics to compare systems that satisfy them.

5.7 Step-level correctness and tool-call accuracy

The table gives us an episode-level view, but understanding why a process is acceptable or not requires examining individual actions. A tool call is correct when its name, arguments, timing, and effect meet the task contract. Syntax validation is necessary, but issue_refund(order_id="HP-1005") can be well formed and still target the wrong order.

For each action, define the relevant checks:

  1. Interface: Is the tool permitted, and do arguments match its schema?
  2. Target: Does the action refer to the entity in the user’s request?
  3. Precondition: Was the required evidence or authorization obtained first?
  4. Effect: Did the environment change as intended, with no collateral change?
  5. Communication: Does the agent’s final claim match the observed state?

A normalized event record should make these checks possible without relying on a transcript alone:

event = {
    "step_id": "step-2",
    "tool": "issue_refund",
    "arguments": {"order_id": "HP-1004"},
    "outcome": "success",
    "timestamp_ms": 1840,
    "trace_id": "episode-17",
}

In production, record the tool and policy versions, call and parent identifiers, environment state references, and a privacy-conscious account of the observation that informed the action. Give each attempt a distinct identifier while retaining a stable logical-operation or parent identifier to link retries. Model text alone may omit the tool result. Retaining every raw prompt indefinitely may capture more sensitive information than the evaluation needs.

Put the denominator next to every rate. “Correct tool selection,” for example, might be correct selections divided by tool-call steps, while “correct argument set” might be calls with all required arguments divided by valid calls. One “tool accuracy” number can hide missing, extra, malformed, or misdirected calls. Also separate per-step rates from per-episode pass rates: ten mostly correct calls do not make an episode safe if the eleventh changes the wrong account.

When possible, use the environment as the authority for state changes. Compare pre- and post-state, check invariants for protected entities, and record failed and retried calls. Neither the agent’s text nor an accepted API request alone proves success.

5.8 Planning quality, loops, and dead ends

Correct individual calls do not necessarily add up to an effective plan: the agent may repeat an unproductive lookup or run out of time before reaching the goal. Plans become useful evaluation targets when they name observable milestones: identify the target, inspect eligibility, take the authorized action, verify the result, and report it. A rubric becomes unreliable, however, when it assumes access to a complete hidden chain of thought. Private reasoning text is neither necessary nor dependable ground truth; evaluate the actions, observations, and state transitions the system exposes.

Measure planning through observable signals:

  • Prerequisite order: did the agent obtain required evidence before acting?
  • Progress: did actions move the task toward a defined goal or resolve a blocker?
  • Efficiency: how many tool calls, retries, tokens, or elapsed seconds were used?
  • Termination: did the agent complete, safely abstain, or stop at a bounded limit?
  • Loop indicators: did it repeat a materially identical action without new information?

A repeated action deserves inspection, but is not automatically a failure. A retry after a transient network error may be appropriate, whereas repeating an unchanged query after the same validation error may be a dead end. Record why the agent retried and whether its input, the environment, or policy-relevant evidence changed, and validate advanced detectors for recurring action-and-state patterns against reviewed traces before using them in a release gate.

Set explicit limits for runaway behavior: maximum tool calls, time or token budgets, and rules for asking the user or escalating. Report a budget overrun separately from task quality. A hard cap can prevent harm and still leave the task unfinished; record both outcomes.

5.9 Error recovery and self-correction

Not every detour is a planning failure, because interactive systems produce errors: a tool may time out, return stale data, reject an argument, or expose a bad assumption. The important question is whether the agent noticed, responded safely, and recovered—or stopped when it could not.

An operational recovery record links a failed step to the later action that addressed it. Useful metrics include the share of recoverable errors followed by successful recovery, repeated failed attempts, and the final outcome. Keep the error type and response visible, since retrying a payment can duplicate it, whereas retrying an idempotent read does not carry the same risk.

The lab’s recovery_of field explicitly links events. It does not infer that any later success fixed the earlier error, but neither does the link prove that the claimed repair actually resolved it. In real systems, validate recovery with environment events such as transaction IDs, idempotency keys, and state diffs. When recovery cannot be established, the agent needs a safe way to stop: abstain, ask for clarification, or hand off.

An agent saying it is uncertain is not, by itself, self-correction: it must correct the action or accurately explain what remains unresolved. To assess that response, compare the original error, later action, resulting state, and final statement.

5.10 Trajectory matching vs. rubric-based judging

The recovery example also shows why the evaluator must know which variations are legitimate. Exact trajectory matching is useful when the environment is deterministic and the task requires a canonical path, such as a narrow protocol conformance test, but it breaks down when multiple safe plans reach the same goal. An agent might check a cached authorization record instead of calling a lookup tool, or use a different valid search sequence; exact matching would penalize either choice.

Use the least restrictive evaluation that still captures the requirement:

  • Exact match for strict protocol steps or fixed-output simulations.
  • Required actions and ordering constraints for tasks with a mandatory safety procedure but flexible intermediate steps.
  • Invariants and state-based checks for tasks where any safe route to the goal is acceptable.
  • Rubrics and expert review for judgments such as whether an explanation is adequate or a handoff is appropriate.

Longest-common-subsequence overlap and other similarity metrics can cluster traces or compare a candidate with a reference. They measure similarity, not quality; use them diagnostically, without treating every deviation as an error. SWE-bench checks whether patches resolve repository issues through tests and task outcomes, so a valid patch need not match a reference diff [1]. Human review and calibrated model judges can assess qualitative process dimensions, with the validation and uncertainty controls described in Chapters 6–7 [7], [8].

List accepted alternatives in the evaluation specification. If the rubric requires an order lookup before refunding, define equivalent authoritative eligibility checks and prohibited actions. Clarify underspecified requirements before labeling a different trajectory an agent defect.

5.11 Error attribution: finding the failing step

Once a trace fails a process check, the next task is diagnosis. Although a trace can locate a failure, it rarely proves its root cause: a wrong refund might come from the model’s decision, a stale observation, a tool bug, a harness race, a policy mismatch, or an evaluation fixture with the wrong expected state.

For each failing episode:

  1. Confirm the outcome against the authoritative environment state.
  2. Find the earliest observable event that violates a declared contract.
  3. Inspect the preceding observation and the tool’s actual response.
  4. Re-run the same task with deterministic replay where possible.
  5. Change one factor—model, tool, prompt, or environment—to test a causal hypothesis.
  6. Record the evidence and uncertainty separately from the proposed cause.

An evaluator can report, “The first observed violation was an issue_refund call before the required eligibility check.” It should not conclude “the model misunderstood the policy” unless evidence rules out a missing or misleading observation. Replay and controlled interventions help distinguish correlation from cause. With nondeterministic models and environments, that may take repeated runs.

Include evaluation defects in the failure taxonomy. A missing trace span, incorrect event ordering, stale fixture, or overly narrow path rule can produce a plausible but false diagnosis. Trace completeness and evaluator version are part of the measurement system.

5.12 Process rewards and credit assignment

The same intermediate evidence used for diagnosis can also provide feedback during development or training. Outcome supervision gives feedback on the final result, whereas process supervision gives it on intermediate steps. In mathematical reasoning, Lightman et al. compared these approaches and released PRM800K, a dataset of step-level human feedback [9]. Their work shows step-level feedback can help in its setting, but it does not establish that a learned process reward will improve every tool-using agent or production workflow.

For agent evaluation, begin with a scorecard, not an unexplained composite:

Dimension Example evidence Typical use
Task outcome Authoritative final state Completion and usefulness
Policy compliance Required checks and forbidden actions Safety gate
Tool correctness Schema, target, result, and side effects Integration diagnosis
Recovery Error-linked successful repair or safe handoff Resilience
Efficiency Calls, latency, and cost Optimization after safety

If you use a weighted process score, publish its dimensions, weights, hard gates, and trade-offs. An efficiency score must not offset an unauthorized state change. Keep the raw dimensions so teams can investigate shifts and catch reward hacking—for example, unnecessary calls earning “verification” points.

Credit assignment is hard when an episode’s outcome arrives late. Labeling every earlier action “good” because the task eventually succeeded can reward luck or unsafe behavior, while labeling every step “bad” after a failure can penalize correct work interrupted by a tool outage. Use step labels only for claims reviewers can judge from available evidence; mark uncertain cases honestly and adjudicate disagreements under a versioned rubric. Process rewards have measurement error too, and they are not ground truth by definition.

Chapter summary

Outcome evaluation

The first half of the chapter showed how an evaluator connects a completion claim to independent checks:

  • Grade observable outcomes and constraints, not only a fluent completion message.
  • Use state checks when multiple safe trajectories are acceptable; add trace checks where process constraints matter.
  • Keep structure, authorization, correct target, outcome, and side effects as distinct checks.
  • Partial-credit scores are diagnostic; explicit hard gates prevent serious failures from averaging away.
  • A deterministic grader can still encode a wrong or incomplete specification.
  • Test graders with positive, negative, wrong-target, malformed, partial, and mutation cases.

For product managers. Ask the team: What authoritative evidence proves the user’s goal was completed? Which mistakes are non-compensable hard failures? Can the grader detect an action on the wrong account or record? What positive and negative controls test the grader itself? Who owns updates when policy changes?

Trajectory and process evaluation

The second half added the evidence needed to understand how the result was reached:

  • Evaluate the authoritative outcome and the process independently; a successful ending can conceal an unsafe path.
  • Define step checks around tool contract, target, preconditions, state effects, and final communication.
  • Treat repeated calls, long traces, and retries as diagnostic signals that need task context.
  • Link errors to explicit recovery evidence, and preserve a safe stop or handoff option.
  • Use exact trajectory matching only for tasks that truly require one path; otherwise prefer policy constraints, invariants, and rubrics.
  • Report the earliest observable failure separately from the hypothesized root cause.
  • Keep process score dimensions and safety gates visible; do not let an aggregate hide a harmful action.

For product managers. Ask which actions must never happen, which prerequisites are mandatory, and what state proves success. Ask the team to show examples where the final answer is right but the path is unacceptable, and where a different path is still valid. Agree on a safe-stop policy, release gates, and how engineering will distinguish an agent error from a tool or evaluator failure.

Hands-on labs (Python)

Lab 1: Outcome evaluation

The offline grader is code/bookkit/graders.py; the complete runnable scenarios are in code/ch07/lab_deterministic_graders.py. It uses fictional order IDs and local dictionaries only. Run these excerpts in the lab’s Python context, with code on the module search path; the standalone script defines case, successful_candidate, and wrong_target_candidate.

This teaching grader trusts the supplied snapshot and safety-violation list. It does not retrieve authoritative state, compare initial and final states, verify policy authorization, or inspect unlisted orders; a missing safety_violations field is treated as an empty list. A production evaluator must obtain and validate its own evidence, including missing-evidence handling, before treating the same checks as a safety gate.

The successful candidate satisfies the response, tool, state, and side-effect checks:

report = grade_refund_case(case, successful_candidate)
print(report)
{'score': 100, 'passed': True, 'criteria': {'structured_output_valid': True, 'completion_report_matches_target': True, 'tool_call_schema_valid': True, 'correct_tool_call': True, 'target_state_reached': True, 'no_collateral_effect': True}, 'hard_failures': []}

Now consider a fluent but deceptive response: it says the refund is done, but the only evidence is the final message.

deceptive_candidate = {
    "output": {"status": "completed", "order_id": "HP-8101"},
    "tool_calls": [],
    "final_state": {"orders": {"HP-8101": {"refunded": False},
                               "HP-8102": {"refunded": False}}},
    "safety_violations": [],
}
report = grade_refund_case(case, deceptive_candidate)
print("naive message check:", "refund" in "Your refund is complete.".lower())
print(report)
naive message check: True
{'score': 40, 'passed': False, 'criteria': {'structured_output_valid': True, 'completion_report_matches_target': True, 'tool_call_schema_valid': False, 'correct_tool_call': False, 'target_state_reached': False, 'no_collateral_effect': True}, 'hard_failures': ['tool-call schema invalid', 'tool call did not target requested order', 'target state not reached']}

The criterion results show where the run failed, and the hard gate blocks the false completion. In the next case, the call and side effect target a protected order, so a valid call shape does not make that run successful:

wrong_target = wrong_target_candidate(case)
print(grade_refund_case(case, wrong_target))
{'score': 30, 'passed': False, 'criteria': {'structured_output_valid': True, 'completion_report_matches_target': True, 'tool_call_schema_valid': True, 'correct_tool_call': False, 'target_state_reached': False, 'no_collateral_effect': False}, 'hard_failures': ['tool call did not target requested order', 'target state not reached', 'collateral state changed']}

Finally, run the grader’s own tests. The tests include positive and negative examples, malformed output, partial completion, wrong-target side effects, and a mutation that removes the identity check. The elapsed time varies by machine, so the excerpt prints the stable test summary rather than the timing:

import subprocess
import sys
import re

result = subprocess.run(
    [sys.executable, "-m", "unittest", "discover", "-s", r"code\tests",
     "-p", "test_graders.py", "-v"],
    check=True,
    capture_output=True,
    text=True,
)
summary = [line for line in result.stderr.splitlines()
           if line.startswith("Ran ") or line == "OK"]
print([re.sub(r"in [\d.]+s", "in ...s", line) for line in summary])
['Ran 7 tests in ...s', 'OK']

The ... replaces the variable elapsed time printed by the test runner. This suite protects a small contract, not every product policy. Add cases when the task, tool schema, or policy changes, and version the grader alongside the dataset it evaluates.

Lab 2: Trajectory and process evaluation

Run python code\ch10\lab_trajectory.py. The lab uses synthetic Harbor & Pine events and makes no provider calls, while its evaluator checks required actions in order, disallowed tools, forbidden actions, repeated calls, an explicit recovery link, and a bounded step budget. It reports outcome and process dimensions separately. The following excerpt also needs code and code\ch10 on the Python module search path.

from bookkit.trajectory import assess_trajectory, trajectory_similarity
from trajectory_fixtures import GOOD_TRACE, SHORTCUT_TRACE

requirements = [
    {"tool": "lookup_order", "arguments": {"order_id": "HP-1004"}},
    {"tool": "issue_refund", "arguments": {"order_id": "HP-1004"}},
]
common = {
    "allowed_tools": {"lookup_order", "issue_refund"},
    "required_actions": requirements,
    "forbidden_actions": [
        {"tool": "issue_refund", "arguments": {"order_id": "HP-1005"}}
    ],
    "max_steps": 4,
}

good = assess_trajectory(GOOD_TRACE, goal_met=True, **common)
shortcut = assess_trajectory(SHORTCUT_TRACE, goal_met=True, **common)
print("good:", good["outcome_met"], good["process_pass"], good["first_violation"])
print("shortcut:", shortcut["outcome_met"], shortcut["process_pass"], shortcut["first_violation"])
print("path similarity:", trajectory_similarity(GOOD_TRACE, SHORTCUT_TRACE))
good: True True None
shortcut: True False {'step_id': None, 'reason': 'missing_required_action', 'phase': 'episode_end'}
path similarity: {'exact_match': False, 'matched_actions': 1, 'precision': 1.0, 'recall': 0.5}

Both examples are supplied with goal_met=True; the evaluator does not independently inspect an order state. Under the fictional contract, the shortcut violates the process requirement by skipping the required lookup, whereas the similarity score describes the paths and nothing more. The script’s recovery example shows a later successful call explicitly referencing an earlier tool error.

The toy required-action check matches tool names and argument patterns in order, even if a matched event reports an error. It also reports an unmatched requirement at episode end rather than necessarily identifying the first unsafe action. Consequently, a recorded lookup alone does not establish a successful eligibility check, and the recovery link is not proof of repair. A real release gate must validate outcomes, observations, ordering, and trace completeness against the actual policy and authoritative state.

Exercises

Use these exercises to separate the evidence that a task succeeded from the evidence that it was performed acceptably.

Outcome evaluation

  1. (Conceptual) For an agent that books travel, name one outcome check and one trajectory constraint that should be evaluated separately.
  2. (Conceptual) Which refund-example criteria should be hard gates for your product, and who should approve that decision?
  3. (Hands-on) Add a currency field to the structured result. Define accepted values and tests for missing, invalid, and valid currency codes.
  4. (Hands-on) Add a second protected order, then mutate the candidate to refund it. Verify the grader fails even when the requested order is also refunded.
  5. (Hands-on) Add a tool-call limit and a rule requiring an order lookup before refunding. Keep schema validity separate from policy compliance.
  6. (Discussion) A candidate scores 95/100 but violates a privacy constraint. Explain why an average score should not determine release readiness.

Trajectory and process evaluation

  1. Conceptual. Give an example of a correct final state reached through an unacceptable process. Which part should be a hard gate, and which part should remain a diagnostic metric?
  2. Design. Write required-action and forbidden-action patterns for an agent that may issue a refund only after checking eligibility and may never modify a different order.
  3. Hands-on. Add a repeated lookup_order call to SHORTCUT_TRACE. Confirm that it is reported as a repeat, then decide whether your task specification should treat the repeat as a failure.
  4. Hands-on. Add an error event and a later successful event with recovery_of. Test that an unrelated success does not count as recovery.
  5. Evaluation review. Propose two valid routes to the same task outcome. Explain why exact trajectory matching would be misleading and what invariant or rubric would work better.
  6. Discussion. A process reward improves offline scores but increases average tool calls in production. What evidence would you collect before adopting it?

Further reading

The following sources extend the chapter’s discussion of executable checks, interactive trajectories, and process supervision:

Outcome evaluation

  • Jimenez et al., SWE-bench: an example of executable tests used to evaluate issue resolution [1].
  • Yao et al., τ-bench: interactive tool-agent-user tasks and outcome-oriented evaluation [2].
  • Wright et al., JSON Schema 2020-12 specification [3].
  • Amodei et al., Concrete Problems in AI Safety, and Krakovna et al., Specification gaming: the flip side of AI ingenuity [4], [5].

Trajectory and process evaluation

  • Liu et al., AgentBench, for interactive evaluation across multiple environments and analysis of agent failure modes [6].
  • Yao et al., \(\tau\)-bench, for policy-aware tool-agent-user interactions and repeated-run reliability [2].
  • Lightman et al., Let’s Verify Step by Step, for a comparison of outcome and process supervision in mathematical reasoning and the PRM800K step-label dataset [9].
  • Yao et al., ReAct, for a foundational pattern that interleaves reasoning and action in language-model agents [10].
  • Jimenez et al., SWE-bench, for outcome-oriented evaluation of software engineering agents against real repository issues [1].
[1]
C. E. Jimenez, J. Yang, A. Wettig, et al., “SWE-bench: Can language models resolve real-world GitHub issues?” in International conference on learning representations (ICLR), 2024. Available: https://openreview.net/forum?id=VTF8yNQM66
[2]
S. Yao, N. Shinn, P. Razavi, and K. Narasimhan, “\(\tau\)-bench: A benchmark for tool-agent-user interaction in real-world domains.” 2024. Available: https://arxiv.org/abs/2406.12045
[3]
A. Wright, H. Andrews, B. Hutton, and G. Dennis, “JSON Schema: A media type for describing JSON documents.” Accessed: Nov. 11, 2026. [Online]. Available: https://json-schema.org/draft/2020-12/json-schema-core.html
[4]
D. Amodei, C. Olah, J. Steinhardt, P. Christiano, J. Schulman, and D. Mané, “Concrete problems in AI safety.” 2016. Available: https://arxiv.org/abs/1606.06565
[5]
V. Krakovna et al., “Specification gaming: The flip side of AI ingenuity.” Accessed: Nov. 11, 2026. [Online]. Available: https://www.deepmind.com/publications/specification-gaming-the-flip-side-of-ai-ingenuity
[6]
X. Liu, H. Yu, H. Zhang, et al., “AgentBench: Evaluating LLMs as agents,” in International conference on learning representations (ICLR), 2024. Available: https://arxiv.org/abs/2308.03688
[7]
L. Zheng et al., “Judging LLM-as-a-judge with MT-bench and chatbot arena,” in Advances in neural information processing systems, 2023. Available: https://proceedings.neurips.cc/paper_files/paper/2023/hash/91f18a1287b398d378ef22505bf41832-Abstract-Datasets_and_Benchmarks.html
[8]
R. Artstein and M. Poesio, “Inter-coder agreement for computational linguistics,” Computational Linguistics, vol. 34, no. 4, pp. 555–596, 2008, doi: 10.1162/coli.07-034-R2.
[9]
H. Lightman et al., “Let’s verify step by step.” 2023. Available: https://arxiv.org/abs/2305.20050
[10]
S. Yao et al., “ReAct: Synergizing reasoning and acting in language models,” in Proc. Int. Conf. Learning representations (ICLR), 2023.