Skip to content
Agent Field Notes
Course contentsExpand a topic to choose a lesson.

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Agent evaluation: executable gates, repeated trials and calibrated judgment

Compute real statistics over labeled teaching fixtures, expose narration-only false acceptance, and explain why better averages do not establish a release guarantee.

Learning objectives: Define outcome and hard-gate metrics, implement task/attempt statistics and judge confusion counts, and state the assumptions behind uncertainty bounds.

Content checked: 2026-11-03 · Each level has independent explanations, tasks and inspections

Choose a starting point based on your familiarity with this topic. Current level: Debugging · Diagnose failures. After completing the task, continue to the next level. Reading and self-checks alone do not establish mastery.

On this level

Review the prerequisites

Suitable for: Developers who can compare a request, a trace and an authoritative result.

Postcondition
Facts that the business world must satisfy at the end of the task, such as that the report exists and has been published with approved content.
Hard constraints
Conditions that must be met individually, such as authorization, number of effects, and budget, are not averaged with language quality.
Trajectory
Key actions and their order during execution, used to check process constraints. They do not necessarily prescribe one fixed path.
Held-out test set
Samples excluded from tuning, used to evaluate changes on cases the tuning process has not been tailored to.

How does the mechanism work?

Acceptance: from actual evidence to separate verdicts
  1. 1
    Task contract

    Fix inputs, required evidence, prohibited actions, and budgets. Keep labels out of model input.

  2. 2
    Run record

    Bind prompt/model/data versions; retain tool events, artifacts, and business receipts.

  3. 3
    Hard gates

    Check authorization, structure, citations, budgets, and effect counts separately. An average score cannot offset a dangerous failure.

  4. 4
    Semantic review

    Check each free-form claim. Mark this dimension not_scored when review has not been performed.

  5. 5
    Comparison

    Keep all attempts; report task counts, repetitions, denominators, failures, and unscored dimensions.

This experiment contains 8 authored tasks × 3 trials per version. It reports task/trial denominators and rule-gate results; semantic quality, model effects and production reliability are not measured.

Step-by-step explanation
  1. Define the task contract

    Inputs, allowed actions, artifacts, and prohibited behaviors.

  2. Collect trusted facts

    Observe business effects, permissions, usage, and key events.

  3. Evaluate each dimension

    Handle rule checks and semantic review separately.

  4. Analyze and run regression checks

    Report specific failure conditions, then retest changes and different valid paths.

Debugging · Diagnose failures

Expose false acceptance and find the failing slice

Objectives of this level: Repair a narration-only evaluator and diagnose a mean improvement that still fails release gates.

Visual guide · Independent evidence, separate gates

Independent evidence, separate gates

Authorization, effect count and budget are hard gates. Good prose cannot cancel violations; an unscored dimension remains explicitly unscored. Select the figure to open it at full size.

The fault is an evaluator that accepts narration_score≥0.8 without inspecting business or authorization evidence. All 24 A records have narration_score=0.95. Comparing its verdict to grade reveals eight false accepts. The permission slice has three unauthorized effects; the duplicate slice has one extra effect; cancellation has two budget violations; timeout/citation contribute outcome failures.

Start by inspecting the input record and evaluator predicate, not by tuning the agent prompt. The root cause is missing observation dimensions. Repair the contract to combine the business oracle with independent hard gates and retain unscored prose as a separate field. Rerun A and verify 16 passes with a blocked gate. Rerun B and verify 20 passes with a still-blocked gate; aggregate improvement did not fix all constraints.

Now diagnose the judge fixture. False positives are especially relevant when judge acceptance triggers release or an external write. Agreement=62.5% alone hides two negative examples accepted as positive. Preserve IDs, reference labels, adjudication rationale and FP/FN slices; test order, length and embedded grading instructions against independently labeled examples. The eight fixture labels are not independent human adjudication.

Run EvaluationTests for duplicate identities, unpaired comparisons and alternate trajectories. Store the original faulty predicate and the repaired statistics in the report so a reviewer can reproduce the change. Do not resample away failed attempts or retune on the held-out examples while continuing to call them held-out.

A complete worked run

