Articles

Goal Engineering for AI Agents: Objectives, Constraints, and Evaluation

Goal engineering for AI agents in practice: a goal spec template, measurable acceptance criteria, per-run tests, feedback units and a guard for proxy metrics.

· 17 min read
goal-engineering ai-agents acceptance-criteria agent-evaluation llm-evaluation annotation python
Banner with the post title on the left and, on the right, a honeycomb of six hexagons for objective, constraints, acceptance criteria, out of scope, owner and review cadence around a central goal_spec.json cell.
Table of Contents

A support team hands an AI agent its billing queue with one instruction: close the backlog. Two weeks later the tickets-closed-per-hour chart is climbing, and so is the reopen queue. Customers write back about the same invoice address, and nobody can say whether the agent did its job, because nobody wrote down what the job was.

Goal engineering for AI agents fixes this by writing down the outcome, the constraints and the checks before the agent runs. This guide builds one goal spec for a billing support agent, turns each criterion into a test on every run, stores reviewer findings as feedback units, and catches a proxy metric that improves while the goal fails.

The support team is an illustration. The three scripts below (gen_fixture.py, check_goal.py and proxy_trap.py) use only the Python standard library and are tested end to end against a synthetic 40-ticket fixture, so every number they print is illustrative, not measured customer results.

TL;DR

  • Goal engineering for AI agents means writing the objective, hard and soft constraints, acceptance criteria, out-of-scope list, owner and review cadence before the agent runs.
  • A measurable acceptance criterion names an observable signal, a threshold, the data source that holds it and the person who decides a tie.
  • Each criterion becomes a deterministic check where possible and an eval only where judgment is needed, run on every agent run, with a release verdict that fails closed.
  • Reviewer findings go into one feedback unit per run and criterion (run id, criterion id, verdict, evidence, reviewer, timestamp), never a free-text review.
  • A guard test pairs each proxy metric with its goal metric: in the illustrative fixture, tickets closed per hour rose from 4.74 to 9.00 while in-scope tickets resolved with no reopen fell from 0.919 to 0.676.

The blank goal specification template below holds every field the rest of this guide fills in, including the keys the checker reads; the optional applies_to takes “all” or “in_scope”. Copy it into version control as goal_spec.json before the agent’s first run.

{
  "spec_version": "",
  "objective": "",
  "owner": "",
  "review_cadence": "",
  "constraints": {"hard": [], "soft": []},
  "out_of_scope": [],
  "observation": {"reopen_window_days": null, "min_age_days_to_score": null},
  "acceptance_criteria": [
    {"id": "", "name": "", "check": "", "applies_to": "", "signal": "", "per_run_threshold": null,
     "min_pass_rate": null, "data_source": "", "check_type": "", "severity": "", "tie_decider": ""}
  ],
  "proxy_guard": {"proxy_metric": "", "goal_metric": "", "min_proxy_gain": null, "max_goal_drop": null},
  "revision_triggers": [],
  "in_scope_categories": [],
  "out_of_scope_categories": []
}

What goal engineering means for AI agents

Goal engineering for AI agents is the work of stating what a finished task looks like in terms a check can confirm. The goal spec names the outcome, the constraints the agent must respect, the acceptance criteria that prove success and the person who owns it, so anyone can tell whether a run did the job.

The term in its AI sense is recent. On 2026-11-14, Harrison Chase of LangChain, writing with Mihir Garimella and Anshul Gupta of Actively AI, argued for scoping an agent around what makes human feedback easy to give, without giving a spec format.

Coding-agent tools ask for parts of a goal spec. Claude Code asks for “One measurable end state”, “A stated check” and “Constraints that matter”, and OpenAI’s Codex asks for “a measurable outcome, a verification surface, and constraints”. The Codex cookbook is dated 2026-05-09 and the Claude Code page shows no date (read in November); this guide’s spec has six parts.

The sources are the Claude Code goal docs and the Codex goals cookbook.

Where AI agent goals sit next to prompts and context

A prompt words one instruction. Context engineering decides what information the model sees at each step. The goal spec defines the outcome and the checks that confirm it, and it stays fixed while prompts and context change around it from one release to the next.

Context design and feedback loops in general stay on their own pages. Everything below covers the spec and the checks that run against it: the template, the criteria, the per-run checks, the feedback units, the proxy guard and the revision rules.

The goal engineering spec template for AI agents

A goal spec for an AI agent fits on one screen and holds six parts: an outcome-based objective, hard and soft constraints, acceptance criteria with ids, an out-of-scope list, a named owner and a review cadence. The filled version below is the spec for a billing support agent, kept as JSON beside its code.

Each field exists because something breaks without it: with no owner, nobody decides a tie, and with no cadence, the spec drifts from the policy it describes. The file below is the whole goal_spec.json, versioned as spec_version 1.0.0, and its roles and numbers are fixture values.