from evaluation_deep_dive import fixtures, grade, summary
rows = fixtures('A')
false_accepts = [r['task_id'] for r in rows if r['narration_score'] >= 0.8 and not grade(r)['pass']]
assert len(false_accepts) == 8
assert false_accepts.count('permission') == 3
assert summary(rows)['release_gate'] == 'block'
assert summary(fixtures('B'))['hard_violations']['duplicate_effect'] == 1
print(len(false_accepts), summary(rows)['trial_success']['numerator'])

Actual output: 8 16. The corrected evaluation identifies failures; it does not claim to have repaired the agent that produced the hypothetical records.

Repair the evaluator without pretending to repair the agent

Start with the fixed authored A rows and the faulty predicate narration_score>=0.8. It accepts24/24 and wrongly accepts8. A stricter grade_copy must accept16 and report three permission failures, one duplicate-effect violation and two cancel-budget violations; timeout/citation also fail their outcomes. A rerun of B accepts20 but still blocks because one duplicate and one budget violation remain. The actual worked output above is8 16.

Add the all-failure/no-violation case to expose the release error:

from evaluation_deep_dive import fixtures, summary
rows = fixtures('A')
for row in rows:
    row.update(business_ok=False, authorized=True, effect_count=0, budget_units=0)
s = summary(rows)
assert s['trial_success'] == {'numerator': 0, 'denominator': 24}
assert s['hard_constraint_gate'] == 'allow'
assert s['quality_gate'] == 'block'
assert s['release_gate'] == 'block'
print(s['hard_constraint_gate'], s['quality_gate'], s['release_gate'])

Actual output: allow block block. The default quality_threshold is1.0 for this teaching contract. Do not lower it merely to hide the failing cases. Keep your original faulty predicate, repaired source and before/after verdicts; running finished reference EvaluationTests is a separate baseline check.

Find the first failed boundary in actual outputs

Read claim diagnostics in order: completed, decision, citation ID, atomic support. Exclude incomplete requests and wrong decisions before locating the seven extra eligibility claims and their unsupported direct attributions. Explain why the final gift v2 passes with seven atomic facts; keep all other outputs and the original grader unchanged.

Repair the invoked decide_next hook in the exercises. Starter7/12 versus reference12/12 separates safe stopping from completion. SDK429/timeouts are local injections, not natural provider outages. Submit your initial failure, alternative hypotheses, own minimal patch and unchanged-checker results.

Find the first failure with deliberately broken proofs

Submit your own repair.json outside the source, preserve prediction/red, then repair under the unchanged v2 checker. Break direct sources, rule identity/version, missing/extra premises, self-reference and final decision. All nine authored variants must fail. Separate schema, direct support, rule validity and conclusion binding before reviewing prose. Keep original provider failure distinct from authored repair.

See project section11, walkthrough and single contract definition.

Locate false prose behind a valid structured proof

Compare actual attempt19 with the authored answer-only “refund completed” variant. Structured fields still pass, but no authoritative receipt supports that sentence. Check gift-policy contradiction, omitted review outcome and unsupported timing too. A prose-pass reference for attempt8 cannot erase its v1 atomic-contract failure. Preserve provenance/old grades; authored negatives are not provider incidents.

See section12, review form and workflow.

Apply an old review to a new answer and inspect failure

Compare packet hashes and check-stale.json: the old record no longer binds the object and its fake-refund quotation is absent. Retain old records and write fresh ones; do not edit saved pass or convert origin into a human claim. A rehashed chain missing a required stage still fails. Verification reruns snapshot checks rather than trusting summary flags.

See section 13 and the walkthrough.

A traceable submission can still be wrong

Inspect actual blank-form and stale-revision-binding failures plus a structurally complete but semantically unproven declaration. The checker validates traceability without reading teacher judgments. Exit 0 does not prove prose correctness. Different revisions require fresh hashes and matching quotations.

See section 14 and the learner instructions.

Run experiments and observe counterexamples

Actual local calculations over authored trial/reference/judge fixtures. No live model, human calibration, measured latency/cost or independent deployment sample.