{
  "spec_version": "1.0.0",
  "data_label": "illustrative fixture, not measured customer results",
  "agent": "billing-support-agent (fixture)",
  "objective": "Resolve inbound billing tickets (plan-change, invoice-address, tax-ID update) so the customer does not come back about the same issue within 7 days.",
  "owner": "support-ops lead (fixture role)",
  "review_cadence": "weekly, and immediately on any revision trigger below",
  "constraints": {
    "hard": [
      "No account change before the customer identity is verified (checked by G2).",
      "Only the three in-scope ticket categories are handled; anything else is escalated (checked by G3)."
    ],
    "soft": [
      "Stay within 12 tool calls per ticket (checked by G5).",
      "Replies match the written billing policy, scored 0 to 1 by an eval (checked by G4)."
    ]
  },
  "out_of_scope": [
    "payment-method changes by phone (category payment-method-change)",
    "contract renewals and custom pricing (category contract-renewal)"
  ],
  "observation": {
    "reopen_window_days": 7,
    "min_age_days_to_score": 7
  },
  "acceptance_criteria": [
    {
      "id": "G1",
      "name": "resolved_no_reopen_7d",
      "check": "resolved_no_reopen",
      "applies_to": "in_scope",
      "check_type": "deterministic",
      "severity": "normal",
      "signal": "in-scope ticket status is resolved and the customer did not reopen it within 7 days of closing (out-of-scope tickets are scored by G3)",
      "per_run_threshold": null,
      "min_pass_rate": 0.8,
      "data_source": "ticketing system export: final_status, closed_at, reopened_at",
      "tie_decider": "support-ops lead"
    },
    {
      "id": "G2",
      "name": "identity_verified_before_account_change",
      "check": "identity_before_change",
      "check_type": "deterministic",
      "severity": "critical",
      "signal": "every account change has identity_verified true and identity_verified_at earlier than account_changed_at",
      "per_run_threshold": null,
      "min_pass_rate": 1.0,
      "data_source": "agent run log: account_changed, identity_verified, account_changed_at, identity_verified_at",
      "tie_decider": "security owner (fixture role); a tie fails the run"
    },
    {
      "id": "G3",
      "name": "out_of_scope_escalated",
      "check": "out_of_scope_escalated",
      "check_type": "deterministic",
      "severity": "critical",
      "signal": "every out-of-scope ticket has final_status escalated",
      "per_run_threshold": null,
      "min_pass_rate": 1.0,
      "data_source": "agent run log: category, final_status",
      "tie_decider": "support-ops lead; a tie fails the run"
    },
    {
      "id": "G4",
      "name": "reply_matches_billing_policy",
      "check": "eval_score_at_least",
      "check_type": "eval",
      "severity": "normal",
      "signal": "custom eval score for the reply is at least 0.7 (one finite score in 0 to 1)",
      "per_run_threshold": 0.7,
      "min_pass_rate": 0.85,
      "data_source": "eval result stored per run: judge_score, judge_reason (fixture stand-in)",
      "tie_decider": "support-ops lead reads the stored reason"
    },
    {
      "id": "G5",
      "name": "within_tool_call_budget",
      "check": "tool_calls_at_most",
      "check_type": "deterministic",
      "severity": "normal",
      "signal": "tool_calls is at most 12",
      "per_run_threshold": 12,
      "min_pass_rate": 0.9,
      "data_source": "agent run log: tool_calls",
      "tie_decider": "support-ops lead"
    }
  ],
  "proxy_guard": {
    "proxy_metric": "tickets_closed_per_hour",
    "goal_metric": "resolved_no_reopen_7d",
    "min_proxy_gain": 0.1,
    "max_goal_drop": 0.02
  },
  "revision_triggers": [
    "a new ticket category is added to scope",
    "the billing policy document changes",
    "the proxy guard fires",
    "any critical failure in a release check",
    "two consecutive weekly reviews with the same criterion below its minimum pass rate"
  ],
  "in_scope_categories": [
    "plan-change",
    "invoice-address",
    "tax-id-update"
  ],
  "out_of_scope_categories": [
    "contract-renewal",
    "payment-method-change"
  ]
}

Objective, owner and review cadence for a billing agent

The objective reads: “Resolve inbound billing tickets (plan-change, invoice-address, tax-ID update) so the customer does not come back about the same issue within 7 days.” It names an outcome the customer feels, three categories and a window a ticketing system can measure.

An activity objective such as “close tickets” fails because the agent can satisfy it while the customer’s problem stays open. The owner is the support-ops lead, a fixture role, and the cadence is “weekly, and immediately on any revision trigger below”.

Hard constraints block a release, soft constraints get scored

The two hard constraints are no account change before the customer’s identity is confirmed (criterion G2) and escalation of anything outside the three in-scope categories (G3). Both are critical, so one violation blocks the release whatever the pass rate, and a reviewer tie fails the run.

The soft constraints are scored: at most 12 tool calls per ticket (G5, minimum pass rate 0.9), and replies that match the written billing policy, scored 0 to 1 by an eval with a per-run bar of 0.7 (G4, minimum pass rate 0.85). Each constraint maps to a criterion id, so a check can read it.

What the out-of-scope list must name

The list names “payment-method changes by phone” and “contract renewals and custom pricing”, each with the category label the agent sees (payment-method-change, contract-renewal) and the required action, escalation. The in_scope_categories and out_of_scope_categories lists feed the G3 check and intake validation, so an unknown category fails the verdict closed.

Writing acceptance criteria an agent can be checked against

A measurable acceptance criterion has four parts: an observable signal, a threshold, the data source that holds the signal, and the person who decides when the evidence is split. Leave one out and two reviewers can read the same agent run and still disagree about whether it passed.

The table below holds the five billing criteria from the illustrative fixture, not measured customer results. Two numbers do different jobs: the per-run threshold decides whether one run passes, and the minimum pass rate decides whether the batch of runs clears the criterion.

IDCriterionObservable signalThreshold (per run / min pass rate)Data sourceCheck typeSeverityTie decider
G1resolved_no_reopen_7dIn-scope ticket resolved, no reopen within 7 days of closingnone / 0.8Ticketing system export: final_status, closed_at, reopened_atDeterministicNormalSupport-ops lead
G2identity_verified_before_account_changeEvery account change has identity_verified true and identity_verified_at before account_changed_atnone / 1.0Agent run logDeterministicCriticalSecurity owner, a tie fails the run
G3out_of_scope_escalatedEvery out-of-scope ticket has final_status escalatednone / 1.0Agent run log: category, final_statusDeterministicCriticalSupport-ops lead, a tie fails the run
G4reply_matches_billing_policyCustom eval score at least 0.7, one finite score in 0 to 10.7 / 0.85Eval result stored per runEvalNormalSupport-ops lead reads the stored reason
G5within_tool_call_budgettool_calls at most 1212 / 0.9Agent run log: tool_callsDeterministicNormalSupport-ops lead

G1 is scored over in-scope tickets only (“applies_to”: “in_scope”), because out-of-scope tickets belong to G3 and a correct escalation is not a G1 miss. A no-reopen success requires the full 7-day window after closing; an observed reopen within the window can fail early. Events after as_of fail the verdict closed.

Rewriting a vague criterion into a measurable one

“Customers are happy with billing answers” names a hope that no export can confirm. Rewritten, it becomes G1: resolved status, no reopen within 7 days, the ticketing system export as evidence, and the support-ops lead deciding a split. Two reviewers reading the same export now reach the same verdict.

“The agent is careful with accounts” becomes G2: every account change has identity_verified true and identity_verified_at strictly before account_changed_at in the exported run log, and the security owner decides disputes. For critical criteria the spec says a tie fails the run, because a disputed identity check is not a pass.

Turning each criterion into a test on every agent run

Each acceptance criterion becomes one check that runs on every agent run: a deterministic function when the signal is a field you can read, and an eval only when the criterion needs judgment. The checker writes one verdict per run and criterion, then a release verdict that fails closed on bad data.

check_goal.py, tested end to end with the Python 3.12.5 standard library, loads goal_spec.json and fixture_runs.json, 40 run records with fields such as category, final_status, reopened_at, tool_calls and judge_score. The records are an illustrative fixture, not measured customer results.

Each fixture run has at most one account change; an export with multiple changes needs a record for each change. The timestamps must come from evidence the agent cannot edit, not its success message.

Flow from the goal spec through one check per criterion and per run to feedback units and a release verdict that fails closed

gen_fixture.py writes both fixture files with no randomness: policy v1 for the baseline and the gamed policy v2 used later. Keep all the files in one folder and run gen_fixture.py first, because proxy_trap.py imports functions from check_goal.py.

"""Writes the two fixture files. Deterministic, no randomness. All data is synthetic:
illustrative fixture, not measured customer results."""
import json
from datetime import datetime, timedelta, timezone

LABEL = "illustrative fixture, not measured customer results"
CATS = ["plan-change", "invoice-address", "tax-id-update"]
OUT = {9: "contract-renewal", 22: "payment-method-change", 35: "contract-renewal"}  # out-of-scope tickets
BASE = datetime(2026, 10, 1, 9, 0, tzinfo=timezone.utc)
AS_OF = "2026-11-12T00:00:00Z"


def iso(d):
    return d.strftime("%Y-%m-%dT%H:%M:%SZ")


def build(policy):
    runs = []
    for i in range(1, 41):
        cat = OUT.get(i, CATS[i % 3])
        changed = cat != "tax-id-update" and i % 2 == 0
        closed = BASE + timedelta(hours=13 * i)
        if policy == "v1":
            escalated = i in (9, 22, 35)
            reopen_days = {4: 2, 15: 5, 28: 3, 30: 9}.get(i)
            minutes = 9 + (i * 7) % 6 + (1 if i % 5 == 0 else 0)  # 9 to 15
            calls = 13 + i % 3 if i in (6, 18, 33) else 3 + (i * 5) % 7  # 3 to 9, three over budget
            score = 0.55 + 0.01 * (i % 5) if i in (3, 14, 21, 26, 37) else 0.74 + 0.02 * (i % 12)
            verified = True
        else:  # v2: the gamed policy, closes on the first reply and skips verification
            escalated = i == 22  # the gamed policy also closes the other out-of-scope tickets (9, 35)
            reopen_days = 1 + i % 6 if i % 3 == 0 and not escalated else None
            minutes = 5 + (i * 3) % 4  # 5 to 8
            calls = 13 if i in (6, 18) else 2 + (i * 5) % 5
            score = 0.55 + 0.01 * (i % 5) if i in (3, 14, 21, 26, 37, 8, 30) else 0.72 + 0.02 * (i % 12)
            verified = i not in (10, 28)
        reopened = None if reopen_days is None else iso(closed + timedelta(days=reopen_days, hours=2))
        runs.append({
            "run_id": f"{policy}-run-{i:03d}",
            "ticket_id": f"T-{1000 + i}",
            "category": cat,
            "policy": policy,
            "final_status": "escalated" if escalated else "resolved",
            "closed_at": None if escalated else iso(closed),
            "reopened_at": reopened,
            "handle_minutes": minutes,
            "tool_calls": calls,
            "account_changed": changed and not escalated,
            "identity_verified": verified,
            "account_changed_at": iso(closed - timedelta(minutes=2)) if changed and not escalated else None,
            "identity_verified_at": iso(closed - timedelta(minutes=3)) if verified else None,
            "judge_score": round(score, 2),
            "judge_reason": "fixture text standing in for an eval reason",
        })
    return {"data_label": LABEL, "as_of": AS_OF, "policy": policy, "runs": runs}


if __name__ == "__main__":
    for policy, name in (("v1", "fixture_runs.json"), ("v2", "fixture_runs_after.json")):
        with open(name, "w") as f:
            json.dump(build(policy), f, indent=1)
        print("wrote", name)
"""Runs one check per acceptance criterion per run, writes feedback units (JSONL), prints
per-criterion pass rates and a release verdict. Fails closed on an empty run list, missing or
malformed fields, duplicate run ids, runs too young to score, an unknown check or scope, a
criterion with no runs in its scope, a record missing closed_at or reopened_at, a non-string
run_id, a runs file that is not JSON, any other unexpected record shape, and any critical
failure (whatever the pass rate). The units file is truncated before anything else, so no exit
path leaves a previous run's units behind. Standard library only. All data is synthetic:
illustrative fixture, not measured customer results.

Usage: python3 check_goal.py [--spec goal_spec.json] [--runs fixture_runs.json]
       [--units feedback_units.jsonl] [--expect-spec-sha256 HEX] | --selftest
"""
import argparse, hashlib, json, math, sys
from datetime import datetime, timedelta, timezone

REQUIRED = {"run_id": str, "ticket_id": str, "category": str, "policy": str, "final_status": str,
            "handle_minutes": (int, float), "tool_calls": int, "account_changed": bool,
            "identity_verified": bool, "judge_score": (int, float), "judge_reason": str}
STATUSES = {"resolved", "escalated"}
SCOPES = {"all", "in_scope"}  # optional per-criterion "applies_to"; default "all"


def applies(c, r, spec):
    return c.get("applies_to", "all") == "all" or r["category"] in spec["in_scope_categories"]


def ts(s):
    if not isinstance(s, str) or not s.strip():
        raise ValueError("timestamp must be a non-empty string")
    value = datetime.fromisoformat(s.replace("Z", "+00:00"))
    if value.utcoffset() is None:
        raise ValueError("timestamp must include a UTC offset")
    return value


def finite(x):
    return isinstance(x, (int, float)) and not isinstance(x, bool) and math.isfinite(x)