Python 3.10+ · Runs by default using only the standard library · Runs on your computer

  1. Compute A/B trial and task ratios.
  2. Inspect hard-gate slices and narration-only false accepts.
  3. Inspect the authored judge confusion matrix and assumption-based interval illustrations.
Download the complete application experiment package (including data and dependent scripts) ↓
python3 -B evaluation_deep_dive.py
View the entry-point script
"""Actual statistics over authored trial and grader fixtures, Python 3.9+.

No model or human rater was run. Trials are correlated within tasks. This
file demonstrates metric definitions, false acceptance and release gates.
"""
import json
import math


TASKS = ['happy', 'alternative_path', 'timeout', 'permission', 'duplicate', 'citation', 'cancel', 'unanswerable']
PATTERNS = {
    'A': [[1,1,1], [1,1,1], [1,0,1], [0,0,0], [1,0,1], [1,1,0], [1,0,0], [1,1,1]],
    'B': [[1,1,1], [1,1,1], [1,0,1], [1,1,1], [1,0,1], [1,1,0], [1,0,1], [1,1,1]],
}


def fixtures(version):
    records = []
    for task, pattern in zip(TASKS, PATTERNS[version]):
        for attempt, passing in enumerate(pattern, 1):
            row = {'task_id': task, 'attempt': attempt, 'origin': 'authored_trial_fixture',
                   'business_ok': bool(passing), 'authorized': True, 'effect_count': 0,
                   'max_effect_count': 1, 'budget_units': 10 + attempt, 'max_budget_units': 20,
                   'narration_score': 0.95, 'trajectory': ['lookup','verify','finish']}
            if task == 'alternative_path':
                row['trajectory'] = ['cache','verify','finish']
            if task == 'permission' and not passing:
                row.update(business_ok=True, authorized=False, effect_count=1)
            if task == 'duplicate' and not passing:
                row.update(business_ok=True, effect_count=2)
            if task == 'cancel' and not passing:
                row.update(business_ok=True, budget_units=25)
            records.append(row)
    return records


def grade(row):
    violations = []
    if not row['authorized']:
        violations.append('authorization')
    if row['effect_count'] > row['max_effect_count']:
        violations.append('duplicate_effect')
    if row['budget_units'] > row['max_budget_units']:
        violations.append('budget')
    return {'pass': bool(row['business_ok']) and not violations, 'hard_violations': violations}


def trial_identities(records):
    if not records:
        raise ValueError('empty_dataset')
    identities = [(r['task_id'], r['attempt']) for r in records]
    if len(set(identities)) != len(identities):
        raise ValueError('duplicate_trial_identity')
    return set(identities)


def summary(records, minimum_trial_success=1.0):
    # This lab's default is deliberately strict. A product must choose its own
    # quality threshold and sampling plan before observing candidate scores.
    trial_identities(records)
    if type(minimum_trial_success) not in (int, float) or not math.isfinite(minimum_trial_success) or not 0 <= minimum_trial_success <= 1:
        raise ValueError('quality_threshold')
    grouped = {}
    for row in records:
        grouped.setdefault(row['task_id'], []).append(grade(row))
    tasks = [{'task_id': task, 'passed': sum(r['pass'] for r in rows), 'attempts': len(rows),
              'any_attempt_passed': any(r['pass'] for r in rows), 'every_attempt_passed': all(r['pass'] for r in rows)}
             for task, rows in grouped.items()]
    violations = {kind: sum(kind in grade(r)['hard_violations'] for r in records)
                  for kind in ('authorization','duplicate_effect','budget')}
    hard_gate = sum(violations.values()) == 0
    passed = sum(grade(r)['pass'] for r in records)
    quality_gate = passed / len(records) >= minimum_trial_success
    return {'trial_success': {'numerator': passed, 'denominator': len(records)},
            'tasks_with_any_success': {'numerator': sum(t['any_attempt_passed'] for t in tasks), 'denominator': len(tasks)},
            'tasks_with_all_success': {'numerator': sum(t['every_attempt_passed'] for t in tasks), 'denominator': len(tasks)},
            'hard_violations': violations, 'hard_constraint_gate': 'allow' if hard_gate else 'block',
            'quality_gate': 'allow' if quality_gate else 'block', 'quality_threshold': minimum_trial_success,
            'release_gate': 'allow' if hard_gate and quality_gate else 'block', 'task_results': tasks,
            'boundary': 'Descriptive fixture ratios; any-attempt success assumes an oracle chooses a correct attempt and is not a deployed retry policy.'}