def validate(doc, spec):
    """Returns (runs, errors). Any error means the verdict is FAIL."""
    errs = []
    runs = doc.get("runs") if isinstance(doc, dict) else None
    if not isinstance(runs, list) or not runs:
        return [], ["empty or missing run list"]
    try:
        as_of = ts(doc["as_of"])
    except Exception:
        return [], ["missing or malformed as_of"]
    window = timedelta(days=spec["observation"]["reopen_window_days"])
    min_age = max(window, timedelta(days=spec["observation"]["min_age_days_to_score"]))
    seen = set()
    for n, r in enumerate(runs):
        rid = r.get("run_id", f"#{n}") if isinstance(r, dict) else f"#{n}"
        if not isinstance(r, dict):
            errs.append(f"{rid}: record is not an object"); continue
        if not isinstance(rid, str):
            errs.append(f"#{n}: run_id missing or not a string"); continue
        if rid in seen:
            errs.append(f"{rid}: duplicate run_id")
        seen.add(rid)
        bad = False
        for k, t in REQUIRED.items():
            v = r.get(k)
            ok = isinstance(v, t) and (t is bool or not isinstance(v, bool)) and (t is bool or t is str or finite(v))
            if not ok:
                errs.append(f"{rid}: field {k} missing, wrong type or non-finite"); bad = True
        for k in ("closed_at", "reopened_at", "account_changed_at", "identity_verified_at"):  # present, null or timestamp
            if k not in r:
                errs.append(f"{rid}: field {k} missing"); bad = True
        if bad:
            continue
        if r["category"] not in set(spec["in_scope_categories"]) | set(spec["out_of_scope_categories"]): errs.append(f"{rid}: unknown category")
        if r["final_status"] not in STATUSES: errs.append(f"{rid}: unknown final_status")
        if not 0 <= r["judge_score"] <= 1: errs.append(f"{rid}: judge_score outside 0 to 1")
        if r["tool_calls"] < 0 or r["handle_minutes"] <= 0: errs.append(f"{rid}: negative or zero count")
        try:
            closed = ts(r["closed_at"]) if r["closed_at"] is not None else None
            reopened = ts(r["reopened_at"]) if r["reopened_at"] is not None else None
            changed = ts(r["account_changed_at"]) if r["account_changed_at"] is not None else None
            verified = ts(r["identity_verified_at"]) if r["identity_verified_at"] is not None else None
        except Exception:
            errs.append(f"{rid}: malformed timestamp"); continue
        if any(event is not None and event > as_of for event in (closed, reopened, changed, verified)):
            errs.append(f"{rid}: event after as_of"); continue
        if r["account_changed"] != (changed is not None) or r["identity_verified"] != (verified is not None):
            errs.append(f"{rid}: identity/account flag does not match timestamp"); continue
        if (r["final_status"] == "resolved") != (closed is not None):
            errs.append(f"{rid}: closed_at does not match final_status")
        elif reopened and (closed is None or reopened < closed):
            errs.append(f"{rid}: reopened_at without an earlier closed_at")
        elif closed and not (reopened is not None and reopened - closed <= window) and as_of - closed < min_age:
            errs.append(f"{rid}: closed under {min_age.days} days before as_of, cannot score reopen yet")
    return runs, errs


def c_resolved_no_reopen(r, spec, _t):
    if r["final_status"] != "resolved":
        return False, f"status {r['final_status']}, not resolved"
    if r["reopened_at"] is not None:
        gap = ts(r["reopened_at"]) - ts(r["closed_at"])
        if gap <= timedelta(days=spec["observation"]["reopen_window_days"]):
            return False, f"reopened {gap.total_seconds() / 86400:.1f} days after closing"
        return True, f"reopened after {gap.total_seconds() / 86400:.1f} days, outside the window"
    return True, "resolved, no reopen"


def c_identity_before_change(r, spec, _t):
    if not r["account_changed"]:
        return True, "no account change"
    ok = r["identity_verified"] and ts(r["identity_verified_at"]) < ts(r["account_changed_at"])
    return ok, f"account changed at {r['account_changed_at']}, identity verified at {r['identity_verified_at']}"


def c_out_of_scope_escalated(r, spec, _t):
    if r["category"] in spec["in_scope_categories"]:
        return True, "in-scope category"
    return r["final_status"] == "escalated", f"out-of-scope category {r['category']}, status {r['final_status']}"


def c_eval_score_at_least(r, spec, t):
    return r["judge_score"] >= t, f"eval score {r['judge_score']} against {t}"


def c_tool_calls_at_most(r, spec, t):
    return r["tool_calls"] <= t, f"{r['tool_calls']} tool calls against budget {t}"


CHECKS = {"resolved_no_reopen": c_resolved_no_reopen, "identity_before_change": c_identity_before_change,
          "out_of_scope_escalated": c_out_of_scope_escalated,
          "eval_score_at_least": c_eval_score_at_least, "tool_calls_at_most": c_tool_calls_at_most}


def evaluate(spec, doc):
    """Returns (verdict, report lines, feedback units). Verdict is PASS only if nothing fails."""
    runs, errs = validate(doc, spec)
    crit = spec["acceptance_criteria"]
    for c in crit:
        if c["check"] not in CHECKS:
            errs.append(f"{c['id']}: unknown check {c['check']}")
        if c.get("applies_to", "all") not in SCOPES:
            errs.append(f"{c['id']}: unknown applies_to {c['applies_to']}")
        elif not errs and not any(applies(c, r, spec) for r in runs):
            errs.append(f"{c['id']}: no runs in scope for this criterion")
    if errs:
        return "FAIL", ["data errors, verdict fails closed:"] + ["  " + e for e in errs[:10]] + (
            [f"  ... and {len(errs) - 10} more"] if len(errs) > 10 else []), []
    now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    units, lines, fail = [], [], False
    for c in crit:
        scoped = [r for r in runs if applies(c, r, spec)]  # runs outside applies_to get no unit
        res = [CHECKS[c["check"]](r, spec, c["per_run_threshold"]) for r in scoped]
        for r, (ok, why) in zip(scoped, res):
            units.append({"unit_id": f"{r['run_id']}:{c['id']}", "run_id": r["run_id"], "criterion_id": c["id"],
                          "verdict": "pass" if ok else "fail", "evidence": why,
                          "reviewer": "check_goal.py", "timestamp": now})
        n_fail = sum(not ok for ok, _ in res)
        rate = (len(res) - n_fail) / len(res)
        bad = rate < c["min_pass_rate"] or (c["severity"] == "critical" and n_fail > 0)
        fail |= bad
        lines.append(f"{c['id']} {c['name']:<40} {len(res) - n_fail:>2}/{len(res)} pass rate {rate:.3f} "
                     f"(min {c['min_pass_rate']}) {c['severity']:<8} {'FAIL' if bad else 'ok'}")
    return ("FAIL" if fail else "PASS"), lines, units


def load(path, expect_sha=None):
    raw = open(path, "rb").read()
    if expect_sha and hashlib.sha256(raw).hexdigest() != expect_sha:
        raise SystemExit(f"FAIL (closed): {path} sha256 does not match the pinned value")
    return json.loads(raw)


def selftest():
    spec, base = load("goal_spec.json"), load("fixture_runs.json")
    cp = lambda: json.loads(json.dumps(base))
    assert evaluate(spec, base)[0] == "PASS", "clean fixture should pass"
    empty = cp(); empty["runs"] = []
    dup = cp(); dup["runs"][1]["run_id"] = dup["runs"][0]["run_id"]
    miss = cp(); del miss["runs"][0]["judge_score"]
    nan = cp(); nan["runs"][0]["judge_score"] = float("nan")
    rng = cp(); rng["runs"][0]["judge_score"] = 1.4
    boolcnt = cp(); boolcnt["runs"][0]["tool_calls"] = True
    young = cp(); young["as_of"] = "2026-10-05T00:00:00Z"
    noreopen = cp(); del noreopen["runs"][0]["reopened_at"]
    listid = cp(); listid["runs"][0]["run_id"] = ["v1-run-001"]
    for name, d in [("empty list", empty), ("duplicate run_id", dup), ("missing field", miss), ("NaN score", nan),
                    ("score out of range", rng), ("bool as count", boolcnt), ("runs too young to score", young),
                    ("record without reopened_at key", noreopen), ("list run_id", listid)]:
        assert evaluate(spec, d)[0] == "FAIL", name
    # one critical failure blocks the release although every pass rate stays high
    crit = cp(); r = next(x for x in crit["runs"] if x["account_changed"]); r["identity_verified"] = False; r["identity_verified_at"] = None
    lax = json.loads(json.dumps(spec)); lax["acceptance_criteria"][1]["min_pass_rate"] = 0.5  # aggregate clears
    v, lines, _ = evaluate(lax, crit)
    assert v == "FAIL" and "G2" in "".join(l for l in lines if "FAIL" in l), "critical failure must block"
    # an out-of-scope ticket that the agent handled instead of escalating is a critical failure
    oos = cp(); r = next(x for x in oos["runs"] if x["category"] in spec["out_of_scope_categories"])
    r["final_status"], r["closed_at"] = "resolved", "2026-10-02T09:00:00Z"
    v, lines, _ = evaluate(spec, oos)
    assert v == "FAIL" and "G3" in "".join(l for l in lines if "FAIL" in l), "out-of-scope handling must block"
    # a deliberately broken record turns its criterion red
    brk = cp(); brk["runs"][0]["tool_calls"] = 99
    _, _, units = evaluate(spec, brk)
    assert any(u["criterion_id"] == "G5" and u["verdict"] == "fail" and u["run_id"] == brk["runs"][0]["run_id"] for u in units)
    bad_spec = json.loads(json.dumps(spec)); bad_spec["acceptance_criteria"][0]["check"] = "no_such_check"
    assert evaluate(bad_spec, base)[0] == "FAIL"
    bad_scope = json.loads(json.dumps(spec)); bad_scope["acceptance_criteria"][0]["applies_to"] = "some"
    assert evaluate(bad_scope, base)[0] == "FAIL", "unknown applies_to must fail closed"
    # G1 scores in-scope tickets only: an out-of-scope ticket gets no G1 unit
    _, _, units = evaluate(spec, base)
    oos_ids = {x["run_id"] for x in base["runs"] if x["category"] in spec["out_of_scope_categories"]}
    assert oos_ids and not any(u["criterion_id"] == "G1" and u["run_id"] in oos_ids for u in units), "G1 must skip out-of-scope"
    try:
        load("goal_spec.json", "0" * 64); raise AssertionError("pin mismatch must stop the run")
    except SystemExit:
        pass
    print("selftest: 16 fail-closed and red-on-broken cases behaved as expected")


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--spec", default="goal_spec.json"); ap.add_argument("--runs", default="fixture_runs.json")
    ap.add_argument("--units", default="feedback_units.jsonl"); ap.add_argument("--expect-spec-sha256")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest:
        selftest(); sys.exit(0)
    open(a.units, "w").close()  # truncated first, so no exit path leaves a previous run's units behind
    spec = load(a.spec, a.expect_spec_sha256)
    try:
        doc = load(a.runs)
    except (OSError, ValueError):
        print("data errors, verdict fails closed:\n  runs file unreadable or not JSON")
        print("RELEASE VERDICT: FAIL"); sys.exit(1)
    print(f"spec {a.spec} sha256 {hashlib.sha256(open(a.spec, 'rb').read()).hexdigest()}")
    d = doc if isinstance(doc, dict) else {}
    runs_n = len(d["runs"]) if isinstance(d.get("runs"), list) else 0
    print(f"runs {a.runs} ({d.get('data_label', 'UNLABELLED')}), {runs_n} records")
    try:
        verdict, lines, units = evaluate(spec, doc)
    except (KeyError, TypeError, ValueError):
        print("data errors, verdict fails closed:\n  unexpected record shape")
        print("RELEASE VERDICT: FAIL"); sys.exit(1)
    print("\n".join(lines))
    with open(a.units, "w") as f:  # rewritten with this run's units only
        f.writelines(json.dumps(u) + "\n" for u in units)
    if units:
        print(f"wrote {len(units)} feedback units to {a.units}")
    print(f"RELEASE VERDICT: {verdict}")
    sys.exit(0 if verdict == "PASS" else 1)
$ python3 check_goal.py
spec goal_spec.json sha256 a105f7dd85133690969f02daddcf285e8a30efecdadac63f548b909e7660f573
runs fixture_runs.json (illustrative fixture, not measured customer results), 40 records
G1 resolved_no_reopen_7d                    34/37 pass rate 0.919 (min 0.8) normal   ok
G2 identity_verified_before_account_change  40/40 pass rate 1.000 (min 1.0) critical ok
G3 out_of_scope_escalated                   40/40 pass rate 1.000 (min 1.0) critical ok
G4 reply_matches_billing_policy             35/40 pass rate 0.875 (min 0.85) normal   ok
G5 within_tool_call_budget                  37/40 pass rate 0.925 (min 0.9) normal   ok
wrote 197 feedback units to feedback_units.jsonl
RELEASE VERDICT: PASS
[exit 0]

Deterministic checks first, an eval only for judgment

G1, G2, G3 and G5 are plain field checks on a status, timestamp order or gaps, a boolean, a category or a count, and two readers of one record cannot disagree about them. Only G4, whether a reply matches the billing policy, needs judgment, so a custom eval scores it from 0 to 1 against a bar of 0.7.

In the fixture, G4 reads a stored stand-in score from judge_score, so the script needs no model and no key. In production that field holds each run’s real eval result with the same threshold logic, and the Future AGI section shows the call that fills it.

For how judge models score text, read LLM-as-a-judge.

A release verdict that fails closed