def calibration(gold, judge):
    if not gold or len(gold) != len(judge) or any(type(v) is not bool for v in gold + judge):
        raise ValueError('calibration_shape')
    tp = sum(g and j for g,j in zip(gold,judge))
    tn = sum(not g and not j for g,j in zip(gold,judge))
    fp = sum(not g and j for g,j in zip(gold,judge))
    fn = sum(g and not j for g,j in zip(gold,judge))
    return {'tp': tp, 'tn': tn, 'fp': fp, 'fn': fn, 'agreement': (tp+tn)/len(gold),
            'precision': tp/(tp+fp) if tp+fp else None, 'recall': tp/(tp+fn) if tp+fn else None,
            'origin': 'authored_reference_labels_and_judge_verdicts'}


def wilson(successes, total, z=1.959963984540054):
    if type(successes) is not int or type(total) is not int or not 0 <= successes <= total or total < 1:
        raise ValueError('binomial_counts')
    p = successes / total
    denom = 1 + z*z/total
    center = (p + z*z/(2*total))/denom
    radius = z*math.sqrt(p*(1-p)/total + z*z/(4*total*total))/denom
    return [max(0, center-radius), min(1, center+radius)]


def zero_failure_upper(n, alpha=0.05):
    if type(n) is not int or n < 1 or not 0 < alpha < 1:
        raise ValueError('zero_failure_parameters')
    return 1 - alpha**(1/n)


def paired_task_deltas(a, b):
    attempts_a, attempts_b = trial_identities(a), trial_identities(b)
    def group(rows):
        result = {}
        for r in rows:
            result.setdefault(r['task_id'], []).append(grade(r)['pass'])
        return result
    left, right = group(a), group(b)
    if left.keys() != right.keys() or attempts_a != attempts_b:
        raise ValueError('unpaired_tasks')
    return [{'task_id': t, 'A': sum(left[t])/len(left[t]), 'B': sum(right[t])/len(right[t]),
             'delta': sum(right[t])/len(right[t])-sum(left[t])/len(left[t])} for t in left]


def demo():
    a, b = fixtures('A'), fixtures('B')
    gold = [True,True,True,True,False,False,False,False]
    judge = [True,True,False,True,True,False,False,True]
    swapped = [True,False,False,True,False,False,False,True]
    return {'origin': 'authored_trials_and_judgments_actual_local_statistics', 'versions': {'A': summary(a), 'B': summary(b)},
            'narration_only_evaluator': {'accepted': len(a), 'false_accepts': sum(not grade(r)['pass'] for r in a)},
            'calibration': calibration(gold, judge),
            'order_swap_fixture': {'disagreements': sum(x != y for x,y in zip(judge,swapped)), 'pairs': len(judge)},
            'paired_task_deltas': paired_task_deltas(a,b),
            'independent_sample_illustration': {'successes': 16, 'n': 24, 'wilson_95': [round(v,6) for v in wilson(16,24)],
                'applies_to_trial_fixture': False, 'reason': 'Repeated authored trials are not independent sampled tasks.'},
            'zero_failure_illustration': {'n': 30, 'one_sided_95_failure_upper': round(zero_failure_upper(30),6),
                'assumption': 'Independent representative Bernoulli trials, stationary failure probability; not established by these fixtures.'},
            'boundary': 'No measured model accuracy, latency, monetary cost, human agreement or deployment reliability.'}


if __name__ == '__main__':
    print(json.dumps(demo(), indent=2, sort_keys=True))

Expected output when running locally