The checker fails closed on an empty run list, missing or malformed fields, duplicate run ids, non-finite or out-of-range scores, runs too young to score, unknown checks or scopes, a criterion with no runs in scope, a missing reopened_at, a non-string run_id, other unexpected record shapes and a runs file that is not JSON.

It empties the units file first, so a failed run, a pin mismatch included, leaves no stale verdicts. Any critical failure blocks the release even when the pass rate clears its minimum, and the spec hash pin applies when CI passes --expect-spec-sha256. The printed results:

$ python3 check_goal.py --expect-spec-sha256 0000000000000000000000000000000000000000000000000000000000000000 --units /dev/null
FAIL (closed): goal_spec.json sha256 does not match the pinned value
[exit 1]
# fail-closed demo: an empty run list, a duplicate run_id and a runs file that is not JSON (temporary files, deleted afterwards)
# to build them, copy fixture_runs.json: empty.json sets "runs" to [], dup.json gives run 2 the run_id of run 1, notjson.txt holds plain text

$ python3 check_goal.py --runs <tmpdir>/empty.json --units /dev/null
spec goal_spec.json sha256 a105f7dd85133690969f02daddcf285e8a30efecdadac63f548b909e7660f573
runs <tmpdir>/empty.json (illustrative fixture, not measured customer results), 0 records
data errors, verdict fails closed:
  empty or missing run list
RELEASE VERDICT: FAIL
[exit 1]

$ python3 check_goal.py --runs <tmpdir>/dup.json --units /dev/null
spec goal_spec.json sha256 a105f7dd85133690969f02daddcf285e8a30efecdadac63f548b909e7660f573
runs <tmpdir>/dup.json (illustrative fixture, not measured customer results), 40 records
data errors, verdict fails closed:
  v1-run-001: duplicate run_id
RELEASE VERDICT: FAIL
[exit 1]

$ python3 check_goal.py --runs <tmpdir>/notjson.txt --units /dev/null
data errors, verdict fails closed:
  runs file unreadable or not JSON
RELEASE VERDICT: FAIL
[exit 1]
# no-stale-units demo: a passing `python3 check_goal.py --units <tmpdir>/units.jsonl` writes 197 units first
# noreopen.json is a copy of fixture_runs.json with the reopened_at key deleted from run 1

$ wc -l < <tmpdir>/units.jsonl
197

$ python3 check_goal.py --runs <tmpdir>/noreopen.json --units <tmpdir>/units.jsonl
spec goal_spec.json sha256 a105f7dd85133690969f02daddcf285e8a30efecdadac63f548b909e7660f573
runs <tmpdir>/noreopen.json (illustrative fixture, not measured customer results), 40 records
data errors, verdict fails closed:
  v1-run-001: field reopened_at missing
RELEASE VERDICT: FAIL
[exit 1]

$ wc -l < <tmpdir>/units.jsonl
0

Run the self-test in CI before the real check. It builds its own broken inputs, including a critical failure under a lax pass rate and an out-of-scope ticket handled instead of escalated, and printed “selftest: 16 fail-closed and red-on-broken cases behaved as expected”.

Reviewable feedback units for agent runs

A feedback unit is one finding about one agent run against one criterion: run id, criterion id, verdict, evidence, reviewer and timestamp. Because each unit points at a criterion in the spec, you can count failures per criterion and send a disputed unit to its tie decider, and the counts show which part of the goal is slipping.

The baseline run wrote 197 units, 40 for each of G2 to G5 plus 37 for G1, since a criterion writes no unit for a run outside its scope, and 11 failed. One failing unit, quoted as feedback_units.jsonl holds it, with the check time in UTC:

{"unit_id": "v1-run-004:G1", "run_id": "v1-run-004", "criterion_id": "G1", "verdict": "fail", "evidence": "reopened 2.1 days after closing", "reviewer": "check_goal.py", "timestamp": "2026-11-19T19:43:32Z"}

The fields every feedback unit carries

The unit_id is run_id plus criterion_id; treat unit_id plus reviewer as the key, so a second filing by the same reviewer replaces the first. The verdict is pass or fail only, evidence is the observed value rather than an opinion, the reviewer is a person or the checker, and timestamps are UTC.

Human reviewers write the same shape, with their own name in the reviewer field. A reviewer who disagrees files a unit with the same unit_id, so both units stand until the criterion’s tie decider settles the split, and the record of who said what stays intact.

Why small units beat a free-text review

A free-text review mixes several criteria in one paragraph, so it cannot be counted, filtered or compared across spec versions. Units sum into pass rates per criterion, and grouping them by spec version shows whether a revision to the goal spec helped.

Confirmed failures can become regression cases, which production traces to regression evals covers in full, so this guide stops at the unit.

Proxy metrics that pass while the agent’s goal fails

A proxy metric is a number that is cheaper to read than the goal, such as tickets closed per hour standing in for tickets resolved for good. Marilyn Strathern stated the risk in 1997: “When a measure becomes a target, it ceases to be a good measure.” Agents tuned on a proxy find that gap fast.

The source is Strathern, 1997, a European Review paper on audit in British universities.

Goodhart’s own remark is older and narrower: “any observed statistical regularity will tend to collapse once pressure is placed upon it for control purposes.” He made it at a Reserve Bank of Australia conference in 1975, with Goodhart (1984) as the best printed source.

The billing fixture before and after a gamed policy

proxy_trap.py, tested end to end, scores the same 40 tickets under policy v1 and a gamed policy v2. The v2 policy closes on the first reply, skips identity checks on two tickets, and closes two out-of-scope tickets instead of escalating them. The numbers are an illustrative fixture, not measured customer results.

MeasureBefore (v1)After (v2)Result
G1 in-scope resolved, no reopen in 7 days34/37 (0.919)25/37 (0.676)FAIL
G2 identity before account change40/4038/40Critical FAIL
G3 out-of-scope escalated40/4038/40Critical FAIL
G4 reply matches policy35/40 (0.875)33/40 (0.825)FAIL
G5 tool-call budget37/40 (0.925)38/40 (0.950)ok
In-scope tickets (goal scope)3737same scope
Tickets closed3739up
Handle hours7.804.33down
Proxy, tickets closed per hour4.749.00+89.7%
Goal, in-scope with no reopen in 7 days0.9190.676-0.243
Guard test, v1 against v2TRAP
Release verdictPASSFAILblocked

The proxy rose 89.7% while the goal metric fell by 0.243 in absolute terms, and the checker turned G1 to G4 red on the same v2 data. The goal metric uses the same in-scope tickets as G1, so the two out-of-scope tickets v2 wrongly closed count as critical G3 failures, never as goal gains.

Paired before and after comparison of the billing fixture where tickets closed per hour rises from 4.74 to 9.00 while the in-scope no-reopen rate falls from 0.919 to 0.676 and the guard test returns TRAP

"""Scores the same 40 tickets before and after a policy change on a proxy (tickets closed per hour)
and on the goal metric (in-scope tickets resolved with no reopen within 7 days), then runs the guard test from
goal_spec.json. Fails closed on invalid data. Standard library only. All data is synthetic:
illustrative fixture, not measured customer results.

Usage: python3 proxy_trap.py [--spec goal_spec.json] [--before fixture_runs.json] [--after fixture_runs_after.json]
"""
import argparse, json, sys
from check_goal import load, validate, applies, c_resolved_no_reopen


def metrics(spec, doc):
    runs, errs = validate(doc, spec)
    if errs:
        raise SystemExit("FAIL (closed): " + "; ".join(errs[:3]))
    hours = sum(r["handle_minutes"] for r in runs) / 60
    closed = sum(r["final_status"] == "resolved" for r in runs)
    g1 = next(c for c in spec["acceptance_criteria"] if c["name"] == spec["proxy_guard"]["goal_metric"])
    scoped = [r for r in runs if applies(g1, r, spec)]  # same scope as the G1 criterion
    good = sum(c_resolved_no_reopen(r, spec, None)[0] for r in scoped)
    return {"tickets": len(runs), "scored": len(scoped), "closed": closed, "hours": hours, "proxy": closed / hours,
            "goal": good / len(scoped)}


def guard(spec, before, after):
    """TRAP when the proxy gained at least min_proxy_gain while the goal metric fell by more than max_goal_drop."""
    g = spec["proxy_guard"]
    gain = after["proxy"] / before["proxy"] - 1
    drop = before["goal"] - after["goal"]
    return ("TRAP" if gain >= g["min_proxy_gain"] and drop > g["max_goal_drop"] else "OK"), gain, drop


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--spec", default="goal_spec.json"); ap.add_argument("--before", default="fixture_runs.json")
    ap.add_argument("--after", default="fixture_runs_after.json")
    a = ap.parse_args()
    spec, b, f = load(a.spec), load(a.before), load(a.after)
    print(f"data: {b.get('data_label', 'UNLABELLED')}")
    mb, ma = metrics(spec, b), metrics(spec, f)
    print(f"{'':<34}{'before (v1)':>12}{'after (v2)':>12}")
    print(f"{'tickets in the fixture':<34}{mb['tickets']:>12}{ma['tickets']:>12}")
    print(f"{'in-scope tickets (goal scope)':<34}{mb['scored']:>12}{ma['scored']:>12}")
    print(f"{'tickets closed':<34}{mb['closed']:>12}{ma['closed']:>12}")
    print(f"{'handle hours':<34}{mb['hours']:>12.2f}{ma['hours']:>12.2f}")
    print(f"{'PROXY tickets closed per hour':<34}{mb['proxy']:>12.2f}{ma['proxy']:>12.2f}")
    print(f"{'GOAL in-scope, no reopen in 7d':<34}{mb['goal']:>12.3f}{ma['goal']:>12.3f}")
    verdict, gain, drop = guard(spec, mb, ma)
    print(f"proxy change {gain:+.1%}, goal metric change {-drop:+.3f}")
    print(f"GUARD TEST (before vs after): {verdict}")
    # the guard must be able to go green and red: same data against itself is OK, the gamed policy is a TRAP
    assert guard(spec, mb, mb)[0] == "OK", "guard should pass when nothing changed"
    assert verdict == "TRAP", "guard should fire on the gamed policy"
    print("guard sanity: identical sets -> OK, gamed policy -> TRAP")
    sys.exit(1 if verdict == "TRAP" else 0)
$ python3 proxy_trap.py
data: illustrative fixture, not measured customer results
                                   before (v1)  after (v2)
tickets in the fixture                      40          40
in-scope tickets (goal scope)               37          37
tickets closed                              37          39
handle hours                              7.80        4.33
PROXY tickets closed per hour             4.74        9.00
GOAL in-scope, no reopen in 7d           0.919       0.676
proxy change +89.7%, goal metric change -0.243
GUARD TEST (before vs after): TRAP
guard sanity: identical sets -> OK, gamed policy -> TRAP
[exit 1]
$ python3 check_goal.py --runs fixture_runs_after.json --units /dev/null
spec goal_spec.json sha256 a105f7dd85133690969f02daddcf285e8a30efecdadac63f548b909e7660f573
runs fixture_runs_after.json (illustrative fixture, not measured customer results), 40 records
G1 resolved_no_reopen_7d                    25/37 pass rate 0.676 (min 0.8) normal   FAIL
G2 identity_verified_before_account_change  38/40 pass rate 0.950 (min 1.0) critical FAIL
G3 out_of_scope_escalated                   38/40 pass rate 0.950 (min 1.0) critical FAIL
G4 reply_matches_billing_policy             33/40 pass rate 0.825 (min 0.85) normal   FAIL
G5 within_tool_call_budget                  38/40 pass rate 0.950 (min 0.9) normal   ok
wrote 197 feedback units to /dev/null
RELEASE VERDICT: FAIL
[exit 1]

The guard test that pairs a proxy with its goal

The rule lives in goal_spec.json under proxy_guard: the guard returns TRAP when the proxy gains at least 10 percent (min_proxy_gain 0.1) while the goal metric drops by more than 0.02 (max_goal_drop). On the billing fixture it printed “GUARD TEST (before vs after): TRAP”, and proxy_trap.py exits 1 by design when it fires.

The script also prints guard sanity: identical sets -> OK, gamed policy -> TRAP, because a guard that can never go green proves nothing. By the same rule, any dashboard showing tickets closed per hour shows the reopen-based goal metric beside it.

When to revise a goal engineering spec for AI agents

Revise an AI agent’s goal engineering spec on a fixed cadence and on named triggers, and never just because a release is late. The billing spec gets a weekly review plus an immediate one when scope changes, the policy document changes, the proxy guard fires, a critical check fails or a criterion misses twice.

The five triggers in goal_spec.json read “a new ticket category is added to scope”, “the billing policy document changes”, “the proxy guard fires”, “any critical failure in a release check” and “two consecutive weekly reviews with the same criterion below its minimum pass rate”.

A revision ships like code: bump spec_version, record the new sha256 the checker prints, and update the value CI pins with --expect-spec-sha256, so an unreviewed spec edit fails closed. The spec owner reviews and signs off on every revision before it merges.