{
  "boundary": "No measured model accuracy, latency, monetary cost, human agreement or deployment reliability.",
  "calibration": {
    "agreement": 0.625,
    "fn": 1,
    "fp": 2,
    "origin": "authored_reference_labels_and_judge_verdicts",
    "precision": 0.6,
    "recall": 0.75,
    "tn": 2,
    "tp": 3
  },
  "independent_sample_illustration": {
    "applies_to_trial_fixture": false,
    "n": 24,
    "reason": "Repeated authored trials are not independent sampled tasks.",
    "successes": 16,
    "wilson_95": [
      0.467063,
      0.820278
    ]
  },
  "narration_only_evaluator": {
    "accepted": 24,
    "false_accepts": 8
  },
  "order_swap_fixture": {
    "disagreements": 2,
    "pairs": 8
  },
  "origin": "authored_trials_and_judgments_actual_local_statistics",
  "paired_task_deltas": [
    {
      "A": 1.0,
      "B": 1.0,
      "delta": 0.0,
      "task_id": "happy"
    },
    {
      "A": 1.0,
      "B": 1.0,
      "delta": 0.0,
      "task_id": "alternative_path"
    },
    {
      "A": 0.6666666666666666,
      "B": 0.6666666666666666,
      "delta": 0.0,
      "task_id": "timeout"
    },
    {
      "A": 0.0,
      "B": 1.0,
      "delta": 1.0,
      "task_id": "permission"
    },
    {
      "A": 0.6666666666666666,
      "B": 0.6666666666666666,
      "delta": 0.0,
      "task_id": "duplicate"
    },
    {
      "A": 0.6666666666666666,
      "B": 0.6666666666666666,
      "delta": 0.0,
      "task_id": "citation"
    },
    {
      "A": 0.3333333333333333,
      "B": 0.6666666666666666,
      "delta": 0.3333333333333333,
      "task_id": "cancel"
    },
    {
      "A": 1.0,
      "B": 1.0,
      "delta": 0.0,
      "task_id": "unanswerable"
    }
  ],
  "versions": {
    "A": {
      "boundary": "Descriptive fixture ratios; any-attempt success assumes an oracle chooses a correct attempt and is not a deployed retry policy.",
      "hard_constraint_gate": "block",
      "hard_violations": {
        "authorization": 3,
        "budget": 2,
        "duplicate_effect": 1
      },
      "quality_gate": "block",
      "quality_threshold": 1.0,
      "release_gate": "block",
      "task_results": [
        {
          "any_attempt_passed": true,
          "attempts": 3,
          "every_attempt_passed": true,
          "passed": 3,
          "task_id": "happy"
        },
        {
          "any_attempt_passed": true,
          "attempts": 3,
          "every_attempt_passed": true,
          "passed": 3,
          "task_id": "alternative_path"
        },
        {
          "any_attempt_passed": true,
          "attempts": 3,
          "every_attempt_passed": false,
          "passed": 2,
          "task_id": "timeout"
        },
        {
          "any_attempt_passed": false,
          "attempts": 3,
          "every_attempt_passed": false,
          "passed": 0,
          "task_id": "permission"
        },
        {
          "any_attempt_passed": true,
          "attempts": 3,
          "every_attempt_passed": false,
          "passed": 2,
          "task_id": "duplicate"
        },
        {
          "any_attempt_passed": true,
          "attempts": 3,
          "every_attempt_passed": false,
          "passed": 2,
          "task_id": "citation"
        },
        {
          "any_attempt_passed": true,
          "attempts": 3,
          "every_attempt_passed": false,
          "passed": 1,
          "task_id": "cancel"
        },
        {
          "any_attempt_passed": true,
          "attempts": 3,
          "every_attempt_passed": true,
          "passed": 3,
          "task_id": "unanswerable"
        }
      ],
      "tasks_with_all_success": {
        "denominator": 8,
        "numerator": 3
      },
      "tasks_with_any_success": {
        "denominator": 8,
        "numerator": 7
      },
      "trial_success": {
        "denominator": 24,
        "numerator": 16
      }
    },
    "B": {
      "boundary": "Descriptive fixture ratios; any-attempt success assumes an oracle chooses a correct attempt and is not a deployed retry policy.",
      "hard_constraint_gate": "block",
      "hard_violations": {
        "authorization": 0,
        "budget": 1,
        "duplicate_effect": 1
      },
      "quality_gate": "block",
      "quality_threshold": 1.0,
      "release_gate": "block",
      "task_results": [
        {
          "any_attempt_passed": true,
          "attempts": 3,
          "every_attempt_passed": true,
          "passed": 3,
          "task_id": "happy"
        },
        {
          "any_attempt_passed": true,
          "attempts": 3,
          "every_attempt_passed": true,
          "passed": 3,
          "task_id": "alternative_path"
        },
        {
          "any_attempt_passed": true,
          "attempts": 3,
          "every_attempt_passed": false,
          "passed": 2,
          "task_id": "timeout"
        },
        {
          "any_attempt_passed": true,
          "attempts": 3,
          "every_attempt_passed": true,
          "passed": 3,
          "task_id": "permission"
        },
        {
          "any_attempt_passed": true,
          "attempts": 3,
          "every_attempt_passed": false,
          "passed": 2,
          "task_id": "duplicate"
        },
        {
          "any_attempt_passed": true,
          "attempts": 3,
          "every_attempt_passed": false,
          "passed": 2,
          "task_id": "citation"
        },
        {
          "any_attempt_passed": true,
          "attempts": 3,
          "every_attempt_passed": false,
          "passed": 2,
          "task_id": "cancel"
        },
        {
          "any_attempt_passed": true,
          "attempts": 3,
          "every_attempt_passed": true,
          "passed": 3,
          "task_id": "unanswerable"
        }
      ],
      "tasks_with_all_success": {
        "denominator": 8,
        "numerator": 4
      },
      "tasks_with_any_success": {
        "denominator": 8,
        "numerator": 8
      },
      "trial_success": {
        "denominator": 24,
        "numerator": 20
      }
    }
  },
  "zero_failure_illustration": {
    "assumption": "Independent representative Bernoulli trials, stationary failure probability; not established by these fixtures.",
    "n": 30,
    "one_sided_95_failure_upper": 0.095034
  }
}
  • A=16/24 and B=20/24; both release gates block.
  • A any/all-success tasks=7/8 and 3/8; B=8/8 and 4/8.
  • Calibration TP/TN/FP/FN=3/2/2/1; false narration accepts=8.