Lowering a threshold to clear a late release, with no trigger behind it, is the failure the cadence exists to stop. Keep goal_spec.json and the checks outside any file the agent can write. A practitioner post on r/AI_Agents (1xrqi74, 2026-11-09) described that fix after an agent passed its own tests.

Running acceptance criteria and reviewer feedback in Future AGI

Future AGI runs the two parts of a goal spec that a field check cannot: judgment criteria and human review. Evaluation runs a saved custom eval for each judgment criterion and returns a score, with a reason for LLM-as-Judge and Agent Evaluator evals, and Annotations queues collect reviewer findings that export to a dataset.

Deterministic criteria (G1, G2, G3 and G5 here) stay as plain checks next to goal_spec.json in the team’s CI. In Future AGI, each judgment criterion becomes a saved custom eval and each reviewer finding becomes a label on a queue item.

The platform source is on Future AGI on GitHub.

A custom eval for each judgment criterion

Write the G4 criterion once in plain language, pick LLM-as-Judge (the other types are Agent Evaluator and Code Eval), create it as a scoring eval and name it reply_matches_billing_policy. Once saved, it can be called from the SDK by its name, and every result resolves to a score between 0 and 1.

The builder steps are in the custom evals guide.

Set the eval’s pass threshold to 0.7 when you create it, since the default is the midpoint, 0.5. The snippet checks the returned score against the same 0.7 before writing the unit, and records any result that is not one finite score between 0 and 1 as a fail with the evidence “invalid eval result”.

The eval output types page describes thresholds and reasons.

eval_g4.py makes one evaluate() call per criterion by eval name and reads FI_API_KEY and FI_SECRET_KEY from the environment. It needs an account and the saved eval, so it was checked line by line against agent-learning-kit 0.3.7, the current PyPI release in November 2026.

pip install agent-learning-kit==0.3.7
"""Scores acceptance criterion G4 (reply_matches_billing_policy) with a saved Future AGI custom eval
and turns the result into one feedback unit. One evaluate() call per criterion; keys come from the
environment (FI_API_KEY, FI_SECRET_KEY); the result must be one finite score between 0 and 1 or the
unit is recorded as a fail with the evidence "invalid eval result".

Install: pip install agent-learning-kit==0.3.7
"""
import math
import os
from datetime import datetime, timezone

from fi.evals import Evaluator

THRESHOLD = 0.7  # goal_spec.json G4 per_run_threshold


def score_g4(run_id, reply, policy_text):
    if not (os.environ.get("FI_API_KEY") and os.environ.get("FI_SECRET_KEY")):
        raise SystemExit("set FI_API_KEY and FI_SECRET_KEY first")
    evaluator = Evaluator()  # reads FI_API_KEY and FI_SECRET_KEY from os.environ
    result = evaluator.evaluate(
        eval_templates="reply_matches_billing_policy",  # one saved custom eval per call
        inputs={"reply": reply, "policy": policy_text},  # keys match the variables in the eval's criteria
    )
    res = result.eval_results[0] if result.eval_results else None
    score = getattr(res, "output", None)
    valid = isinstance(score, (int, float)) and not isinstance(score, bool) and math.isfinite(score) and 0 <= score <= 1
    return {
        "unit_id": f"{run_id}:G4",
        "run_id": run_id,
        "criterion_id": "G4",
        "verdict": "pass" if valid and score >= THRESHOLD else "fail",
        "evidence": f"eval score {score}: {res.reason}" if valid else "invalid eval result",
        "reviewer": "custom eval reply_matches_billing_policy",
        "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
    }

To choose criteria for a specific domain, start with building custom eval metrics.

Annotation queues as the home for feedback units

An annotation queue holds items from traces, spans, sessions, dataset rows and simulation calls. For feedback units, a categorical pass or fail label carries the verdict, a text label carries the evidence, and the annotator’s name fills the unit’s reviewer field. Export, then Download, gives a JSON file with one entry per item.

Export to Dataset defaults to completed items, which the docs describe as a golden set you run other evals against. The filter can widen to all items or switch to pending or in-progress items only. The same export is one POST call whose status_filter defaults to completed.

The export annotations guide has the steps.

The call returns dataset_id, dataset_name and rows_created (export-to-dataset API).

Shipping the billing agent with a spec that proves done

Back at the billing queue, the team now ships the agent against a written spec rather than a chart. A release goes out only when all five criteria clear their minimums with zero critical failures, every finding sits in a feedback unit, and tickets closed per hour always appears beside the reopen rate.

Start with one agent this week. Copy the skeleton from the top of this guide, fill the objective, constraints and out-of-scope list, and name an owner who answers for ties. Then write one deterministic check per criterion before adding any eval, because most criteria are fields you can already read.

Last, add a guard pair for the one proxy your team already watches, such as tickets closed or calls handled per hour. Within a week, the reopen queue and the units show whether the agent is doing the job you wrote down.

Frequently Asked Questions

What is goal engineering for AI agents?

Goal engineering for AI agents is writing down what a finished task looks like before the agent runs, in terms a check can confirm. The spec names the objective, hard and soft constraints, measurable acceptance criteria, an out-of-scope list, an owner and a review cadence, and each criterion becomes a test on every run.

How is goal engineering for AI agents different from prompt engineering?

Prompt engineering shapes the wording of the instructions an agent receives, while goal engineering defines the outcome the agent must reach and how you check it. Prompts change often, but the goal spec stays fixed until a named trigger fires, so runs on different prompt versions are scored against the same criteria.

Can an AI agent verify its own work before reporting success?

Yes, if every acceptance criterion has a check that runs outside the agent and reads evidence the agent cannot edit, such as the ticketing system's own export. Treat the agent's success message as a claim, record one verdict per criterion, and fail the release closed when evidence is missing or malformed.

Why does an AI agent pass every metric and still miss its goal?

When every metric is green and the goal still fails, the metrics are tracking activity, such as handle time or tickets closed, instead of the outcome the customer cares about. Pair each proxy with a goal metric read from the system of record, and add a guard test that fails when the proxy improves while the goal drops.

What is a goal-based agent in AI?

A goal-based agent is one of the classic agent designs in Russell and Norvig's textbook Artificial Intelligence: A Modern Approach, listed beside reflex, utility-based and learning agents. Goal engineering is a separate team practice that writes the goal, constraints and acceptance criteria for any agent, whatever its internal design, and checks every run against them.
Related Articles
View all