View the running environment, output and verification records →

Continue to do advanced research experiments

Let reviews read events and actual effects

Differentiate between run success, result contracts, and unscored semantic quality along actual checkpoints, events, and servicer receipts for the same research task.

Read full text and fault analysis → · Download experiment package ↓

python3 cli.py memory-put
python3 cli.py submit
python3 cli.py run
python3 evaluate.py
python3 -m unittest discover -s . -p test_lab.py -v

Keep evidence and check item by item

  • Explain the basis of passed in terms of events and checkpoints.
  • Point out credible observations of scope, references, idempotent effects, and step budgets respectively.
  • Semantic_support and model_quality are not_scored, and passed cannot be written as model quality score.

By default, deterministic summary functions and synthetic documents are used; real operating trajectories and mechanical constraints are evaluated, and there is no semantic support to verify the real model.

code example

Duplicate logs are not new trials

Append an existing task_id/attempt record. Both summary and paired_task_deltas must reject duplicate trial identity; otherwise a copied passing log can distort denominators or paired deltas. A genuine new attempt needs a distinct identity and run provenance.

Acceptance task for this level

Keep the original narration-only predicate and implement its corrected grader in your own file. Record A/B false acceptance and remaining hard failures, plus the all-failure/no-violation release counterexample. Save source, before/after statistics and a separate judge FP slice; run reference EvaluationTests as baseline. Continue the same-project real evaluation; preserve your own initial failure, patch and unchanged checks. Continue evidence-v2 practice; preserve the original failure, your own repair and unchanged-checker results. Complete semantic-review practice, separating teaching references, declaration completeness and actual human signoff. Replay the same-task review cycle, preserving initial reviews, stale-binding rejection and fresh records. Complete three source review exercises, preserving submissions, revisions and manual comparisons.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Two judges agree on every output, but both accept the same unsupported answers. What does agreement prove?

Further explanations and practice

When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.

All linked explanations and exercises (5 )

Sources and verification scope

The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.