diff --git a/pyproject.toml b/pyproject.toml index 462400a97..e63aa7779 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -196,6 +196,7 @@ echo-mcp = "agent_env.examples" mail-mcp = "agent_env.examples" next-env-event = "agent_env.examples" advance-to-next-event = "agent_env.examples" +milestone-gates = "agent_env.examples" [project.urls] Homepage = "https://www.agentenvframework.com" diff --git a/src/agent_env/examples/milestone-gates/README.md b/src/agent_env/examples/milestone-gates/README.md new file mode 100644 index 000000000..12c21eeef --- /dev/null +++ b/src/agent_env/examples/milestone-gates/README.md @@ -0,0 +1,111 @@ +A prompt_agent post-turn hook that runs a multiturn task as a chain of milestones, each blocked by a few gates checked +while the conversation runs, and tells the user sim what it found. + +`artifacts/milestone-gates/hook.py` is the hook. After each agent turn it runs the open milestone's gates against the +env and the agent's own work, then asks the user side with a note only the user sim sees (`turn.ask_user(note=...)`; +the agent never sees it): + +- every gate passes: the milestone is done, and the note opens the next one with its `line`, or asks the user sim to + wrap up after the last; +- a gate fails: the note carries that gate's `nudge`, which the task author writes and keeps vague (where to look, never + the value), and the turn counts toward the milestone's `max_nudges`; +- still failing after `max_nudges` turns: a `blocking` milestone ends the conversation (`gate_never_passed:`), any + other is let go and the next one opens; +- no gate could be checked at all (say, a turn's trajectory wasn't fetched): the user sim is asked to stay on the + milestone, and the turn counts toward `max_nudges`, so evidence that never arrives ends in the usual give-up. + +The user sim words every message; the hook decides only where the conversation is. A user sim that moves on by itself +(its message carries a later milestone's `line`) is followed. When a milestone passes, later ones the agent has already +done are skipped. The conversation ends with `milestones_done` once the wrap-up is answered, or with `sim_idle` when +the user sim sends the same message `idle_end` turns in a row. + +Gates are cheap first: code and tool-state checks run before any judge, and a judge runs only when they pass. A judge +that can't answer after one retry leaves its gate unknown, which neither fails nor nudges. + +```json +{"id": "talk", "type": "prompt_agent", "prompt": "Make me a sheet of every active subscription.", + "user_agent_name": "user", "max_conversation_turns": 20, + "post_turn_hooks": [{"file_artifact_id": "@local/agentenv-framework/milestone-gates/milestone-gates", "params": { + "role": "admin", + "milestones": [ + {"id": "M1", "max_nudges": 3, "blocking": true, + "artifacts": {"sheet": {"find": {"tool": "drive_list", "path": "files", "where": {"name": "subscriptions"}}}}, + "gates": [ + {"id": "m1-sheet", "nudge": "I don't see the sheet yet.", "check": {"artifact": "sheet", "expect": "exists"}}, + {"id": "m1-quiet", "nudge": "Hold off on emailing anyone.", + "check": {"no_new": [{"tool": "gmail_sent", "path": "messages", "baseline_count": 0}]}}]}, + {"id": "M2", "line": "Now put what you found on the cut-list card. Don't email anyone yet.", + "gates": [ + {"id": "m2-comment", "nudge": "Did the comment go on the card?", + "check": {"trajectory_judge": "During this step the assistant adds one comment to the cut-list card."}}]}]}}]} +``` + +The gates are opt-in: a task runs them only when a `prompt_agent` step lists the hook in `post_turn_hooks`, and no +other step or task is affected. `"enabled": false` switches them off while keeping the milestones in the task, for a +run with and without gates: the hook still checks its params, but runs no gate and sends the user sim no note, so +the conversation goes as if no hook were listed. It records `disabled` once. + +Params: + +- `enabled`: `true` by default; `false` switches the gates off, as above. +- `milestones`: `[{id, line?, type?, blocking?, max_nudges?, skip_if_done?, show?, artifacts, gates}]`, in order. `line` + is what the user sim sends to open the milestone (the first one's is the step's prompt). `show` names an artifact + whose start goes in a nudge's note, so the user sim can react to what it "opened". `type: "correct"` is never + skipped. +- `role`: the env role the gates read as; it needs read access to everything they check. +- `env`: the deployed env's `env_id` to read; the first deployed env by default. +- `judge_model`: the model for `judge` gates on an artifact. `trajectory_judge_model`: the model for `trajectory_judge` + gates; a small model misreads long logs, so pick a strong one. +- `trajectory_max_chars`: the most rendered trajectory one judge call gets (600000 by default); the oldest turns before + the open milestone are cut first. +- `excerpt_chars` (600), `final_note`, `idle_end` (2; 0 never ends on it). + +A gate is `{id, nudge, check}`. The check kinds, by the gate types of a multiturn task: + +| Gate type | Check | What it reads | +|---|---|---| +| format | `{"artifact": name, "format": {max_paragraphs, max_sentences, contains_all, contains_none}}` | the artifact's text, by code | +| action | `{"call": call, "expect": expect}` | a read tool's result: `"exists"`, `{"count": {"eq"/"min"/"max": n}}`, `{"contains": text}`, `{"equals": value}` | +| action | `{"artifact": name, "expect": "exists"}` | the artifact was found | +| action | `{"no_new": [call + {baseline_count?}]}` | nothing added since the milestone opened | +| content | `{"artifact": name, "judge": "statement"}` | one model call over the artifact's text | +| content | `{"trajectory_judge": "statement"}` | one model call over the agent's work: every turn's trajectory so far, writes in full, reads shortened, the open milestone's turns marked `THIS STEP` | + +A call is `{tool, args?, path?, where?, number?}`: `path` is a dotted path into the tool's JSON result, `where` keeps +list items whose fields contain the given text, `number` reads a count the tool reports. An artifact is +`{find: call + {pick?: "first" | "last"}, read?: {tool, args, extract?}, field?}`: `read` args may use `"{field}"` +from the item `find` picked, and `extract: "gmail"` turns a Gmail API message into its headers and plain-text body. +Without `read`, `field` (a dotted path) takes that field of the picked item as the artifact's text, such as a draft's +`body`; otherwise the text is the whole item as JSON, where a format check would count escaped line breaks. + +The params are checked when the step loads the hook, before the first message (the hook's `check_params`): unknown +keys on a milestone or gate, a check that isn't exactly one kind or lacks what its kind needs, an artifact a milestone +doesn't define, a gate `type` outside format, action and content, repeated gate or milestone ids, and a judge gate +with no judge model each fail the step there. Without this, a malformed check would fail as a gate on every turn and +nudge the agent about nothing. + +After the wrap-up has been answered, the hook checks the last milestone once more and records it, so the summary matches what the agent left: work it changed while answering the wrap-up counts. If any milestone was let go, the wrap-up note (`final_note_gave_up`) asks the user sim to wrap up without saying everything is done and without taking on anything new. + +After every turn the hook also sets its summary of where the conversation got to, for a verifier or the hub to read +without going through its records (`turn.summarize`), at +`metadata["post_turn_hook_summaries"][step_id][""]`: + +```json +{"enabled": true, "reached": "M2", "done": 2, "total": 2, "end": "milestones_done", + "milestones": [{"id": "M1", "status": "passed", "opened_turn": 1, "closed_turn": 1, "nudges": 0, + "gates": {"m1-draft": {"passed": true, "type": "action"}, "m1-short": {"passed": true, "type": "format"}}}]} +``` + +A milestone's `status` is `not_reached`, `open`, `passed`, `skipped` (done before it opened), `gave_up` (let go after +`max_nudges`), `passed_over` (the user sim moved past it) or `derailed` (a blocking one that never passed, which ended +the conversation: `end` is then `gate_never_passed:`). A gate's `type` follows its check, as in the table above. +`end` stays null when the conversation ended some other way, such as running out of turns. Switched off, the summary +is `{"enabled": false}`. + +The hook keeps its state in its own records (`metadata["post_turn_hooks"]`): each turn's milestone, every gate's +verdict and reason, the decision (passed, nudge, hold, gave_up, end) and the user sim's answer. `trajectory_judge` +gates need the agent to offer per-turn trajectories (`turn.trajectory_urls`); without them those gates are unknown. + +The user sim should treat the note as what it found when it checked, and never judge "done" itself: the hook ends the +conversation. A hook runs in the control-plane process with the trust of an `env_outcome_verifier` script, and its +model calls are not in the step's usage. diff --git a/src/agent_env/examples/milestone-gates/artifacts/milestone-gates/hook.py b/src/agent_env/examples/milestone-gates/artifacts/milestone-gates/hook.py new file mode 100644 index 000000000..60dd555e4 --- /dev/null +++ b/src/agent_env/examples/milestone-gates/artifacts/milestone-gates/hook.py @@ -0,0 +1,879 @@ +"""milestone-gates: a prompt_agent post-turn hook that checks each milestone's gates while the conversation runs. + +After every agent turn it runs the open milestone's gates against the env (tool state, the artifact's text, and one +LLM judge call for a content gate), then tells the user sim what it found in a note only the sim sees +(``turn.ask_user(note=...)``): +- all gates pass: the milestone is done; the note opens the next one, or asks the sim to wrap up after the last; +- a gate fails: the note carries that gate's nudge, written by the task author and vague on purpose; +- a gate still fails after ``max_nudges`` failing turns: a blocking milestone ends the conversation + (``gate_never_passed:``); any other is let go and the next one opens. +Every turn that ends with a failing gate counts toward ``max_nudges``, whether or not the sim pressed on it. + +The hook follows the sim: when the sim's answer opens a later milestone (its message carries that milestone's +``line``, or the sim reports it in a ``milestone`` field), the hook moves there before the agent acts, taking that +milestone's no_new baselines then. And when the sim sends the same message ``idle_end`` turns in a row, it has nothing +left to ask: the agent still gets that message (a hook that asked returns its answer), and the conversation +ends at the start of the next turn (``sim_idle``). + +A judge gate that can't get an answer (after one retry) is unknown (``passed`` None): it neither fails nor nudges. + +The sim words every message; the hook only decides where the conversation is. See the README beside this bundle. + +Params: + role the env role the gates read as (needs read access to everything they check) + env the deployed env's env_id to read (default: the first deployed env) + judge_model model for an artifact's judge gates (needed when one is used) + excerpt_chars how much of a milestone's ``show`` artifact goes in the note (default 600) + final_note the note after the last milestone passes, when every milestone passed + final_note_gave_up the note after the last milestone when one was let go (never says everything is done) + idle_end end after the sim sends the same message this many turns in a row (default 2; 0 = never) + trajectory_judge_model model for trajectory_judge gates (needed when one is used; a small model misreads long + logs) + trajectory_max_chars the most rendered trajectory one judge call gets (default 600000); the oldest turns + before the open milestone are cut first + milestones [{id, line?, type?, skip_if_done?, blocking?, max_nudges?, show?, artifacts: {name: artifact}, + gates: [gate]}] + ``line`` is the text the sim sends to open the milestone, used to tell when it has moved on. + When a milestone is done, each next one the agent has already done is skipped (its gates all pass + then, at least one of them on something the agent made): the note tells the sim to skip its line. + ``skip_if_done: false`` turns that off for a milestone; type ``correct`` is never skipped. + +A gate is {id, nudge, check}, with check one of: + {"trajectory_judge": "statement"} one LLM call: is the statement true of the agent's work, read from its + trajectory (every turn so far, rendered compactly: writes in full, + reads shortened; the open milestone's turns marked THIS STEP). Needs + the framework to hand hooks ``turn.trajectory_urls``; without them the + gate is unknown. A task's rubric criteria can be used as they are. + {"call": call, "expect": expect} a read tool's result meets ``expect`` + {"artifact": name, "expect": "exists"} the artifact was found + {"artifact": name, "format": {...}} code over the artifact's text: max_paragraphs, max_sentences, + contains_all [text, ...], contains_none [text, ...] + {"artifact": name, "judge": "statement"} one yes/no LLM call: is the statement true of the artifact's text + {"no_new": [call + {"baseline_count"?}]} no item added since the milestone opened (the first milestone, + which opens before the hook first runs, needs ``baseline_count``) +A call is {tool, args?, path?, where?, number?}: ``path`` is a dotted path into the tool's JSON result, ``where`` +keeps the list items whose fields contain the given text, and ``number`` reads a count the tool reports (that field of +the first item) instead of counting the list. ``expect`` is "exists", or {"count": {"eq"|"min"|"max": n}}, +{"contains": text} or {"equals": value}. +An artifact is {find: call + {pick?: "first"|"last"}, read?: {tool, args, extract?}, field?}: ``read`` args may use +"{field}" from the item ``find`` picked, and ``extract: "gmail"`` turns a Gmail API message into its headers and +plain-text body; without ``read``, ``field`` (a dotted path) takes that field of the picked item as its text, else the +artifact's text is the picked item itself, as JSON. +""" +from __future__ import annotations + +import json +import re +from typing import Any, Optional + +# When none of the open milestone's gates could be checked: the sim stays on it, and it counts toward max_nudges, so a +# milestone whose evidence never arrives is let go (or ends the run, if blocking) instead of holding forever. +HOLD_NOTE = ("Nothing could be checked this time. Don't move on: reply to what the assistant said, and stay on the " + "milestone you're on.") +MILESTONE_KEYS = {"id", "line", "type", "skip_if_done", "blocking", "max_nudges", "show", "artifacts", "gates"} +DEFAULT_FINAL = "Everything you asked for is done. Wrap up the way you planned (send your last line), then stop." +# The wrap-up after a milestone was let go: nothing claims it was all done, and the user takes on nothing new. +DEFAULT_FINAL_GAVE_UP = ("Wrap up now: send your last line, then stop. Don't say everything is done, and don't ask " + "for or agree to anything new.") +JUDGE_SYSTEM = ("You check one statement against a document. Use only the document. Answer passed=true only if the " + "document clearly shows the statement is true. Keep why to one sentence of at most 30 words.") +TRAJECTORY_JUDGE_SYSTEM = ( + "You check one statement about what an AI assistant did, against a log of its work: every tool call it made with " + "the result, its writes in full and its reads shortened, and what it said. Judge only from the log. Turns marked " + "THIS STEP are what the statement means by 'this step' or 'during this step'; earlier turns are context, such as " + "what the assistant made before. Judge what the statement is checking, the way a careful reviewer would read it: " + "mentioning something only to exclude it or say it doesn't apply doesn't fail a statement about what is " + "included. Answer passed=true only if the log clearly shows the statement is true. Keep why to one sentence of at " + "most 30 words.") +JUDGE_FORMAT = {"type": "json_schema", "json_schema": {"name": "gate", "strict": True, "schema": { + "type": "object", "additionalProperties": False, "required": ["passed", "why"], + "properties": {"passed": {"type": "boolean"}, "why": {"type": "string"}}}}} + + +def check_params(params): + """Called by the framework when the hook loads, before the conversation starts: refuse params the hook can't run + with, so the step fails before the first message instead of after the agent's first turn.""" + _spec(params) + + +async def post_turn(turn, params): + spec = _spec(params) + answer = await _post_turn(turn, spec) + if hasattr(turn, "summarize"): # a framework older than Turn.summarize keeps only the records + turn.summarize(_summary(spec, turn.records())) + return answer + + +async def _post_turn(turn, spec): + if not spec["enabled"]: # configured but switched off: the conversation runs as if no hook were listed + if not turn.records(): + turn.record({"decision": "disabled"}) + return None + state = _state(turn.records()) + milestones = spec["milestones"] + if state["finished"]: # the wrap-up was sent and the agent has answered it + # Check the last milestone once more: the agent may have changed its work while answering the wrap-up, and + # the summary should match what it left, as the task's final rubric will. + m = milestones[state["index"]] + gates = await _run_gates(turn, spec, _env(turn, spec), m, state) + turn.record({"decision": "done", "milestone": m["id"], "gates": gates}) + return {"end": "milestones_done"} + if state["idle"]: # the sim repeated itself last turn; the agent has answered that, so end before asking again + turn.record({"decision": "end", "end": "sim_idle"}) + return {"end": "sim_idle"} + m = milestones[state["index"]] + env = _env(turn, spec) + gates = await _run_gates(turn, spec, env, m, state) + failed = [g for g in gates if g["passed"] is False] + entry = {"milestone": m["id"], "gates": gates} + checks = {g["id"]: g["check"] for g in m["gates"]} + # Unknown: no gate checked at all, or a tool/state gate (not a judge) that couldn't be checked, such as a no_new + # gate whose baseline couldn't be read. Either way the milestone isn't shown done. A judge that can't answer + # doesn't hold it up (see _judge). + unchecked = bool(gates) and (all(g["passed"] is None for g in gates) or any( + g["passed"] is None and not _costly(checks[g["id"]]) for g in gates if g["id"] in checks)) + if turn.last: # nothing more can be asked: record where it stood, passed if its gates passed on this turn + turn.record({**entry, "decision": "last_turn", "nudges": state["nudges"], + "passed": not failed and not unchecked}) + return None + if not failed and not unchecked: + return await _advance(turn, spec, env, state, entry, "passed") + if state["nudges"] >= m["max_nudges"]: + if m["blocking"]: + end = f"gate_never_passed:{m['id']}" + turn.record({**entry, "decision": "end", "end": end, "nudges": state["nudges"]}) + return {"end": end} + return await _advance(turn, spec, env, state, entry, "gave_up") + if failed: + note = failed[0]["nudge"] + await _excerpt(turn, spec, env, m, state) + else: # no gate could be checked (say, the turn's trajectory wasn't fetched): hold, without a nudge on nothing + note = HOLD_NOTE + answer = await turn.ask_user(note=note) + record = {**entry, "decision": "nudge" if failed else "hold", "note": note, "nudges": state["nudges"] + 1, + "sim_nudged": _sim_field(turn, "nudged")} + return await _after_answer(turn, spec, env, state, record, answer, state["index"]) + + +async def _after_answer(turn, spec, env, state, record, answer, expected): + """Record the sim's answer, follow it to a later milestone if it opened one, and end if it has gone idle.""" + message = _answer_text(answer) + record["sim_message"] = message[:300] + moved = _sim_milestone(turn, spec, message) + if moved is not None and moved > expected: + record.update(followed_sim=spec["milestones"][moved]["id"], next_index=moved, wrap_up=False, + baselines=await _baselines(env, spec, spec["milestones"][moved])) + idle = spec["idle_end"] + if idle >= 2 and message.strip(): + before = [r.get("sim_message") for r in turn.records() if "sim_message" in r][-(idle - 1):] + if len(before) == idle - 1 and all(_same(b, message) for b in before): + # A hook that asked returns the answer, so the agent gets this message and the next turn ends. + record["idle"] = True + turn.record(record) + return answer + + +# ---- state --------------------------------------------------------------------------------------------------------- + +def _state(records: list[dict]) -> dict: + """Where the conversation is, from this hook's own records: the open milestone, nudges spent on it, the no_new + baselines taken when it opened, the turn its line first reached the agent (``since``), and whether the wrap-up + has gone out.""" + index, nudges, baselines, finished, idle, since = 0, 0, {}, False, False, 1 + for r in records: + idle = bool(r.get("idle")) + if r.get("next_index") is not None: # passed, let go, or followed the sim to a later milestone + index, nudges, baselines = r["next_index"], 0, r.get("baselines") or {} + finished = r.get("wrap_up", False) + if not finished: # the wrap-up keeps the last milestone's turns as the step a final check reads + since = int(r.get("turn", 0)) + 1 # its line goes to the agent in the next turn + elif r.get("decision") in ("nudge", "hold"): + nudges = r["nudges"] + return {"index": index, "nudges": nudges, "baselines": baselines, "finished": finished, "idle": idle, + "since": since} + + +def _gate_type(check: dict) -> str: + """A gate's type when the spec doesn't give one, from how it's checked: format (code over text), action (tool + state), content (a judge). A spec's ``type`` wins: a trajectory judge can check an action.""" + if "judge" in check or "trajectory_judge" in check: + return "content" + return "format" if "format" in check else "action" + + +def _summary(spec: dict, records: list[dict]) -> dict: + """Where the conversation got to, from this hook's records, for whoever grades it (Turn.summarize): each + milestone's status (not_reached, open, passed, skipped (done before it opened), gave_up (let go after max_nudges), + undone (done, then broken while the agent answered the wrap-up), + passed_over (the user sim moved past it), derailed (a blocking one that never passed, which ended the run)), the + turn it opened and closed, nudges spent, and each gate's last verdict and type; then the furthest milestone + reached, how many were done, and the end reason once the hook ended the conversation.""" + if not spec["enabled"]: + return {"enabled": False} + milestones = spec["milestones"] + types = {g["id"]: g.get("type") or _gate_type(g["check"]) for m in milestones for g in m["gates"]} + rows = [{"id": m["id"], "status": "not_reached", "opened_turn": None, "closed_turn": None, "nudges": 0, + "gates": {}} for m in milestones] + rows[0].update(status="open", opened_turn=1) + by_id = {r["id"]: r for r in rows} + end = None + + def verdicts(row, gates): + row["gates"].update({g["id"]: {"passed": g["passed"], "type": types.get(g["id"])} for g in gates}) + + for r in records: + turn, row = r.get("turn"), by_id.get(r.get("milestone")) + if row is not None: + verdicts(row, r.get("gates") or []) + decision = r.get("decision") + if decision in ("nudge", "hold"): + row["nudges"] = r.get("nudges", row["nudges"]) + elif decision in ("passed", "gave_up"): + row.update(status=decision, closed_turn=turn) + elif decision == "last_turn" and r.get("passed"): # done on the final turn, with nothing left to ask + row.update(status="passed", closed_turn=turn) + elif decision == "end" and r.get("end", "").startswith("gate_never_passed"): + row.update(status="derailed", closed_turn=turn, nudges=r.get("nudges", row["nudges"])) + for s in r.get("skipped") or []: + verdicts(by_id[s["milestone"]], s["gates"]) + by_id[s["milestone"]].update(status="skipped", opened_turn=turn, closed_turn=turn) + nxt = r.get("next_index") + if nxt is not None and not r.get("wrap_up"): + if r.get("followed_sim"): # the sim opened a later milestone itself: those before it are passed over + for skipped_over in rows[:nxt]: + if skipped_over["status"] in ("open", "not_reached"): + skipped_over.update(status="passed_over", closed_turn=turn) + if rows[nxt]["status"] == "not_reached": + rows[nxt].update(status="open", opened_turn=turn + 1) + if r.get("decision") == "done": + end = "milestones_done" + final = r.get("gates") or [] + if row is not None and final: + if all(g["passed"] for g in final) and row["status"] not in ("passed", "skipped"): + row.update(status="passed", closed_turn=turn) # done in the end, after the wrap-up + elif any(g["passed"] is False for g in final) and row["status"] in ("passed", "skipped"): + row.update(status="undone", closed_turn=turn) # done before, broken while answering the wrap-up + elif r.get("decision") == "end": + end = r.get("end") + reached = [row["id"] for row in rows if row["status"] != "not_reached"] + return {"enabled": True, "reached": reached[-1] if reached else None, + "done": sum(row["status"] in ("passed", "skipped") for row in rows), "total": len(rows), + "end": end, "milestones": rows} + + +async def _skips(turn, spec, env, state, nxt) -> tuple[int, list[dict]]: + """From milestone ``nxt`` on, the ones the agent has already done: every gate passes now, at least one of them + checks something the agent made (a no_new gate alone, its baselines taken now, proves nothing), and the milestone + may be skipped (``skip_if_done``, never type ``correct``, whose line is always sent). Returns the first milestone + not skipped and what each skipped one's gates found.""" + milestones, skipped = spec["milestones"], [] + while nxt < len(milestones): + m = milestones[nxt] + if not m["skip_if_done"] or m["type"] == "correct": + break + gates = await _run_gates(turn, spec, env, m, {**state, "baselines": await _baselines(env, spec, m)}) + made = [g for g in m["gates"] if "no_new" not in g["check"]] + if not made or not all(r["passed"] is True for r in gates): + break + skipped.append({"milestone": m["id"], "gates": gates}) + nxt += 1 + return nxt, skipped + + +async def _advance(turn, spec, env, state, entry, how): + """The open milestone is passed or let go: open the next one the agent hasn't already done (taking its no_new + baselines now, before the agent works on it), or send the wrap-up after the last.""" + milestones = spec["milestones"] + head = (f"{milestones[state['index']]['id']} isn't done, but let it go." if how == "gave_up" + else f"{milestones[state['index']]['id']} is done.") + nxt, skipped = await _skips(turn, spec, env, state, state["index"] + 1) + if skipped: + ids = ", ".join(s["milestone"] for s in skipped) + head += (f" {ids} {'is' if len(skipped) == 1 else 'are'} already done too, so skip " + f"{'its line' if len(skipped) == 1 else 'their lines'}.") + if nxt < len(milestones): + baselines = await _baselines(env, spec, milestones[nxt]) + line = milestones[nxt].get("line") + note = (f"{head} Open {milestones[nxt]['id']} now: send this line: {line}" if line + else f"{head} Open {milestones[nxt]['id']} now: send its line.") + record = {**entry, "decision": how, "next_index": nxt, "baselines": baselines, "note": note} + else: + let_go = how == "gave_up" or any(r.get("decision") == "gave_up" for r in turn.records()) + final = spec["final_note_gave_up"] if let_go else spec["final_note"] + note = (f"{head} " if how == "gave_up" or skipped else "") + final + # The final check after the wrap-up reads the last milestone: the open one, or the last one skipped as done + # (its baselines taken now, as the skip took them). + last = len(milestones) - 1 if skipped else state["index"] + baselines = state["baselines"] if last == state["index"] else await _baselines(env, spec, milestones[last]) + record = {**entry, "decision": how, "next_index": last, "wrap_up": True, "note": note, + "baselines": baselines} + if skipped: + record["skipped"] = skipped + answer = await turn.ask_user(note=note) + return await _after_answer(turn, spec, env, state, record, answer, record["next_index"]) + + +def _sim_field(turn, name) -> Any: + """The peer sim's own field for this turn (prompt_agent records extra JSON fields), or None.""" + outputs = (turn.metadata.get("usersim_turn_outputs") or {}) + step_id = getattr(turn, "step_id", None) # turn numbers restart in each prompt_agent step + for entries in ([outputs.get(step_id) or []] if step_id is not None else outputs.values()): + for e in entries: + if e.get("turn") == turn.number and name in (e.get("fields") or {}): + value = e["fields"][name] + return bool(value) if name == "nudged" else value + return None + + +def _answer_text(answer: Any) -> str: + if not isinstance(answer, dict): + return "" + return "\n".join(p.get("text", "") for p in answer.get("message") or [] if isinstance(p, dict)) + + +def _norm(text: str) -> str: + return re.sub(r"[^a-z0-9]+", " ", (text or "").lower()).strip() + + +def _same(a: Optional[str], b: str) -> bool: + return a is not None and _norm(a) == _norm(b[:300]) + + +def _sim_milestone(turn, spec, message) -> Optional[int]: + """The latest milestone the sim's message opens: one whose ``line`` it carries, else the one its ``milestone`` + field names. None when neither says.""" + said = _norm(message) + hits = [i for i, m in enumerate(spec["milestones"]) if m.get("line") and _norm(m["line"])[:120] in said] + if hits: + return max(hits) + field = _sim_field(turn, "milestone") + ids = [m["id"] for m in spec["milestones"]] + return ids.index(field) if isinstance(field, str) and field in ids else None + + +# ---- gates --------------------------------------------------------------------------------------------------------- + +async def _run_gates(turn, spec, env, m, state) -> list[dict]: + """Every tool, format and no_new gate; the judge gates only when all of those pass (they cost a model call).""" + artifacts: dict[str, Optional[str]] = {} + out = [] + for g in m["gates"]: + if _costly(g["check"]): + continue + out.append(await _gate(turn, spec, env, m, state, g, artifacts)) + cheap_ok = all(r["passed"] for r in out) + for g in m["gates"]: + if not _costly(g["check"]): + continue + if cheap_ok: + out.append(await _gate(turn, spec, env, m, state, g, artifacts)) + else: + out.append({"id": g["id"], "passed": None, "why": "not run: an earlier gate failed", "nudge": g["nudge"], + **({"type": g["type"]} if g.get("type") else {})}) + order = {g["id"]: i for i, g in enumerate(m["gates"])} + return sorted(out, key=lambda r: order[r["id"]]) + + +def _costly(check: dict) -> bool: + """A gate that costs a model call: run only when every other gate passes.""" + return "judge" in check or "trajectory_judge" in check + + +async def _gate(turn, spec, env, m, state, g, artifacts) -> dict: + check = g["check"] + try: + if "trajectory_judge" in check: + passed, why = await _trajectory_gate(turn, spec, state, check["trajectory_judge"]) + elif "call" in check: + passed, why = _expect(await _call(env, spec["role"], check["call"]), check["expect"]) + elif "no_new" in check: + passed, why = await _no_new(env, spec["role"], m, state, check["no_new"], g["id"]) + else: + text = await _artifact(env, spec["role"], m, check["artifact"], artifacts) + if text is None: + passed, why = False, f"artifact {check['artifact']!r} not found" + elif check.get("expect") == "exists": + passed, why = True, "found" + elif "format" in check: + passed, why = _format(text, check["format"]) + else: + passed, why = await _judge(spec, check["judge"], text) + except Exception as e: # noqa: BLE001 - a gate that can't be checked counts as failed, and says why + passed, why = False, f"error: {type(e).__name__}: {str(e)[:200]}" + return {"id": g["id"], "passed": passed, "why": why, "nudge": g["nudge"], + **({"type": g["type"]} if g.get("type") else {})} # format, action or content, when the spec says + + +async def _call(env, role, call) -> Any: + resp = await env.call_tool(call["tool"], call.get("args") or {}, role) + value = _result(resp) + for key in [k for k in (call.get("path") or "").split(".") if k]: + value = value[int(key)] if isinstance(value, list) else value[key] + where = call.get("where") + if where: + value = [item for item in value if all(str(v).lower() in str(_dig(item, k)).lower() for k, v in where.items())] + if call.get("number"): # a count the tool reports (the first item's field), not the length of a list + item = value[0] if isinstance(value, list) and value else value + value = int(_dig(item, call["number"]) or 0) if isinstance(item, dict) else 0 + return value + + +def _size(value: Any) -> int: + if isinstance(value, bool): + return int(value) + if isinstance(value, (int, float)): + return int(value) + return len(value) if isinstance(value, list) else (1 if value else 0) + + +def _result(resp: dict) -> Any: + """A /step call_tool response's content as JSON when it is JSON, else its text.""" + if isinstance(resp, dict) and resp.get("isError"): + raise RuntimeError(f"tool error: {_text(resp)[:200]}") + text = _text(resp) + try: + return json.loads(text) + except ValueError: + return text + + +def _text(resp: Any) -> str: + if isinstance(resp, dict) and isinstance(resp.get("content"), list): + return "\n".join(c.get("text", "") for c in resp["content"] if isinstance(c, dict)) + return resp if isinstance(resp, str) else json.dumps(resp) + + +def _dig(item: Any, dotted: str) -> Any: + for key in dotted.split("."): + item = item.get(key) if isinstance(item, dict) else None + return item + + +def _expect(value: Any, expect: Any) -> tuple[bool, str]: + if expect == "exists": + ok = bool(value) + return ok, "found" if ok else "nothing found" + if "count" in expect: + n = _size(value) + c = expect["count"] + ok = (c.get("eq") is None or n == c["eq"]) and (c.get("min") is None or n >= c["min"]) and \ + (c.get("max") is None or n <= c["max"]) + return ok, f"count {n}" + if "contains" in expect: + hay = value if isinstance(value, str) else json.dumps(value) + ok = expect["contains"].lower() in hay.lower() + return ok, ("contains " if ok else "missing ") + repr(expect["contains"]) + if "equals" in expect: + ok = value == expect["equals"] + return ok, f"value {value!r}" + raise ValueError(f"unknown expect {expect!r}") + + +def _baseline_key(m: dict, gate_id: str, i: int) -> str: + return f"{m['id']}:{gate_id}:{i}" + + +async def _no_new(env, role, m, state, calls, gate_id: str) -> tuple[Optional[bool], str]: + """Nothing added since the milestone opened. Unknown (None) when a baseline couldn't be read then: comparing + against nothing would be a guess.""" + added, missing = [], [] + for i, call in enumerate(calls): + base = state["baselines"].get(_baseline_key(m, gate_id, i), call.get("baseline_count")) + if base is None: + missing.append(call["tool"]) + continue + n = _size(await _call(env, role, call)) + if n > base: + added.append(f"{call['tool']} +{n - base}") + if added: # a failure another call found stands, whatever couldn't be compared + return False, "new: " + ", ".join(added) + if missing: + return None, f"unknown: no baseline for {', '.join(missing)} (it couldn't be read when {m['id']} opened)" + return True, "nothing new" + + +async def _baselines(env, spec, m) -> dict: + """Each no_new call's count when ``m`` opens, keyed by gate and call. A read that fails leaves its baseline + missing (its gate is then unknown), rather than failing the step over a temporary tool error.""" + out = {} + for g in m["gates"]: + for i, call in enumerate(g["check"].get("no_new") or []): + try: + out[_baseline_key(m, g["id"], i)] = _size(await _call(env, spec["role"], call)) + except Exception: # noqa: BLE001 - a missing baseline makes only this gate unknown + continue + return out + + +async def _artifact(env, role, m, name, cache) -> Optional[str]: + if name in cache: + return cache[name] + a = m["artifacts"][name] + found = await _call(env, role, a["find"]) + items = found if isinstance(found, list) else ([found] if found else []) + if not items: + cache[name] = None + return None + item = items[-1] if a["find"].get("pick", "last") == "last" else items[0] + if a.get("read"): + args = {k: (v.format(**item) if isinstance(v, str) and isinstance(item, dict) else v) + for k, v in (a["read"].get("args") or {}).items()} + resp = await env.call_tool(a["read"]["tool"], args, role) + if isinstance(resp, dict) and resp.get("isError"): # a failed read is not the artifact's text + raise RuntimeError(f"tool error reading {name!r}: {_text(resp)[:200]}") + text = _text(resp) + if a["read"].get("extract") == "gmail": + text = _gmail_text(text) + elif a.get("field") and isinstance(item, dict): # one field of the item, as its text (a draft's body) + value = _dig(item, a["field"]) + text = None if value is None else (value if isinstance(value, str) else json.dumps(value, indent=1)) + else: + text = item if isinstance(item, str) else json.dumps(item, indent=1) + cache[name] = text + return text + + +def _gmail_text(raw: str) -> str: + """A Gmail API message as a person reads it: subject, recipients, thread, then the plain-text body (base64url in + ``payload``, in the first text/plain part, else text/html with the tags dropped).""" + import base64 + msg = json.loads(raw) + payload = msg.get("payload") or {} + headers = {h.get("name", "").lower(): h.get("value", "") for h in payload.get("headers") or []} + + def parts(p): + yield p + for c in p.get("parts") or []: + yield from parts(c) + + def decode(p): + data = (p.get("body") or {}).get("data") or "" + return base64.urlsafe_b64decode(data + "=" * (-len(data) % 4)).decode("utf-8", "replace") if data else "" + + every = list(parts(payload)) + body = next((decode(p) for p in every if p.get("mimeType") == "text/plain" and decode(p)), "") + if not body: + html = next((decode(p) for p in every if p.get("mimeType") == "text/html" and decode(p)), "") + body = re.sub(r"<[^>]+>", " ", html) + head = [f"Subject: {headers.get('subject', '')}", f"To: {headers.get('to', '')}", + f"Cc: {headers.get('cc', '')}", f"Thread: {msg.get('threadId', '')}"] + return "\n".join(head) + "\n\n" + (body.strip() or msg.get("snippet", "")) + + +_HEADER = re.compile(r"^(Subject|To|Cc|Thread): ") +_LIST_ITEM = re.compile(r"^\s*([-*\u2022]|\d+[.)])\s") + + +def _body(text: str) -> str: + """The text a reader counts: without the header block ``extract: "gmail"`` puts first.""" + blocks = re.split(r"\n\s*\n", text.strip(), maxsplit=1) + if len(blocks) == 2 and all(_HEADER.match(line) for line in blocks[0].splitlines() if line.strip()): + return blocks[1] + return text + + +def _paragraphs(text: str) -> list[str]: + """Paragraphs as a reader counts them: a greeting or sign-off line ("Dana,", "Thanks, Fred") isn't one, and a + list continues the paragraph before it.""" + out: list[str] = [] + for block in re.split(r"\n\s*\n", text.strip()): + lines = [line for line in block.splitlines() if line.strip()] + if not lines: + continue + if len(lines) <= 2 and sum(len(line.split()) for line in lines) <= 4 and lines[-1].rstrip()[-1:] not in ".!?:": + continue # a greeting or sign-off; a short sentence, or a line ending in ":" leading into a list, counts + if out and all(_LIST_ITEM.match(line) for line in lines): + out[-1] += "\n" + block + continue + out.append(block) + return out + + +def _format(text: str, fmt: dict) -> tuple[bool, str]: + problems = [] + body = _body(text) # counts are of the body; contains_* also see the header block (the thread id is there) + paragraphs = _paragraphs(body) + sentences = [s for s in re.split(r"(?<=[.!?])\s+", body.strip()) if s.strip()] + if fmt.get("max_paragraphs") is not None and len(paragraphs) > fmt["max_paragraphs"]: + problems.append(f"{len(paragraphs)} paragraphs > {fmt['max_paragraphs']}") + if fmt.get("max_sentences") is not None and len(sentences) > fmt["max_sentences"]: + problems.append(f"{len(sentences)} sentences > {fmt['max_sentences']}") + low = text.lower() + problems += [f"missing {t!r}" for t in fmt.get("contains_all") or [] if t.lower() not in low] + problems += [f"has {t!r}" for t in fmt.get("contains_none") or [] if t.lower() in low] + return (not problems), ("format ok" if not problems else "; ".join(problems)) + + +async def _judge(spec, statement: str, text: str, *, model: Optional[str] = None, system: str = JUDGE_SYSTEM, + max_chars: Optional[int] = 40000) -> tuple[bool, str]: + """One judge call on ``statement`` against ``text``, cut to ``max_chars`` (an artifact's text; a trajectory gate + sizes its own log, so passes None).""" + import httpx + from agent_env.config import get_config + config = get_config() + base = config.get_litellm_base_url().rstrip("/") + headers = {"Authorization": f"Bearer {config.get_litellm_api_key()}", **(config.get_model_headers(base) or {})} + body = {"model": model or spec["judge_model"], "max_tokens": 2000, "response_format": JUDGE_FORMAT, + "messages": [{"role": "system", "content": system}, + {"role": "user", "content": f"STATEMENT: {statement}\n\nDOCUMENT:\n{text if max_chars is None else text[:max_chars]}"}]} + problem = "" + for _ in range(2): # one retry; then the gate is unknown, never a fail + try: + async with httpx.AsyncClient() as client: + r = await client.post(f"{base}/chat/completions", json=body, headers=headers, timeout=120) + r.raise_for_status() + return _judge_answer(r.json()["choices"][0]["message"]["content"]) + except Exception as e: # noqa: BLE001 + problem = f"{type(e).__name__}: {str(e)[:150]}" + return None, f"judge unknown: {problem}" + + +# ---- trajectory_judge: the agent's work, read from its trajectory ------------------------------------------------- + +async def _trajectory_gate(turn, spec, state, statement: str) -> tuple[Optional[bool], str]: + """The statement judged against every turn's rendered trajectory so far, the open milestone's turns (from + ``state["since"]``) marked THIS STEP. Unknown (None) when the framework hands the hook no trajectories.""" + urls = tuple(getattr(turn, "trajectory_urls", ()) or ()) + if not urls: + return None, "unknown: no trajectories (the framework or the agent offers none)" + step = range(state.get("since", 1), turn.number + 1) + missing = [n for n in step if n > len(urls) or urls[n - 1] is None] + if missing: # the step's own work can't be seen, so a fail would be a guess; an earlier turn's gap is only context + return None, f"unknown: no trajectory for turn(s) {missing} of this step (the fetch failed or returned none)" + texts = [] + for n, url in enumerate(urls, 1): + if url is None: + texts.append((n, "(no trajectory for this turn)")) + continue + if url not in _RENDERED: + raw = await turn.read_trajectory(n) + _RENDERED[url] = render_trajectory(json.loads(raw)) if raw else "(empty trajectory)" + if n in step and not _RENDERED[url].strip(): + # Work in a format this renderer doesn't read (not claude-code's stream-json) would show as nothing. + return None, f"unknown: turn {n}'s trajectory isn't in a format this hook reads" + texts.append((n, _RENDERED[url])) + log = _evidence(texts, step, spec["trajectory_max_chars"]) + return await _judge(spec, statement, log, model=spec["trajectory_judge_model"], system=TRAJECTORY_JUDGE_SYSTEM, + max_chars=None) + + +_RENDERED: dict[str, str] = {} # rendered turns by trajectory URL, kept for the step: a turn's trajectory never changes + + +def _evidence(texts: list[tuple[int, str]], step: range, max_chars: int) -> str: + """The turns' logs, step turns marked; past ``max_chars``, the oldest turns before the step are cut first.""" + blocks = [(n, f"===== Turn {n}{' (THIS STEP)' if n in step else ''} =====\n{t}") for n, t in texts] + while sum(len(b) for _, b in blocks) > max_chars and blocks and blocks[0][0] not in step: + blocks.pop(0) + out = "\n\n".join(b for _, b in blocks) + return out if len(out) <= max_chars else out[-max_chars:] + + +# Writes in full (they are what a gate judges); reads and the agent's text shortened. trajectory_max_chars bounds it all. +TRAJ_WRITE_CHARS, TRAJ_READ_CHARS, TRAJ_TEXT_CHARS = None, 160, 1500 +_WRITE_VERBS = re.compile(r"(create|update|add|send|reply|post|comment|delete|remove|trash|write|batch|append|set_|" + r"share|move|rename|edit|insert|archive|label|assign|draft|upload|invite|cancel|close)", re.I) +_READ_VERBS = re.compile(r"^(\w+_)?(get|list|search|read|find|query|fetch|view|describe|lookup|download|export|count)" + r"(_|$)", re.I) + + +def is_write(tool: str) -> bool: + """A call that changes something: a write verb in its name, which doesn't start (after the app prefix) with a + read verb, so trello_get_comments and gmail_get_messages_batch are reads.""" + name = tool.split("__")[-1] + return not _READ_VERBS.match(name) and bool(_WRITE_VERBS.search(name)) + + +def _cut(value, limit: Optional[int]) -> str: + text = value if isinstance(value, str) else json.dumps(value, ensure_ascii=False) + text = re.sub(r"\s+", " ", text).strip() + return text if limit is None or len(text) <= limit else text[:limit] + f"... [+{len(text) - limit} chars]" + + +def _result_text(content) -> str: + if isinstance(content, list): + return " ".join(c.get("text", "") if isinstance(c, dict) else str(c) for c in content) + return content if isinstance(content, str) else json.dumps(content, ensure_ascii=False) + + +def render_trajectory(messages: list) -> str: + """One claude-code turn trajectory (stream-json messages) as text: each tool call in order with its result, + writes in full, reads up to TRAJ_READ_CHARS, and the agent's text. Empty for a trajectory in another format, + which the trajectory gate then treats as unreadable.""" + results: dict = {} + for m in messages: + if isinstance(m, dict) and m.get("type") == "user": + for block in (m.get("message") or {}).get("content") or []: + if isinstance(block, dict) and block.get("type") == "tool_result": + results[block.get("tool_use_id")] = _result_text(block.get("content")) + lines: list[str] = [] + for m in messages: + if not isinstance(m, dict) or m.get("type") != "assistant": + continue + for block in (m.get("message") or {}).get("content") or []: + if not isinstance(block, dict): + continue + if block.get("type") == "text" and block.get("text", "").strip(): + lines.append(f"AGENT SAYS: {_cut(block['text'], TRAJ_TEXT_CHARS)}") + elif block.get("type") == "tool_use": + tool = block.get("name", "?") + write = is_write(tool) + limit = TRAJ_WRITE_CHARS if write else TRAJ_READ_CHARS + lines.append(f"{'WRITE' if write else 'read'} {tool.split('__')[-1]}({_cut(block.get('input'), limit)})") + if block.get("id") in results: + lines.append(f" -> {_cut(results[block['id']], limit)}") + return "\n".join(lines) + + +def _judge_answer(content: Optional[str]) -> tuple[bool, str]: + content = content or "" + got = json.loads(content[content.find("{"): content.rfind("}") + 1]) + return bool(got["passed"]), str(got.get("why", ""))[:300] + + +async def _excerpt(turn, spec, env, m, state) -> str: + name = m.get("show") + if not name: + return "" + try: + text = await _artifact(env, spec["role"], m, name, {}) + except Exception: # noqa: BLE001 - the excerpt is a courtesy; the nudge stands without it + return "" + if not text: + return "" + cut = text[: spec["excerpt_chars"]] + return f"\nYou opened it and saw:\n{cut}" + ("\n[...]" if len(text) > len(cut) else "") + + +# ---- params -------------------------------------------------------------------------------------------------------- + +def _env(turn, spec): + envs = turn.envs + if not envs: + raise RuntimeError("milestone-gates needs a deployed env to read") + if spec.get("env"): + match = [e for e in envs if e.env_id == spec["env"]] + if not match: + raise RuntimeError(f"no deployed env {spec['env']!r}") + return match[0] + return envs[0] + + +GATE_KEYS = {"id", "nudge", "check", "type"} +GATE_TYPES = ("format", "action", "content") +FORMAT_KEYS = {"max_paragraphs", "max_sentences", "contains_all", "contains_none"} + + +def _check_problem(check: dict) -> Optional[str]: + """What's wrong with a gate's check, or None: exactly one kind, with what that kind needs.""" + kinds = [k for k in ("trajectory_judge", "call", "no_new", "artifact") if k in check] + if len(kinds) != 1: + return f"check needs exactly one of trajectory_judge, call, no_new, artifact; got {sorted(check)}" + kind = kinds[0] + if kind == "trajectory_judge": + return None if isinstance(check[kind], str) and check[kind].strip() else "trajectory_judge needs a statement" + if kind == "call": + if not isinstance(check["call"], dict) or not check["call"].get("tool"): + return "call needs a tool" + return _expect_problem(check.get("expect")) + if kind == "no_new": + calls = check["no_new"] + if not isinstance(calls, list) or not calls or not all(isinstance(c, dict) and c.get("tool") for c in calls): + return "no_new needs a list of calls, each with a tool" + bad = [c["baseline_count"] for c in calls if c.get("baseline_count") is not None and not _whole(c["baseline_count"])] + return f"no_new baseline_count must be a whole number, got {bad[0]!r}" if bad else None + how = [k for k in ("expect", "format", "judge") if k in check] + if len(how) != 1: + return f"an artifact check needs exactly one of expect, format, judge; got {how or 'none'}" + if how == ["expect"] and check["expect"] != "exists": + return "an artifact's expect can only be \"exists\"" + if how == ["format"]: + fmt = check["format"] + if not isinstance(fmt, dict) or not fmt or set(fmt) - FORMAT_KEYS: + return f"format needs one or more of {sorted(FORMAT_KEYS)}" + for key in ("max_paragraphs", "max_sentences"): + if key in fmt and not _whole(fmt[key]): + return f"format.{key} must be a whole number, got {fmt[key]!r}" + for key in ("contains_all", "contains_none"): + if key in fmt and not (isinstance(fmt[key], list) and fmt[key] + and all(isinstance(t, str) and t for t in fmt[key])): + return f"format.{key} must be a list of text, got {fmt[key]!r}" + if how == ["judge"] and not (isinstance(check["judge"], str) and check["judge"].strip()): + return "judge needs a statement" + return None + + +def _expect_problem(expect: Any) -> Optional[str]: + if expect == "exists": + return None + if not isinstance(expect, dict) or len(expect) != 1 or not set(expect) <= {"count", "contains", "equals"}: + return 'expect must be "exists" or one of {count}, {contains}, {equals}' + if "count" in expect and (not isinstance(expect["count"], dict) or not expect["count"] + or set(expect["count"]) - {"eq", "min", "max"} + or not all(_whole(v) for v in expect["count"].values())): + return "expect.count needs eq, min or max, each a whole number" + if "contains" in expect and not (isinstance(expect["contains"], str) and expect["contains"]): + return "expect.contains must be text" + return None + + +def _whole(value: Any) -> bool: + return isinstance(value, int) and not isinstance(value, bool) and value >= 0 + + +def _spec(params: dict) -> dict: + if not isinstance(params.get("enabled", True), bool): + raise ValueError("milestone-gates enabled must be true or false") + if not isinstance(params.get("role"), str) or not params["role"]: + raise ValueError("milestone-gates needs role: the env role its gates read as") + milestones = params.get("milestones") + if not isinstance(milestones, list) or not milestones: + raise ValueError("milestone-gates needs milestones") + out = [] + for i, m in enumerate(milestones): + unknown = set(m) - MILESTONE_KEYS + if unknown: + raise ValueError(f"milestone {i} has unknown keys {sorted(unknown)}") + gates = m.get("gates") or [] + if not gates: + raise ValueError(f"milestone {m.get('id', i)} has no gates") + for g in gates: + if not g.get("id") or not g.get("nudge") or not isinstance(g.get("check"), dict): + raise ValueError(f"milestone {m.get('id', i)}: each gate needs id, nudge and check") + unknown_gate = set(g) - GATE_KEYS + if unknown_gate: + raise ValueError(f"gate {g['id']} has unknown keys {sorted(unknown_gate)}") + if g.get("type") is not None and g["type"] not in GATE_TYPES: + raise ValueError(f"gate {g['id']}: type {g['type']!r} is not one of {list(GATE_TYPES)}") + art = g["check"].get("artifact") + if art is not None and art not in (m.get("artifacts") or {}): + raise ValueError(f"gate {g['id']} names artifact {art!r}, not in its milestone's artifacts") + problem = _check_problem(g["check"]) + if problem: + raise ValueError(f"gate {g['id']}: {problem}") + if i == 0: + for call in g["check"].get("no_new") or []: + if call.get("baseline_count") is None: + raise ValueError(f"gate {g['id']}: a no_new gate in the first milestone needs baseline_count") + out.append({"id": m.get("id") or f"M{i + 1}", "line": m.get("line"), "blocking": m.get("blocking", True), + "max_nudges": int(m.get("max_nudges", 3)), "show": m.get("show"), + "type": m.get("type"), "skip_if_done": bool(m.get("skip_if_done", True)), + "artifacts": m.get("artifacts") or {}, "gates": gates}) + ids = [g["id"] for m in out for g in m["gates"]] + repeated = sorted({gid for gid in ids if ids.count(gid) > 1}) + if repeated: + raise ValueError(f"gate ids must be unique; repeated: {repeated}") + milestone_ids = [m["id"] for m in out] + if len(set(milestone_ids)) != len(milestone_ids): + raise ValueError(f"milestone ids must be unique: {milestone_ids}") + checks = [g["check"] for m in out for g in m["gates"]] + for key, kind in (("judge_model", "judge"), ("trajectory_judge_model", "trajectory_judge")): + if any(kind in c for c in checks) and not (isinstance(params.get(key), str) and params[key].strip()): + raise ValueError(f"milestone-gates needs {key}: a gate uses {kind}") + return {"enabled": params.get("enabled", True), "role": params["role"], "env": params.get("env"), "milestones": out, + "judge_model": params.get("judge_model"), + "trajectory_judge_model": params.get("trajectory_judge_model"), + "trajectory_max_chars": int(params.get("trajectory_max_chars", 600_000)), + "excerpt_chars": int(params.get("excerpt_chars", 600)), + "final_note": params.get("final_note", DEFAULT_FINAL), + "final_note_gave_up": params.get("final_note_gave_up", DEFAULT_FINAL_GAVE_UP), + "idle_end": int(params.get("idle_end", 2))} diff --git a/src/agent_env/examples/milestone-gates/envs/desk/Dockerfile b/src/agent_env/examples/milestone-gates/envs/desk/Dockerfile new file mode 100644 index 000000000..f7aeb5dd1 --- /dev/null +++ b/src/agent_env/examples/milestone-gates/envs/desk/Dockerfile @@ -0,0 +1,8 @@ +FROM public.ecr.aws/docker/library/python:3.11-slim@sha256:c20888b6acdd1e63e1c433a185bf3ad162c0288fe484616ce062e0d28add2900 +WORKDIR /app +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt +COPY server.py . +RUN useradd --create-home --uid 10001 appuser +USER appuser +CMD ["python", "server.py"] diff --git a/src/agent_env/examples/milestone-gates/envs/desk/requirements.txt b/src/agent_env/examples/milestone-gates/envs/desk/requirements.txt new file mode 100644 index 000000000..2f5494844 --- /dev/null +++ b/src/agent_env/examples/milestone-gates/envs/desk/requirements.txt @@ -0,0 +1,3 @@ +# A release pins agentenv-framework-protocol to the version it was released with. +agentenv-framework-protocol +mcp>=1.25,<2 diff --git a/src/agent_env/examples/milestone-gates/envs/desk/server.py b/src/agent_env/examples/milestone-gates/envs/desk/server.py new file mode 100644 index 000000000..b7fd9e196 --- /dev/null +++ b/src/agent_env/examples/milestone-gates/envs/desk/server.py @@ -0,0 +1,54 @@ +"""The desk env: one supplier email in the inbox, and mail the agent can draft or send, for the milestone-gates +example's gates to read.""" +from typing import Annotated, Optional + +from pydantic import Field + +from agentenv_protocol import AgentEnvEnvironment, environment_card, tool + + +@environment_card(name="desk") +class DeskEnv(AgentEnvEnvironment): + def __init__(self) -> None: + super().__init__() + self.inbox = [{"id": 1, "from": "billing@supplier.example", "subject": "Invoice 4417 overdue", + "body": "Invoice 4417 for 1,240.00 was due on the 1st and is still open. Can you confirm when " + "it will be paid?"}] + self.drafts: list[dict] = [] + self.sent: list[dict] = [] + + @tool(name="list_inbox") + def list_inbox(self) -> list[dict]: + """Every email in the inbox, oldest first.""" + return self.inbox + + @tool(name="save_draft") + def save_draft(self, to: Annotated[str, Field(description="Who it will go to.")], + subject: Annotated[str, Field(description="Its subject.")], + body: Annotated[str, Field(description="Its text.")]) -> str: + """Save an email as a draft, without sending it.""" + self.drafts.append({"id": len(self.drafts) + 1, "to": to, "subject": subject, "body": body}) + return "saved" + + @tool(name="list_drafts") + def list_drafts(self) -> list[dict]: + """Every saved draft, oldest first.""" + return self.drafts + + @tool(name="send_email") + def send_email(self, to: Annotated[str, Field(description="Who to send it to.")], + subject: Annotated[str, Field(description="Its subject.")], + body: Annotated[str, Field(description="Its text.")], + cc: Annotated[Optional[str], Field(description="Who to copy, comma-separated.")] = None) -> str: + """Send an email.""" + self.sent.append({"id": len(self.sent) + 1, "to": to, "cc": cc or "", "subject": subject, "body": body}) + return "sent" + + @tool(name="list_sent") + def list_sent(self) -> list[dict]: + """Every sent email, oldest first.""" + return self.sent + + +if __name__ == "__main__": + DeskEnv().serve() diff --git a/src/agent_env/examples/milestone-gates/tasks/overdue-invoice.json b/src/agent_env/examples/milestone-gates/tasks/overdue-invoice.json new file mode 100644 index 000000000..1cfb8438c --- /dev/null +++ b/src/agent_env/examples/milestone-gates/tasks/overdue-invoice.json @@ -0,0 +1,33 @@ +[ + {"id": "env", "type": "deploy_env", "env_id": "desk", "sandbox_type": "local"}, + {"id": "agent", "type": "deploy_agent", "env_ids": ["desk"]}, + {"id": "user", "type": "deploy_user_sim_agent", "agent_name": "dana", "multi_day": false, + "model": "claude-haiku-4-5", + "persona": {"display_name": "Dana Reyes", "first_name": "Dana", + "description": {"who_you_are": ["You run accounts payable at a small studio."], + "how_you_write": ["Short messages, no greeting."], + "what_you_know": ["Invoice 4417 was approved for payment on Friday."], + "decisions": ["You want to see a reply before anything goes out to a supplier."]}, + "keep_private": ["Finance approved it only after a second review."]}, + "opening_prompt": "The supplier chased invoice 4417. Draft a short reply saying we'll pay it Friday, but don't send it yet."}, + {"id": "talk", "type": "prompt_agent", "user_agent_name": "dana", "max_conversation_turns": 8, + "prompt": "The supplier chased invoice 4417. Draft a short reply saying we'll pay it Friday, but don't send it yet.", + "post_turn_hooks": [{"file_artifact_id": "milestone-gates", "params": { + "role": "default", "idle_end": 2, + "milestones": [ + {"id": "M1", "max_nudges": 2, "show": "draft", + "artifacts": {"draft": {"find": {"tool": "list_drafts", "pick": "last"}, "field": "body"}}, + "gates": [ + {"id": "m1-draft", "nudge": "I don't see a draft yet.", "check": {"artifact": "draft", "expect": "exists"}}, + {"id": "m1-not-sent", "nudge": "Don't send anything yet, I want to see it first.", + "check": {"no_new": [{"tool": "list_sent", "baseline_count": 0}]}}, + {"id": "m1-short", "nudge": "Can you make it shorter?", + "check": {"artifact": "draft", "format": {"max_paragraphs": 2}}}]}, + {"id": "M2", "line": "Looks good. Send it to the supplier and copy finance@studio.example.", + "artifacts": {"sent": {"find": {"tool": "list_sent", "pick": "last"}}}, + "gates": [ + {"id": "m2-sent", "nudge": "Has it gone out?", "check": {"artifact": "sent", "expect": "exists"}}, + {"id": "m2-recipients", "nudge": "Check who it went to.", + "check": {"artifact": "sent", "format": {"contains_all": ["billing@supplier.example", + "finance@studio.example"]}}}]}]}}]} +] diff --git a/src/agent_env/task_step/task_steps/agent/deploy_user_sim_agent.py b/src/agent_env/task_step/task_steps/agent/deploy_user_sim_agent.py index e3a8653f1..9cc911e23 100644 --- a/src/agent_env/task_step/task_steps/agent/deploy_user_sim_agent.py +++ b/src/agent_env/task_step/task_steps/agent/deploy_user_sim_agent.py @@ -192,7 +192,8 @@ def persona_problems(persona: Any) -> list[str]: return out -def person(key: str, persona: dict, opening: list[dict], seed: dict, multi_day: Optional[bool]) -> dict: +def person(key: str, persona: dict, opening: list[dict], seed: dict, multi_day: Optional[bool], + preset: Optional[str] = None) -> dict: """The user as the built-in user sim's ``setup`` takes them: ``persona``'s fields, the ``opening`` parts with the run's ```` placeholders filled in (as always_on fills them), and the done line ``multi_day`` picks. The step writes its prompt from this, and user_sim_judge rebuilds that prompt from the step's record (``recorded_person``).""" @@ -205,7 +206,7 @@ def person(key: str, persona: dict, opening: list[dict], seed: dict, multi_day: "description": persona.get("description"), "permissions": persona.get("permissions"), "keep_private": persona.get("keep_private"), "opening": {"text": text, **({"files": files} if files else {})} if text else None, - "done_ends_run": not multi_day} + "done_ends_run": not multi_day, **({"preset": preset} if preset else {})} def recorded_person(us: dict, seed: dict, multi_day: Optional[bool] = None) -> dict: @@ -214,7 +215,7 @@ def recorded_person(us: dict, seed: dict, multi_day: Optional[bool] = None) -> d persona = {**{k: us.get(k) for k in PERSONA_KEYS}, "display_name": us.get("display_name") or us.get("name") or "the user"} return person(us.get("name"), persona, recorded_opening(us), seed, - us["multi_day"] if us.get("multi_day") is not None else multi_day) + us["multi_day"] if us.get("multi_day") is not None else multi_day, us.get("preset")) def recorded_instructions(us: dict, seed: dict, multi_day: Optional[bool] = None) -> Optional[str]: @@ -250,7 +251,8 @@ class DeployUserSimAgentTaskStep(DeployAgentTaskStep): "a2a_agent_version": FieldScope.TASK} def __init__(self, id: str, version: Optional[int], *, persona: Optional[dict] = None, model: Optional[str] = None, - multi_day: Optional[bool] = None, opening_prompt: Optional[str | list[dict]] = None, **deploy: Any): + multi_day: Optional[bool] = None, opening_prompt: Optional[str | list[dict]] = None, + preset: Optional[str] = None, **deploy: Any): if deploy.get("system_prompt") is not None: raise ValueError(f"{self.type} '{id}': system_prompt is written from the persona and opening_prompt; don't set it") deploy.pop("system_prompt", None) @@ -268,16 +270,21 @@ def __init__(self, id: str, version: Optional[int], *, persona: Optional[dict] = # Required: always_on starts the run from it, and refuses a user sim without one only after the deploy. found += opening_problems(opening_prompt) found += persona_problems(persona) + if preset is not None and preset not in user_sim_versions.PRESETS: + found.append(f"preset {preset!r} is not one of {list(user_sim_versions.PRESETS)}") + elif preset in ("chat", "milestone") and multi_day: + found.append(f"preset {preset!r} is one conversation: multi_day must be false") if found: raise ValueError(f"{self.type} '{self.agent_name}': " + "; ".join(found)) self.persona = persona self.model = model self.multi_day = multi_day self.opening_prompt = opening_prompt + self.preset = preset # Who the user is as the task writes it, the seed not filled in: what the judge's rubric_persona_sha256 is. self.persona_sha256 = persona_fingerprint(persona, opening_prompt) - _OWN = ("persona", "model", "multi_day", "opening_prompt") + _OWN = ("persona", "model", "multi_day", "opening_prompt", "preset") def seeded_from(self, written: "DeployUserSimAgentTaskStep") -> None: """This step is ``written`` with the run's seed filled in (``substitute_seed_in_steps``): keep the fingerprint @@ -308,7 +315,24 @@ def _resolve_agent_ref(self, context: TaskStepContext) -> tuple[str, Optional[in def person(self, context: TaskStepContext) -> dict: """The user as the built-in user sim's ``setup`` takes them, as always_on hands them over.""" return person(self.agent_name, self.persona, opening_parts(self.opening_prompt), - context.metadata.get("seed") or {}, self.multi_day) + context.metadata.get("seed") or {}, self.multi_day, self.preset) + + def task_problems(self, steps: list) -> list[str]: + """A preset names the steps this user goes with: a milestone user talks to a prompt_agent with a post-turn + hook (the hook's notes are what it moves on), and a chat or milestone user is never always_on's.""" + if self.preset is None: + return [] + out = [] + talks = [s for s in steps if s.type == "prompt_agent" and getattr(s, "user_agent_name", None) == self.agent_name] + if self.preset == "milestone": + if not talks: + out.append(f"user '{self.agent_name}' has preset milestone, but no prompt_agent step talks to it") + out += [f"user '{self.agent_name}' has preset milestone, but prompt_agent '{s.id}' has no post_turn_hooks " + "to check its milestones" for s in talks if not getattr(s, "post_turn_hooks", None)] + if self.preset in ("chat", "milestone"): + out += [f"user '{self.agent_name}' has preset {self.preset}, one conversation, but always_on '{s.id}' " + "plays it" for s in steps if s.type == "always_on" and getattr(s, "user_sim", None) == self.agent_name] + return out def _setup(self, context: TaskStepContext) -> dict: return user_sim_versions.setup(user_sim_versions.VERSION, self.person(context)) @@ -365,6 +389,9 @@ async def _set_user(self, context: TaskStepContext, agent, setup: dict) -> TaskS # Each tag the prompt shows with its line, so an answer's ``used`` ("D9") names what this run saw. "tagged_lines": user_sim_versions.tagged_lines(self.person(context)), "multi_day": self.multi_day, + # The preset as written (None: chat or always_on by multi_day), and what a judge's rules may depend on. + "preset": self.preset, + "features": sorted(user_sim_versions.features(self.person(context))), # The run record's user sim settings, as always_on wrote them when it set the agent up itself. "setup": {"model": model, "model_from": source, "user_sim_step_model": self.model, "model_set": True, "system_prompt_chars": len(prompt), "output_format": setup.get("output_format"), diff --git a/src/agent_env/task_step/task_steps/agent/user_sim.md b/src/agent_env/task_step/task_steps/agent/user_sim.md index aff2aaf66..95dad1f6c 100644 --- a/src/agent_env/task_step/task_steps/agent/user_sim.md +++ b/src/agent_env/task_step/task_steps/agent/user_sim.md @@ -32,11 +32,36 @@ Its own fields: | `persona` | required | Who the user is: `display_name` (their full name), `first_name` (else the display name's first word), `time_zone` (their IANA zone; else the task clock's, else UTC; a clock that sets a different zone is refused), `description`, `permissions`, `keep_private`, `schedule`, `response_times`, `max_replies` (after that many replies the user stops reading) | | `model` | required | The user sim's model. This step's `step_params` `model` wins, then the run's `user_model` (`--user-model`), then this | | `opening_prompt` | required | The user's first message: text, or text and file parts (below). The always-on step sends it and has no prompt of its own | +| `preset` | optional | `chat`, `always_on` or `milestone`: the kind of run (below) | | `multi_day` | required, for now | Whether the run goes past the day it starts on (always-on's `end_time` falls on a later day). It picks the prompt's done line; always-on refuses a run of the other kind | `multi_day` is a stopgap: the prompt is written before the run, so the step has to be told which done line to use. It goes away once the step can learn it from the task. +`preset` (optional) names the kind of run the user is in: + +| Preset | The run | What it changes | +|---|---|---| +| `chat` | One conversation with a `prompt_agent`; done ends it. `multi_day: false` | Its answer format: the prompt is today's single-session one, but its answer line, each read and its agent's schema offer only `reply` and `done` (below) | +| `always_on` | An `always_on` run; the user reads emails, texts and notifications between messages | Nothing: the prompt is today's multi-day one | +| `milestone` | One conversation in steps that a `prompt_agent` post-turn hook checks (such as milestone-gates). `multi_day: false` | The prompt tells the user to trust the hook's note over the reply, always reply while it says something isn't done, press on what it raises in their own words and never more specifically (not even with names from the assistant's own reply), move on only when it says so, send the line it gives word for word, and answer done only after it says everything is done | + +A `chat` or `milestone` user always answers: its answer format, the line at the end of each read and the schema set on +its agent offer only `reply` and `done`, and a `no_reply` (or an empty reply) is a format error, asked again once in the +same session. Don't write a persona for these presets that tells the user to answer no_reply. Without a preset, and +for `always_on`, the user may stay quiet as before. + +A `milestone` user that answers no_reply to a turn that carried a hook's note is asked again in the same session, up +to twice (each try listed under the read's `gate_rewrites`, each recorded in `metadata["user_sim_note_retries"]`); one +that still won't reply ends the run as a user-sim error (`error_type: user_sim_error`), so verifiers skip it and it is +redone, rather than grading the agent on a conversation the user abandoned mid-milestone. + +Without a preset the user is `chat` or `always_on` by `multi_day`, as before. The task is refused when it loads if a +`milestone` user's `prompt_agent` has no `post_turn_hooks`, if no `prompt_agent` talks to it, or if an `always_on` +step plays a `chat` or `milestone` user. The step records the preset as written and `features`: the parts of the +prompt and run a judge's rules may depend on (`told_lines`, `should_know_lines`, `permission_rules`, `when_done`, +`phone`, `milestones`, `hook_notes`), so a judge can read only the rules that fit this user. + **A first message with files.** `opening_prompt` can be a list of parts in `prompt_agent`'s `parts` format, text and file parts, for a first message that attaches a photo, a PDF, a spreadsheet or any other file: diff --git a/src/agent_env/task_step/task_steps/agent/user_sim_common.py b/src/agent_env/task_step/task_steps/agent/user_sim_common.py index 28581486d..88bbce711 100644 --- a/src/agent_env/task_step/task_steps/agent/user_sim_common.py +++ b/src/agent_env/task_step/task_steps/agent/user_sim_common.py @@ -19,7 +19,8 @@ def person_of(us: dict) -> dict: "email": us.get("email"), "time_zone": us.get("time_zone"), "description": us.get("description"), "versions": us.get("versions") or {}, "output_format": us.get("output_format"), - "permissions": us.get("permissions"), "keep_private": us.get("keep_private")} + "permissions": us.get("permissions"), "keep_private": us.get("keep_private"), + **({"preset": us["preset"]} if us.get("preset") else {})} def persona_fingerprint(persona: dict, opening_prompt: Any) -> str: diff --git a/src/agent_env/task_step/task_steps/agent/user_sim_versions.py b/src/agent_env/task_step/task_steps/agent/user_sim_versions.py index 785905870..c6e02df58 100644 --- a/src/agent_env/task_step/task_steps/agent/user_sim_versions.py +++ b/src/agent_env/task_step/task_steps/agent/user_sim_versions.py @@ -1,6 +1,8 @@ """The built-in user sim: deploy_user_sim_agent writes its system prompt with ``setup``, and the always_on step reads with ``answer``. The interface is in deploy_user_sim_agent.py; how to write a user for it is in user_sim.md. It has -one version, ``ours``. +one version, ``ours``, and three presets (``PRESETS``): chat, always_on and milestone. A preset sets the done line, +whether the user may answer no_reply (chat and milestone always answer: ``outcomes``) and, for milestone, how the user +takes a post-turn hook's note; ``features`` names what a judge's rules may depend on. ``setup`` writes the system prompt once per run: fixed lines on how a real person reads and answers, the description as tagged sections (with the opening request), the user's rules from ``permissions`` and ``keep_private``, and the @@ -53,6 +55,33 @@ "never_supply": "put facts the assistant should find in what_to_look_up, and secrets in keep_private", } +# What kind of run the user sim is in. Each sets its done line and any rules for what it's sent, and names the parts +# of the prompt and the run a judge's rules may depend on (``features``). None: chat or always_on, by ``done_ends_run``. +PRESETS: dict[str, str] = { + "chat": "one conversation; done ends it", + "always_on": "a run over hours or days; the user reads emails, texts and notifications between messages", + "milestone": "one conversation in steps a post-turn hook checks; the user moves on when its note says so", +} +# The milestone preset: a post-turn hook checks the work and tells the user what it found in a note only they see. +MILESTONE_LINES = ( + "After the assistant's reply you may get a note that only you see: what you found when you checked its work " + "yourself. Trust the note over what the reply says about itself. If it says something isn't done, always reply " + "(never no reply) and bring it up in your own words, never more specifically than the note: no answer, figure, " + "name or record it doesn't give you, not even one from the assistant's own reply. Move on only when the note says " + "so, and when it gives you a line to send next, send that line word for word.") +DONE_MILESTONE = ('Answer "done" only after the note says everything is done and you\'ve sent your last line; until ' + 'then, keep the chat going.') +# The parts of the prompt or the run a judge's rule may depend on (see ``features``). +FEATURES: dict[str, str] = { + "told_lines": "a THINGS YOU ALREADY TOLD THE ASSISTANT section (T lines)", + "should_know_lines": "a THINGS THE ASSISTANT SHOULD ALREADY KNOW section (C lines)", + "permission_rules": "rules for the assistant: just do, ask first, never, tell you after", + "when_done": "a WHEN YOU'RE DONE section", + "phone": "reads that show the emails, texts and notifications that reached the user", + "milestones": "a run in steps that a hook opens one at a time", + "hook_notes": "notes from a post-turn hook on what the user found checking the work", +} + PERMISSION_KINDS: dict[str, str] = { "just_do": "Just do", "ask_first": "Ask you first", @@ -83,6 +112,10 @@ "required": ["outcome", "message"], } OUTPUT_FORMAT: dict[str, Any] = {"type": "json_schema", "schema": ANSWER_SCHEMA} +# A one-conversation preset's user always answers: no no_reply in its answer line, its schema or its reads. +ALWAYS_ANSWERS = ("chat", "milestone") +OUTCOMES_ALWAYS = ("reply", "done") +CLOSING_ALWAYS = "Your AI assistant sent you this. As {first}, decide: reply, or say you're done." DONE_ENDS_RUN = ('Only answer "done" with a short sign-off. If your message answers a question or tells the assistant ' 'to do something, answer "reply": after "done", the conversation is over.') @@ -124,7 +157,9 @@ def _first(person: dict) -> str: def _preamble(person: dict) -> list[str]: full, first = person["name"], _first(person) - if person.get("done_ends_run"): + if preset_of(person) == "milestone": + done = DONE_MILESTONE + elif person.get("done_ends_run"): done = DONE_ENDS_RUN elif person["description"].get("when_done"): done = DONE_MULTI_DAY @@ -141,11 +176,71 @@ def _preamble(person: dict) -> list[str]: "make calls about it unless the assistant asks, or your description says to.", "If the assistant asks something no line below covers: for a choice, choose the way you would; for a fact " "about you or anyone else that isn't written below, say you don't know. Never guess facts.", + *([MILESTONE_LINES] if preset_of(person) == "milestone" else []), done, - 'In "used", write the tag of the line you relied on, or "none". Answer in JSON:\n' + ANSWER_LINE, + 'In "used", write the tag of the line you relied on, or "none". Answer in JSON:\n' + answer_line(person), ] +def preset_of(person: dict) -> str: + """The run kind the user sim is in: its ``preset``, else chat when done ends the run, else always_on.""" + return person.get("preset") or ("chat" if person.get("done_ends_run") else "always_on") + + +def features(person: dict) -> frozenset[str]: + """The parts of this user sim's prompt and run that a judge's rules may depend on (``FEATURES``): a section the + description fills in, rules the permissions give, and what the preset adds. A judge given these reads only the + rules that fit this sim, so one product's rules never reach a sim whose prompt never asked for them.""" + description = person.get("description") or {} + have = {feature for key, feature in (("already_told", "told_lines"), ("should_already_know", "should_know_lines"), + ("when_done", "when_done")) + if _lines(description.get(key))} + if any(_items((person.get("permissions") or {}).get(kind))[0] for kind in PERMISSION_KINDS): + have.add("permission_rules") + preset = preset_of(person) + if preset == "always_on": + have.add("phone") + if preset == "milestone": + have |= {"milestones", "hook_notes"} + return frozenset(have) + + +def outcomes(person: dict) -> tuple[str, ...]: + """The outcomes this user may answer with: a chat or milestone preset's user always answers (no no_reply); + without a preset, or always_on, all three, as before.""" + return OUTCOMES_ALWAYS if person.get("preset") in ALWAYS_ANSWERS else OUTCOMES + + +def answer_line(person: dict) -> str: + allowed = outcomes(person) + if allowed == OUTCOMES: + return ANSWER_LINE + return '{"outcome": ' + " | ".join(f'"{o}"' for o in allowed) + ', "message": "...", "used": "..."}' + + +def output_format(person: dict) -> dict[str, Any]: + """The answer format set on the user sim's agent: OUTPUT_FORMAT, its outcome enum this user's ``outcomes``.""" + allowed = outcomes(person) + if allowed == OUTCOMES: + return OUTPUT_FORMAT + schema = {**ANSWER_SCHEMA, "properties": {**ANSWER_SCHEMA["properties"], + "outcome": {"type": "string", "enum": list(allowed)}}} + return {"type": "json_schema", "schema": schema} + + +def retry_line(person: dict) -> str: + return "Your last answer wasn't in the required format. Answer again, only as JSON: " + answer_line(person) + + +def allowed(person: dict, parsed: dict) -> dict: + """An answer whose outcome this user may not give (a no_reply, or an empty reply, from one who always answers) is a + format error: retried once, and recorded as such if the retry is no better.""" + allowed = outcomes(person) + if not parsed["schema_errors"] and parsed["outcome"] not in allowed: + return {**parsed, "schema_errors": [f"outcome {parsed['outcome']!r} is not one of {list(allowed)}"]} + return parsed + + def tag_line(tag: str, text: str) -> str: """One description line under its tag; the line's later lines hang under its text.""" head, *rest = text.split("\n") @@ -270,6 +365,11 @@ def problems(person: Any) -> list[str]: out.append("keep_private must be a list of non-empty lines") if person.get("time_zone") is not None: out += zone_problems(person["time_zone"]) + preset = person.get("preset") + if preset is not None and preset not in PRESETS: + out.append(f"preset {preset!r} is not one of {list(PRESETS)}") + elif preset in ("chat", "milestone") and not person.get("done_ends_run"): + out.append(f"preset {preset!r} is one conversation: it can't run over more than one day") return out @@ -373,8 +473,9 @@ def dated(r: dict, items: list) -> list[dict]: # an earlier read's items, each if read.get("user_note"): # from a post-turn hook: what the user saw checking the work, never sent to the assistant out.append("\nWHAT YOU FOUND WHEN YOU CHECKED ITS WORK YOURSELF (the assistant doesn't see this):") out += [" " + line for line in read["user_note"].strip().splitlines()] - out.append("\n" + CLOSING.format(first=_first(person))) - out.append("Answer in JSON: " + ANSWER_LINE) + closing = CLOSING_ALWAYS if outcomes(person) == OUTCOMES_ALWAYS else CLOSING + out.append("\n" + closing.format(first=_first(person))) + out.append("Answer in JSON: " + answer_line(person)) return "\n".join(out) @@ -441,7 +542,7 @@ def setup(version: str, person: dict) -> dict: found = problems(person) if found: raise ValueError(f"user sim {person.get('name')!r}: " + "; ".join(found)) - return {"system_prompt": system_prompt(person), "output_format": OUTPUT_FORMAT} + return {"system_prompt": system_prompt(person), "output_format": output_format(person)} async def answer(version: str, person: dict, history: list[dict], read: dict, @@ -451,11 +552,11 @@ async def answer(version: str, person: dict, history: list[dict], read: dict, if text is None: return {"outcome": "no_reply", "message": "", "used": None, "input": None, "raw": None, "turns": 0} got = await ask(text) - first = _parsed(got) + first = allowed(person, _parsed(got)) if not first["schema_errors"] or got.get("error"): return {**first, "input": text, "raw": got.get("text"), "retried": False} - again = await ask(RETRY) - second = _parsed(again) + again = await ask(retry_line(person)) + second = allowed(person, _parsed(again)) if second["schema_errors"]: second["schema_errors"] = ([f"first answer: {e}" for e in first["schema_errors"]] + [f"answer after the retry: {e}" for e in second["schema_errors"]]) diff --git a/src/agent_env/task_step/task_steps/post_turn_hooks.py b/src/agent_env/task_step/task_steps/post_turn_hooks.py index 4a333d375..71fb48d53 100644 --- a/src/agent_env/task_step/task_steps/post_turn_hooks.py +++ b/src/agent_env/task_step/task_steps/post_turn_hooks.py @@ -10,7 +10,7 @@ import sys import tempfile import uuid -from collections.abc import Awaitable, Callable, Mapping +from collections.abc import Awaitable, Callable, Mapping, Sequence from dataclasses import dataclass from types import MappingProxyType from typing import Any, Optional @@ -34,6 +34,8 @@ _SPEC_KEYS = ("file_artifact_id", "file_artifact_version", "params") _RECORD_TAGS = ("hook", "turn") +# Where each hook's summary of a step's conversation is kept (Turn.summarize). +SUMMARIES_KEY = "post_turn_hook_summaries" _INVOKABLE = (EXT_CLOCK_URI, EXT_TRIGGERS_URI, EXT_NOTIFICATIONS_URI) _TOOL_CALL_TIMEOUT_S = 600 @@ -69,7 +71,9 @@ class PostTurnHook: class PostTurnHooks: - """The hooks of one step run, each loaded once; ``close`` removes their scripts' temporary files.""" + """The hooks of one step run, each loaded once when the step starts; ``close`` removes their scripts' temporary + files. A hook's script defines ``async def post_turn(turn, params)`` and may define ``def check_params(params)``, + called at load, which raises ValueError for params it can't run with.""" def __init__(self) -> None: self.hooks: list[PostTurnHook] = [] @@ -105,6 +109,17 @@ async def _load(self, spec: dict, module_name: str) -> PostTurnHook: if not inspect.iscoroutinefunction(post_turn): raise ValueError(f"post-turn hook '{spec['file_artifact_id']}' must define " "`async def post_turn(turn, params)`: steps and runs share one event loop") + # A hook may check its params when it loads, before the conversation starts, so a bad one fails the step + # before the first message instead of after the agent's first turn. + check_params = getattr(module, "check_params", None) + if check_params is not None: + if not callable(check_params) or inspect.iscoroutinefunction(check_params): + raise ValueError(f"post-turn hook '{spec['file_artifact_id']}': check_params must be " + "`def check_params(params)`") + try: + check_params(spec.get("params") or {}) + except ValueError as e: + raise ValueError(f"post-turn hook '{spec['file_artifact_id']}' refused its params: {e}") from e return PostTurnHook(spec["file_artifact_id"], spec.get("file_artifact_version"), spec.get("params") or {}, post_turn) @@ -195,8 +210,12 @@ class Turn: """What a hook is handed after an agent turn; ``last`` after the final one, when a returned message is ignored.""" def __init__(self, *, context: TaskStepContext, step_id: str, hook: PostTurnHook, answer: _Answer, number: int, - last: bool, agent_reply: str, agent_parts: list[dict]) -> None: + last: bool, agent_reply: str, agent_parts: list[dict], + trajectory_urls: Sequence[Optional[str]] = ()) -> None: self.number = number + # The agent's native trajectory of each turn so far, oldest first: None for a turn whose trajectory the + # agent returned none of or couldn't be fetched; empty when the agent's card offers no trajectories. + self.trajectory_urls: tuple[Optional[str], ...] = tuple(trajectory_urls) self.last = last self.agent_reply = agent_reply self.agent_parts = copy.deepcopy(agent_parts) @@ -204,6 +223,7 @@ def __init__(self, *, context: TaskStepContext, step_id: str, hook: PostTurnHook self.envs = [HookEnv(d, hook.artifact_id) for d in context.deployed_envs] self._context = context self._step_id = step_id + self.step_id = step_id # the prompt_agent step this turn is in: turn numbers restart in each self._hook = hook self._answer = answer @@ -212,6 +232,19 @@ def metadata(self) -> Mapping[str, Any]: """A read-only copy of the run's metadata, its secret keys stripped.""" return MappingProxyType(_strip_redacted_keys(self._context.metadata)) + async def read_trajectory(self, number: int) -> Optional[str]: + """Turn ``number``'s trajectory (1 is the first turn) as the agent stored it, as text; None when that turn + has none, including every turn of an agent whose card offers no trajectories. Raises IndexError for a turn + that hasn't happened.""" + if not 1 <= number <= self.number: + raise IndexError(f"turn {number}: the conversation is at turn {self.number}") + url = self.trajectory_urls[number - 1] if number <= len(self.trajectory_urls) else None + if url is None: + return None + from agent_env.config import get_config + data = await asyncio.to_thread(lambda: get_config().get_object_store_at(url).get(url)) + return data.decode("utf-8", errors="replace") + async def ask_user(self, note: Optional[str] = None) -> Answer: """Today's user side: agent triggers, then a human or the LLM user sim, which sees only replies sent here. @@ -236,6 +269,16 @@ def record(self, entry: dict) -> None: (self._context.metadata.setdefault("post_turn_hooks", {}).setdefault(self._step_id, []) .append({"hook": self._hook.artifact_id, "turn": self.number, **copy.deepcopy(entry)})) + def summarize(self, summary: dict) -> None: + """Set this hook's summary of the conversation so far, replacing the last one: + ``metadata["post_turn_hook_summaries"][step_id][hook]``, one object per hook per step that a verifier or the + hub reads without going through the hook's records. Set it every turn to keep it right however the + conversation ends; ``{}`` leaves an empty one.""" + if not isinstance(summary, dict): + raise ValueError("a hook's summary is an object") + (self._context.metadata.setdefault(SUMMARIES_KEY, {}).setdefault(self._step_id, {}) + [self._hook.artifact_id]) = copy.deepcopy(summary) + def records(self) -> list[dict]: """This hook's own records in this conversation, oldest first: what ``record`` appended for this step, as read-only copies (another step's conversation, or another hook in this one, keeps its own).""" @@ -281,12 +324,13 @@ def _parts(message: Any, hook: PostTurnHook) -> list[dict]: async def run_post_turn_hooks(hooks: PostTurnHooks, *, context: TaskStepContext, step_id: str, number: int, last: bool, agent_reply: str, agent_parts: list[dict], ask_user: Callable[..., Awaitable[Answer]], - user_triggers: Callable[[], Awaitable[Optional[Answer]]]) -> Optional[Answer]: + user_triggers: Callable[[], Awaitable[Optional[Answer]]], + trajectory_urls: Sequence[Optional[str]] = ()) -> Optional[Answer]: """Run the hooks in order; the first to return a message or an end decides, and one that asked returns that.""" answer = _Answer(ask_user, user_triggers) for hook in hooks.hooks: turn = Turn(context=context, step_id=step_id, hook=hook, answer=answer, number=number, last=last, - agent_reply=agent_reply, agent_parts=agent_parts) + agent_reply=agent_reply, agent_parts=agent_parts, trajectory_urls=trajectory_urls) returned = await hook.post_turn(turn, copy.deepcopy(hook.params)) if answer.value is not None: if returned != answer.value: diff --git a/src/agent_env/task_step/task_steps/prompt_agent.py b/src/agent_env/task_step/task_steps/prompt_agent.py index 131fb705e..2b5200209 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -676,6 +676,7 @@ async def _converse( conversation_tool_call_count: Optional[int] = None final_task_id = "" per_turn_trajectory_urls: list[str | None] = [] + hook_trajectory_urls: list[str | None] = [] # what post-turn hooks read: native while the run's copies wait per_turn_trajectories: list[TurnTrajectory] = [] source_agent_per_turn_prompt_parts: list[list[dict] | None] = [] traj_ext_cached = A2AAgent.find_extension(card, A2AAgent.EXT_TRAJECTORY) @@ -772,12 +773,22 @@ def record_turn() -> None: target_a2a_task_id, card=card, sandbox_type=agent.sandbox_type, headers=agent.control_headers, ) stored = StoredTrajectory() + hook_url = None if not atif_copies.replaces_native: # the run's copy, read off the turn's path, replaces native try: stored = await read_native() except Exception as e: logger.warning(f"Turn {turn+1} trajectory fetch failed (continuing): {e}") + hook_url = stored.url + elif hooks is not None: + # The run's copies arrive after the conversation; hooks judge this turn's work now, so they get + # its native trajectory. The step's record keeps the copies. + try: + hook_url = (await read_native()).url + except Exception as e: + logger.warning(f"Turn {turn+1} trajectory fetch for post-turn hooks failed (continuing): {e}") per_turn_trajectory_urls.append(stored.url) + hook_trajectory_urls.append(hook_url) turn_record = TurnTrajectory(format=stored.format, atif=None) per_turn_trajectories.append(turn_record) atif_copies.turn(len(per_turn_trajectory_urls) - 1, sent_task_id, target_a2a_task_id, turn_record, @@ -815,6 +826,7 @@ def record_turn() -> None: agent_parts=agent_response_parts, ask_user=functools.partial(user_side.ask, turn + 1, reply, agent_response_parts), user_triggers=functools.partial(user_side.triggers, turn + 1, reply), + trajectory_urls=hook_trajectory_urls, ) if answer is None and not last: answer = await user_side.ask(turn + 1, final_terminal.response_text, agent_response_parts) @@ -1243,15 +1255,36 @@ async def _answer(self, number: int, agent_parts: list[dict], solver_message: st self._record("user_side_notes", {"turn": number, "note": note}) answer = await self._built_in.ask(number, _agent_text(solver_message, agent_parts), self._ask_built_in, note=note) + keep = note is not None and self._built_in.person.get("preset") == "milestone" + if keep: + answer = await self._keep_replying(number, answer) if self._gate is not None and "message" in answer: async def rewrite_built_in(why: str) -> dict: # the gate's request alone: the hook's note went once - return await self._built_in.rewrite(number, why, self._ask_built_in) + got = await self._built_in.rewrite(number, why, self._ask_built_in) + # A rewrite is still a turn with the note in play: a milestone user doesn't leave by no_reply here. + return await self._keep_replying(number, got) if keep else got answer = await self._gated(number, answer, rewrite_built_in, hook_note=note) self._end_after = answer.get("end_after") return answer return await self._ask_peer(number, agent_parts, note) + async def _keep_replying(self, number: int, answer: dict) -> dict: + """A milestone user sim stays in the conversation while a hook's note is in play: a no_reply to a turn that + carried a note is asked again, up to ``NOTE_REPLY_TRIES`` times, in the same session (each try is listed under + the read's ``gate_rewrites``). A user sim that still won't reply ends the run as a user-sim error, so verifiers + skip it and it is redone, rather than grading the agent on a conversation the user abandoned mid-milestone.""" + for _ in range(NOTE_REPLY_TRIES): + if answer.get("end") != "user_no_reply": + return answer + self._record("user_sim_note_retries", {"turn": number}) + answer = await self._built_in.rewrite(number, NOTE_NO_REPLY, self._ask_built_in) + if answer.get("end") == "user_no_reply": + self._built_in.error = ("the milestone user sim answered no_reply to a turn that carried a hook's note, " + f"{NOTE_REPLY_TRIES + 1} times") + return {"end": "user_sim_error"} + return answer + async def _ask_built_in(self, text: str) -> dict: """One turn of the user sim deploy_user_sim_agent deployed, in this conversation's session: ``{"text", "structured", "trajectory_url"}``, or ``{"text": None, "error"}``.""" @@ -1434,6 +1467,13 @@ def _text_of(parts: list[dict]) -> str: return "\n".join(p.get("text", "") for p in parts if p.get("kind") == "text") +# A milestone user sim that answers no_reply while a hook's note is in play is asked again this many times. +NOTE_REPLY_TRIES = 2 +NOTE_NO_REPLY = ("[Conversation system note, not from the assistant.] The chat isn't over: what you found checking its " + "work still needs answering. Reply to the assistant about it, in your own words and no more " + "specifically than your note. Answer in JSON: " + user_sim_versions.ANSWER_LINE) + + class _BuiltInUserSim: """The user deployed by deploy_user_sim_agent, read as always_on reads it, in one sitting: each agent reply is one read, done ends the conversation, and there is no phone.""" @@ -1521,7 +1561,12 @@ async def rewrite(self, number: int, note: str, ask_user_sim) -> dict: ``schema_errors`` are the latest rewrite's), keeps what the user sim first answered as ``first_message``, and lists each rewrite under ``gate_rewrites``.""" got = await ask_user_sim(note) - ans = user_sim_versions.parse(got["structured"] if isinstance(got.get("structured"), dict) else got.get("text")) + ans = user_sim_versions.allowed(self.person, user_sim_versions.parse( + got["structured"] if isinstance(got.get("structured"), dict) else got.get("text"))) + if ans["schema_errors"] and not got.get("error"): # as an ordinary answer: one retry in the answer's format + got = await ask_user_sim(user_sim_versions.retry_line(self.person)) + ans = user_sim_versions.allowed(self.person, user_sim_versions.parse( + got["structured"] if isinstance(got.get("structured"), dict) else got.get("text"))) error = got.get("error") rewrite = {k: ans.get(k) for k in ("outcome", "message", "used", "schema_errors")} rewrite.update(user_sim_error=error, user_sim_trajectory_url=got.get("trajectory_url")) diff --git a/tst/installer/test_container_journey.py b/tst/installer/test_container_journey.py index d13237c00..ff67c1020 100644 --- a/tst/installer/test_container_journey.py +++ b/tst/installer/test_container_journey.py @@ -133,7 +133,7 @@ def test_a_new_user_installs_agent_env_adds_plugins_runs_a_task_and_removes_them container.ok("python", "-m", "pip", "install", "-q", "--no-index", "--find-links", "/wheels", "uv") container.ok("uv", "tool", "install", "agentenv-framework") rows = container.ok("agent-env", "plugin", "list").stdout.split("STATUS\n", 1)[1] - assert re.fullmatch(r"agentenv-framework +\S+ +10 bundles +ok\n", rows), rows + assert re.fullmatch(r"agentenv-framework +\S+ +11 bundles +ok\n", rows), rows added = container.ok("agent-env", "plugin", "add", browser, grader, "--yes") assert "toy_navigate active" in added.stdout and "toy_grade active" in added.stdout diff --git a/tst/unit/bundle/installed_test.py b/tst/unit/bundle/installed_test.py index ed5d3b8ba..ca089a5bc 100644 --- a/tst/unit/bundle/installed_test.py +++ b/tst/unit/bundle/installed_test.py @@ -130,7 +130,7 @@ def test_the_plugin_report_counts_the_bundles_agent_env_ships(monkeypatch, quiet (BUNDLES, "advance-to-next-event", "active"), (BUNDLES, "agents", "active"), (BUNDLES, "browsers", "active"), (BUNDLES, "computers", "active"), (BUNDLES, "desktop", "active"), (BUNDLES, "drivers", "active"), (BUNDLES, "echo-mcp", "active"), (BUNDLES, "hello", "active"), (BUNDLES, "mail-mcp", "active"), - (BUNDLES, "next-env-event", "active")] + (BUNDLES, "milestone-gates", "active"), (BUNDLES, "next-env-event", "active")] assert "\n agent-env itself\n" in shown and "requires:" not in shown diff --git a/tst/unit/bundle/shipped_bundles_test.py b/tst/unit/bundle/shipped_bundles_test.py index 666041e8d..e8ad09b89 100644 --- a/tst/unit/bundle/shipped_bundles_test.py +++ b/tst/unit/bundle/shipped_bundles_test.py @@ -27,7 +27,7 @@ def _shipped() -> dict: def test_agentenv_framework_ships_its_bundles(): assert SHIPPED == ["advance-to-next-event", "agents", "browsers", "computers", "desktop", "drivers", "echo-mcp", "hello", - "mail-mcp", "next-env-event"] + "mail-mcp", "milestone-gates", "next-env-event"] @pytest.mark.parametrize("name", SHIPPED) diff --git a/tst/unit/task/lint_test.py b/tst/unit/task/lint_test.py index ab1d012d7..4465670e4 100644 --- a/tst/unit/task/lint_test.py +++ b/tst/unit/task/lint_test.py @@ -404,8 +404,9 @@ def _shipped(): if bundle.dist == CORE and any((bundle.root / "tasks").glob("*.json"))} -# The shipped examples that show env triggers and no grading, which lint rightly says grade nothing. -_UNGRADED = {"advance-to-next-event", "next-env-event"} +# The shipped examples that show env triggers or a conversation hook and no grading, which lint rightly says grade +# nothing. +_UNGRADED = {"advance-to-next-event", "milestone-gates", "next-env-event"} @pytest.mark.usefixtures("local_stores") diff --git a/tst/unit/task_step/test_milestone_gates_hook.py b/tst/unit/task_step/test_milestone_gates_hook.py new file mode 100644 index 000000000..169d6ed18 --- /dev/null +++ b/tst/unit/task_step/test_milestone_gates_hook.py @@ -0,0 +1,806 @@ +"""Offline tests for the milestone-gates example hook: a fake Turn and env, scripted tool results per turn, no network.""" +import json +import copy +import importlib.util +from pathlib import Path + +import pytest + +import agent_env + +HOOK = Path(agent_env.__file__).parent / "examples" / "milestone-gates" / "artifacts" / "milestone-gates" / "hook.py" +_spec = importlib.util.spec_from_file_location("milestone_gates_hook", HOOK) +mg = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(mg) + + +class Env: + """Tool results by name; ``state`` is edited between turns to play the agent's work.""" + + def __init__(self, state): + self.env_id = "work" + self.state = state + self.calls = [] + + async def call_tool(self, tool, args, role): + self.calls.append((tool, args, role)) + value = self.state[tool] + value = value(args) if callable(value) else value + return {"content": [{"type": "text", "text": value if isinstance(value, str) else json.dumps(value)}]} + + +class Turn: + def __init__(self, env, records, number, last=False, sim_fields=None, reply=None, trajectories=None): + self.envs, self._records, self.number, self.last = [env], records, number, last + self.notes, self.reply = [], reply + # trajectories: {url: stream-json messages}; trajectory_urls is one url per turn so far + self._trajectories = trajectories or {} + self.trajectory_urls = tuple(self._trajectories)[:number] + self.reads = [] + self.metadata = {"usersim_turn_outputs": {"talk": [{"turn": number, "fields": sim_fields}]} if sim_fields + else {}} + + async def read_trajectory(self, n): + url = self.trajectory_urls[n - 1] + self.reads.append(url) + return None if url is None else json.dumps(self._trajectories[url]) + + def records(self): + return [dict(r) for r in self._records] + + def record(self, entry): + self._records.append({**entry, "turn": self.number}) + + def summarize(self, summary): + self.summary = json.loads(json.dumps(summary)) # what a run's metadata could hold + + async def ask_user(self, note=None): + self.notes.append(note) + text = self.reply or f"sim says ({self.number}.{len(self.notes)})" + self.answer = {"message": [{"kind": "text", "text": text}]} + return self.answer + + +async def post_turn(turn, params): + """mg.post_turn, held to the framework's rule: a hook that asked the user side returns that answer.""" + turn.answer = None + returned = await mg.post_turn(turn, params) + if turn.answer is not None: + assert returned == turn.answer, f"asked the user side, then returned {returned!r}" + return returned + + +SHEET = {"id": "s1", "name": "Q4 subscriptions", "mimeType": "spreadsheet"} +PARAMS = { + "role": "auditor", "judge_model": "judge-m", "trajectory_judge_model": "traj-m", + "milestones": [ + {"id": "M1", "max_nudges": 2, "show": "sheet", + "artifacts": {"sheet": {"find": {"tool": "drive_list", "path": "files", "where": {"mimeType": "spread"}}, + "read": {"tool": "sheet_read", "args": {"id": "{id}"}}}}, + "gates": [ + {"id": "m1-sheet", "nudge": "I don't see the sheet yet.", "check": {"artifact": "sheet", "expect": "exists"}}, + {"id": "m1-cols", "nudge": "Can it show the monthly cost?", + "check": {"artifact": "sheet", "format": {"contains_all": ["status", "monthly"]}}}, + {"id": "m1-quiet", "nudge": "Hold off on emailing anyone.", + "check": {"no_new": [{"tool": "gmail_sent", "path": "messages", "baseline_count": 0}]}}, + ]}, + {"id": "M2", "blocking": False, "max_nudges": 1, + "gates": [{"id": "m2-comment", "nudge": "Did the comment go on the card?", + "check": {"call": {"tool": "trello_comments", "path": "comments"}, "expect": {"count": {"eq": 1}}}}, + {"id": "m2-quiet", "nudge": "Don't email yet.", + "check": {"no_new": [{"tool": "gmail_sent", "path": "messages"}]}}]}, + ], +} + + +def _status(t) -> list[tuple]: + """Each milestone's status, opened and closed turn, and nudges, from turn ``t``'s summary.""" + return [(m["id"], m["status"], m["opened_turn"], m["closed_turn"], m["nudges"]) for m in t.summary["milestones"]] + + +def world(): + return {"drive_list": {"files": []}, "sheet_read": "vendor,status,monthly\nVaultly,active,19.99", + "gmail_sent": {"messages": []}, "trello_comments": {"comments": []}} + + +@pytest.mark.asyncio +async def test_a_failing_gate_sends_its_nudge_and_counts_it(): + env, records = Env(world()), [] + t = Turn(env, records, 1) + answer = await post_turn(t, PARAMS) + assert answer == {"message": [{"kind": "text", "text": "sim says (1.1)"}]} + assert t.notes == ["I don't see the sheet yet."] # no sheet: no excerpt either + assert records[-1]["decision"] == "nudge" and records[-1]["nudges"] == 1 + assert [g["passed"] for g in records[-1]["gates"]] == [False, False, True] + + +@pytest.mark.asyncio +async def test_switched_off_it_checks_nothing_and_tells_the_sim_nothing_and_says_so_once(): + env, records = Env(world()), [] + for n in (1, 2): + t = Turn(env, records, n) + assert await post_turn(t, {**PARAMS, "enabled": False}) is None + assert t.notes == [] + assert env.calls == [] and records == [{"decision": "disabled", "turn": 1}] + assert t.summary == {"enabled": False} + + +@pytest.mark.asyncio +async def test_every_failing_turn_counts_even_when_the_sim_did_not_press_on_it(): + env, records = Env(world()), [] + await post_turn(Turn(env, records, 1, sim_fields={"nudged": False}), PARAMS) + assert records[-1]["nudges"] == 1 and records[-1]["sim_nudged"] is False + + +@pytest.mark.asyncio +async def test_all_gates_passing_opens_the_next_milestone_and_takes_its_baselines_then(): + w = world() + w["drive_list"] = {"files": [SHEET]} + w["gmail_sent"] = {"messages": [{"id": "old"}]} # sent before M1 opened? no: baseline_count 0, so M1 fails + env, records = Env(w), [] + t = Turn(env, records, 1) + await post_turn(t, PARAMS) + assert records[-1]["gates"][2] == {"id": "m1-quiet", "passed": False, "why": "new: gmail_sent +1", + "nudge": "Hold off on emailing anyone."} + assert t.notes[0].startswith("Hold off on emailing anyone.\nYou opened it and saw:\nvendor,status,monthly") + + w["gmail_sent"] = {"messages": []} + t2 = Turn(env, records, 2) + await post_turn(t2, PARAMS) + assert t2.notes == ["M1 is done. Open M2 now: send its line."] + assert records[-1]["decision"] == "passed" and records[-1]["baselines"] == {"M2:m2-quiet:0": 0} + + # M2: an email now is new against the baseline taken when M2 opened + w["gmail_sent"] = {"messages": [{"id": "x"}]} + w["trello_comments"] = {"comments": [{"id": "c"}]} + t3 = Turn(env, records, 3) + await post_turn(t3, PARAMS) + assert t3.notes == ["Don't email yet."] + assert _status(t3) == [("M1", "passed", 1, 2, 1), ("M2", "open", 3, None, 1)] + assert {k: t3.summary[k] for k in ("enabled", "reached", "done", "total", "end")} == { + "enabled": True, "reached": "M2", "done": 1, "total": 2, "end": None} + assert t3.summary["milestones"][0]["gates"] == {"m1-sheet": {"passed": True, "type": "action"}, + "m1-cols": {"passed": True, "type": "format"}, + "m1-quiet": {"passed": True, "type": "action"}} + assert t3.summary["milestones"][1]["gates"]["m2-quiet"] == {"passed": False, "type": "action"} + + +@pytest.mark.asyncio +async def test_a_blocking_milestone_that_never_passes_ends_the_conversation(): + env, records = Env(world()), [] + for n in (1, 2): + await post_turn(Turn(env, records, n), PARAMS) + t3 = Turn(env, records, 3) + answer = await post_turn(t3, PARAMS) + assert answer == {"end": "gate_never_passed:M1"} + assert [r["decision"] for r in records] == ["nudge", "nudge", "end"] + assert _status(t3) == [("M1", "derailed", 1, 3, 2), ("M2", "not_reached", None, None, 0)] + assert (t3.summary["reached"], t3.summary["done"], t3.summary["end"]) == ("M1", 0, "gate_never_passed:M1") + + +@pytest.mark.asyncio +async def test_a_non_blocking_milestone_is_let_go_and_the_last_one_wraps_up_then_ends(): + w = world() + w["drive_list"] = {"files": [SHEET]} + env, records = Env(w), [] + await post_turn(Turn(env, records, 1), PARAMS) # M1 passes + t2 = Turn(env, records, 2) + await post_turn(t2, PARAMS) # M2 fails: nudge 1 of 1 + assert t2.notes == ["Did the comment go on the card?"] + t3 = Turn(env, records, 3) + await post_turn(t3, PARAMS) # still failing, not blocking: let go, and it was the last + assert t3.notes == ["M2 isn't done, but let it go. " + mg.DEFAULT_FINAL_GAVE_UP] # not "everything is done" + assert records[-1]["decision"] == "gave_up" and records[-1]["wrap_up"] is True + t4 = Turn(env, records, 4) + assert await post_turn(t4, PARAMS) == {"end": "milestones_done"} + assert _status(t4) == [("M1", "passed", 1, 1, 0), ("M2", "gave_up", 2, 3, 1)] + assert (t4.summary["done"], t4.summary["end"]) == (1, "milestones_done") + + +@pytest.mark.asyncio +async def test_judge_gates_run_only_after_the_cheap_ones_pass(monkeypatch): + calls = [] + + async def judge(spec, statement, text): + calls.append(statement) + return "19.99" in text, "seen" + + monkeypatch.setattr(mg, "_judge", judge) + params = json.loads(json.dumps(PARAMS)) + params["milestones"][0]["gates"].append( + {"id": "m1-1p", "nudge": "Check the seat counts.", "check": {"artifact": "sheet", "judge": "Vaultly 19.99"}}) + env, records = Env(world()), [] + await post_turn(Turn(env, records, 1), params) + assert calls == [] and records[-1]["gates"][3]["passed"] is None + env.state["drive_list"] = {"files": [SHEET]} + await post_turn(Turn(env, records, 2), params) + assert calls == ["Vaultly 19.99"] and records[-1]["decision"] == "passed" + + +@pytest.mark.asyncio +async def test_a_tool_error_fails_the_gate_with_the_reason(): + w = world() + w["drive_list"] = lambda args: (_ for _ in ()).throw(RuntimeError("boom")) + env, records = Env(w), [] + await post_turn(Turn(env, records, 1), PARAMS) + assert records[-1]["gates"][0]["why"] == "error: RuntimeError: boom" + + +@pytest.mark.asyncio +async def test_on_the_last_turn_it_records_where_it_stood_and_asks_nothing(): + env, records = Env(world()), [] + t = Turn(env, records, 1, last=True) + assert await post_turn(t, PARAMS) is None + assert t.notes == [] and records[-1]["decision"] == "last_turn" + + +@pytest.mark.parametrize("bad, fragment", [ + ({"milestones": []}, "needs role"), + ({"role": "a", "milestones": []}, "needs milestones"), + ({"role": "a", "milestones": [{"id": "M1", "gates": []}]}, "has no gates"), + ({"role": "a", "milestones": [{"id": "M1", "gates": [{"id": "g", "check": {}}]}]}, "needs id, nudge and check"), + ({"role": "a", "milestones": [{"id": "M1", "gates": [{"id": "g", "nudge": "n", "check": {"artifact": "x"}}]}]}, + "not in its milestone's artifacts"), + ({"role": "a", "milestones": [{"id": "M1", "gates": [{"id": "g", "nudge": "n", + "check": {"no_new": [{"tool": "t"}]}}]}]}, "baseline_count"), + ({"role": "a", "milestones": [{"id": "M1", "nudges": 2, "gates": []}]}, "unknown keys"), + ({"role": "a", "milestones": [{"id": "M1", "gates": [{"id": "g", "nudge": "n", + "check": {"trajectory_judge": "it did"}}]}]}, + "needs trajectory_judge_model"), + ({**PARAMS, "enabled": "no"}, "enabled must be true or false"), + ({"role": "a", "milestones": [{"id": "M1", "gates": [{"id": "g", "nudge": "n", "check": {"judge": "it did"}}]}]}, "exactly one of trajectory_judge"), + ({"role": "a", "milestones": [{"id": "M1", "gates": [{"id": "g", "nudge": "n", "check": {"trajectory_judge": "x", "call": {"tool": "t"}}}]}]}, "exactly one of trajectory_judge"), + ({"role": "a", "milestones": [{"id": "M1", "gates": [{"id": "g", "nudge": "n", "check": {"call": {}, "expect": "exists"}}]}]}, "needs a tool"), + ({"role": "a", "milestones": [{"id": "M1", "gates": [{"id": "g", "nudge": "n", "check": {"call": {"tool": "t"}}}]}]}, "expect must be"), + ({"role": "a", "milestones": [{"id": "M1", "gates": [{"id": "g", "nudge": "n", "check": {"no_new": []}}]}]}, "no_new needs a list"), + ({"role": "a", "milestones": [{"id": "M1", "artifacts": {"x": {}}, "gates": [ + {"id": "g", "nudge": "n", "check": {"artifact": "x"}}]}]}, "exactly one of expect, format, judge"), + ({"role": "a", "milestones": [{"id": "M1", "artifacts": {"x": {}}, "gates": [ + {"id": "g", "nudge": "n", "check": {"artifact": "x", "format": {"max_words": 3}}}]}]}, "format needs"), + ({"role": "a", "milestones": [{"id": "M1", "gates": [ + {"id": "g", "nudge": "n", "nudges": 2, "check": {"call": {"tool": "t"}, "expect": "exists"}}]}]}, + "unknown keys"), + ({"role": "a", "milestones": [{"id": "M1", "gates": [ + {"id": "g", "nudge": "n", "type": "style", "check": {"call": {"tool": "t"}, "expect": "exists"}}]}]}, + "is not one of"), + ({"role": "a", "milestones": [ + {"id": "M1", "gates": [{"id": "g", "nudge": "n", "check": {"call": {"tool": "t"}, "expect": "exists"}}]}, + {"id": "M2", "line": "next", "gates": [ + {"id": "g", "nudge": "n", "check": {"call": {"tool": "t"}, "expect": "exists"}}]}]}, + "gate ids must be unique"), +]) +def test_a_bad_spec_is_refused(bad, fragment): + with pytest.raises(ValueError, match=fragment): + mg._spec(bad) + with pytest.raises(ValueError, match=fragment): # and when the framework loads the hook, before any turn + mg.check_params(bad) + + +@pytest.mark.asyncio +async def test_a_number_field_is_compared_against_its_baseline(): + params = {"role": "r", "milestones": [{"id": "M1", "max_nudges": 1, "gates": [{"id": "q", "nudge": "no email", + "check": {"no_new": [{"tool": "labels", "path": "labels", "where": {"id": "SENT"}, + "number": "messagesTotal", "baseline_count": 41}]}}]}]} + env, records = Env({"labels": {"labels": [{"id": "INBOX", "messagesTotal": 9}, {"id": "SENT", "messagesTotal": 41}]}}), [] + await post_turn(Turn(env, records, 1), params) + assert records[-1]["gates"][0]["passed"] is True + env.state["labels"]["labels"][1]["messagesTotal"] = 42 + records = [] + await post_turn(Turn(env, records, 1), params) + assert records[-1]["gates"][0] == {"id": "q", "passed": False, "why": "new: labels +1", "nudge": "no email"} + + +def test_a_gmail_message_reads_as_headers_and_its_plain_text_body(): + import base64 + body = base64.urlsafe_b64encode("Run-rate is $4,210/month.\n\nDisputed: Murf, Webflow.".encode()).decode().rstrip("=") + msg = {"threadId": "t/184", "snippet": "Run-rate", "payload": {"mimeType": "multipart/alternative", + "headers": [{"name": "Subject", "value": "Re: vendor spend"}, {"name": "To", "value": "dana@x.co"}], + "parts": [{"mimeType": "text/html", "body": {"data": "PGI-aGk8L2I-"}}, + {"mimeType": "text/plain", "body": {"data": body}}]}} + text = mg._gmail_text(json.dumps(msg)) + assert text.startswith("Subject: Re: vendor spend\nTo: dana@x.co\nCc: \nThread: t/184\n\nRun-rate is $4,210") + assert mg._format(text.split("\n\n", 1)[1], {"max_paragraphs": 2}) == (True, "format ok") + + +LINED = json.loads(json.dumps(PARAMS)) +LINED["milestones"][0]["line"] = "Make me a sheet of every subscription." +LINED["milestones"][1]["line"] = "Now put what you found on the cut-list card. Don't email anyone yet." + + +@pytest.mark.asyncio +async def test_when_the_sim_sends_a_later_line_the_hook_follows_it_before_the_agent_acts(): + w = world() + w["gmail_sent"] = {"messages": [{"id": "a"}, {"id": "b"}]} # M1 fails on quiet (baseline 0) + env, records = Env(w), [] + t = Turn(env, records, 1, reply="ok thanks.\n\nNow put what you found on the cut-list card. Don't email anyone yet.") + await post_turn(t, LINED) + r = records[-1] + assert r["decision"] == "nudge" and r["followed_sim"] == "M2" and r["next_index"] == 1 + assert r["baselines"] == {"M2:m2-quiet:0": 2} # taken now, before the agent works on M2 + t2 = Turn(env, records, 2) + await post_turn(t2, LINED) # M2 is checked now, against its own baseline: no comment yet + assert records[-1]["milestone"] == "M2" and t2.notes == ["Did the comment go on the card?"] + assert records[-1]["nudges"] == 1 + assert _status(t2) == [("M1", "passed_over", 1, 1, 1), ("M2", "open", 2, None, 1)] + + +@pytest.mark.asyncio +async def test_the_sim_milestone_field_moves_the_hook_when_there_is_no_line(): + env, records = Env(world()), [] + await post_turn(Turn(env, records, 1, sim_fields={"milestone": "M2"}), PARAMS) + assert records[-1]["followed_sim"] == "M2" + await post_turn(Turn(env, records, 2, sim_fields={"milestone": "M1"}), PARAMS) # never moves back + assert records[-1]["milestone"] == "M2" and "followed_sim" not in records[-1] + + +@pytest.mark.asyncio +async def test_the_same_sim_message_twice_in_a_row_ends_the_conversation(): + env, records = Env(world()), [] + assert (await post_turn(Turn(env, records, 1, reply="thanks, that's all for now"), PARAMS))["message"] + # The repeat still reaches the agent (a hook that asked returns the answer); the next turn ends unasked. + assert (await post_turn(Turn(env, records, 2, reply="Thanks - that's all for now!"), PARAMS))["message"] + assert records[-1]["idle"] is True + t3 = Turn(env, records, 3) + assert await post_turn(t3, PARAMS) == {"end": "sim_idle"} + assert t3.notes == [] and records[-1]["end"] == "sim_idle" + + +@pytest.mark.asyncio +async def test_an_unknown_judge_gate_neither_fails_nor_nudges(monkeypatch): + async def judge(spec, statement, text): + return None, "judge unknown: JSONDecodeError" + + monkeypatch.setattr(mg, "_judge", judge) + params = json.loads(json.dumps(PARAMS)) + params["milestones"][0]["gates"].append( + {"id": "m1-shape", "nudge": "Can it show a total?", "check": {"artifact": "sheet", "judge": "has a total"}}) + w = world() + w["drive_list"] = {"files": [SHEET]} + env, records = Env(w), [] + t = Turn(env, records, 1) + await post_turn(t, params) + assert records[-1]["decision"] == "passed" and records[-1]["gates"][3]["passed"] is None + assert t.notes == ["M1 is done. Open M2 now: send its line."] + + +@pytest.mark.asyncio +async def test_the_judge_retries_a_cut_off_reply_once(monkeypatch): + import sys + import types + replies = ['{"passed": true, "why": "the sheet has a tot', '{"passed": true, "why": "has a total"}'] + posts = [] + + class Resp: + def __init__(self, content): + self.content = content + + def raise_for_status(self): + pass + + def json(self): + return {"choices": [{"message": {"content": self.content}}]} + + class Client: + async def __aenter__(self): + return self + + async def __aexit__(self, *a): + return False + + async def post(self, url, json, headers, timeout): + posts.append(json) + return Resp(replies[len(posts) - 1]) + + class Config: + def get_litellm_base_url(self): + return "http://llm" + + def get_litellm_api_key(self): + return "k" + + def get_model_headers(self, base): + return {} + + monkeypatch.setattr("httpx.AsyncClient", lambda: Client()) + cfg = types.ModuleType("agent_env.config") + cfg.get_config = lambda: Config() + monkeypatch.setitem(sys.modules, "agent_env.config", cfg) + assert await mg._judge({"judge_model": "m"}, "has a total", "text") == (True, "has a total") + assert len(posts) == 2 and posts[0]["max_tokens"] >= 1000 + replies[1] = replies[0] + posts.clear() + passed, why = await mg._judge({"judge_model": "m"}, "has a total", "text") + assert passed is None and why.startswith("judge unknown: JSONDecodeError") + + +def test_paragraphs_are_counted_in_the_body_as_a_reader_counts_them(): + reply = ("Subject: Re: Vendor spend\nTo: dana@example.com\nCc: \nThread: t1\n\n" + "Dana,\n\nGoing into Q4 the vendor subscriptions run 1,204.50 a month from the October bill.\n\n" + "Four charges to dispute:\n\n- Midjourney 60.00\n- SavvyCal 16.00\n\nThanks,\nFred") + assert mg._format(reply, {"max_paragraphs": 2}) == (True, "format ok") + assert mg._format(reply, {"max_paragraphs": 1})[0] is False + assert mg._format(reply, {"contains_all": ["Thread: t1", "Midjourney"]}) == (True, "format ok") + assert mg._format("One.\n\nTwo is here.\n\nThree is here too.", {"max_paragraphs": 2}) == ( + False, "3 paragraphs > 2") + + +def _three(**m2): + """PARAMS with M2's settings changed and an M3 (one comment on a Linear issue).""" + params = json.loads(json.dumps(PARAMS)) + params["milestones"][1].update(m2) + params["milestones"].append({"id": "M3", "gates": [{"id": "m3-linear", "nudge": "Did it go on the ticket?", + "check": {"call": {"tool": "linear_comments", "path": "comments"}, + "expect": {"count": {"min": 1}}}}]}) + return params + + +def _m1_done_and_m2_too(): + w = world() + w["drive_list"] = {"files": [SHEET]} + w["trello_comments"] = {"comments": [{"id": "c1"}]} # M2's comment, made early while M1 was open + w["linear_comments"] = {"comments": []} + return Env(w) + + +@pytest.mark.asyncio +async def test_a_next_milestone_the_agent_already_did_is_skipped(): + env, records = _m1_done_and_m2_too(), [] + t = Turn(env, records, 1) + await post_turn(t, _three()) + assert t.notes == ["M1 is done. M2 is already done too, so skip its line. Open M3 now: send its line."] + assert records[-1]["next_index"] == 2 and records[-1]["skipped"][0]["milestone"] == "M2" + assert mg._state(records)["index"] == 2 + assert _status(t) == [("M1", "passed", 1, 1, 0), ("M2", "skipped", 1, 1, 0), ("M3", "open", 2, None, 0)] + assert (t.summary["reached"], t.summary["done"]) == ("M3", 2) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("m2", [{"type": "correct"}, {"skip_if_done": False}], ids=["correct", "opted-out"]) +async def test_a_correct_or_opted_out_milestone_is_opened_even_when_done(m2): + env, records = _m1_done_and_m2_too(), [] + t = Turn(env, records, 1) + await post_turn(t, _three(**m2)) + assert t.notes == ["M1 is done. Open M2 now: send its line."] and "skipped" not in records[-1] + + +@pytest.mark.asyncio +async def test_a_milestone_with_only_no_new_gates_is_never_skipped(): + params = _three() + params["milestones"][1]["gates"] = [params["milestones"][1]["gates"][1]] # m2-quiet alone + env, records = _m1_done_and_m2_too(), [] + t = Turn(env, records, 1) + await post_turn(t, params) + assert t.notes == ["M1 is done. Open M2 now: send its line."] + + +@pytest.mark.asyncio +async def test_skipping_the_last_milestone_sends_the_wrap_up(): + env, records = _m1_done_and_m2_too(), [] + t = Turn(env, records, 1) + await post_turn(t, PARAMS) # two milestones: M2 was the last + assert t.notes == ["M1 is done. M2 is already done too, so skip its line. " + mg.DEFAULT_FINAL] + assert records[-1]["wrap_up"] is True and mg._state(records)["finished"] is True + + + +# ---- trajectory_judge --------------------------------------------------------------------------------------------- + +def _turn_messages(*calls, text=None): + """A claude-code turn trajectory: each call is (tool, input, result).""" + assistant = [{"type": "tool_use", "id": f"t{i}", "name": f"mcp__hg__{tool}", "input": inp} + for i, (tool, inp, _) in enumerate(calls)] + if text: + assistant.append({"type": "text", "text": text}) + results = [{"type": "tool_result", "tool_use_id": f"t{i}", "content": [{"type": "text", "text": res}]} + for i, (_, _, res) in enumerate(calls)] + return [{"type": "assistant", "message": {"content": assistant}}, {"type": "user", "message": {"content": results}}] + + +TRAJ_PARAMS = {"role": "auditor", "trajectory_judge_model": "traj-m", "milestones": [ + {"id": "M1", "line": "make the sheet", "gates": [ + {"id": "m1-sheet", "nudge": "I don't see the sheet.", "check": {"trajectory_judge": "The agent saves a sheet."}}]}, + {"id": "M2", "line": "comment on the ticket", "gates": [ + {"id": "m2-linear", "nudge": "Anything on the ticket?", + "check": {"trajectory_judge": "The agent comments on ENG-1."}}]}, +]} +TRAJ = { + "s3://t/1.json": _turn_messages(("gdrive_list_folder", {"folderId": "f"}, "[]" * 200), + ("gsheets_create_spreadsheet", {"title": "Subs"}, "id s1"), text="Made it."), + "s3://t/2.json": _turn_messages(("linear_create_comment", {"issueId": "ENG-1", "body": "Acme, Globex"}, "ok")), +} + + +def test_the_renderer_keeps_writes_whole_and_shortens_reads(): + text = mg.render_trajectory(TRAJ["s3://t/1.json"]) + assert "WRITE gsheets_create_spreadsheet(" in text and "read gdrive_list_folder(" in text + assert "AGENT SAYS: Made it." in text and "+240 chars" in text # the read's 400-char result is cut to 160 + assert [mg.is_write(t) for t in ("trello_get_comments", "gmail_get_messages_batch", "linear_list_comments", + "linear_create_comment", "gsheets_values_update", "gdrive_move_file")] == [ + False, False, False, True, True, True] + + +@pytest.mark.asyncio +async def test_a_trajectory_gate_judges_every_turn_so_far_with_the_open_milestones_turns_marked(monkeypatch): + mg._RENDERED.clear() + seen = [] + + evidence = {"The agent saves a sheet.": "gsheets_create_spreadsheet", + "The agent comments on ENG-1.": "linear_create_comment"} + + async def judge(spec, statement, text, *, model=None, system=mg.JUDGE_SYSTEM, max_chars=40000): + seen.append((statement, model, system, text, max_chars)) + return evidence[statement] in text, "judged on the log" + + monkeypatch.setattr(mg, "_judge", judge) + records = [] + await post_turn(Turn(Env(world()), records, 1, trajectories=TRAJ), TRAJ_PARAMS) # M1 passes after turn 1 + assert records[-1]["next_index"] == 1 and mg._state(records)["since"] == 2 + t2 = Turn(Env(world()), records, 2, trajectories=TRAJ) + await post_turn(t2, TRAJ_PARAMS) + statement, model, system, log, max_chars = seen[-1] + assert statement == "The agent comments on ENG-1." and model == "traj-m" + assert max_chars is None # the log is sized by trajectory_max_chars, never cut to an artifact's 40k + assert system == mg.TRAJECTORY_JUDGE_SYSTEM + assert "===== Turn 1 =====" in log and "===== Turn 2 (THIS STEP) =====" in log + assert "WRITE linear_create_comment(" in log and "WRITE gsheets_create_spreadsheet(" in log + assert t2.reads == ["s3://t/2.json"] # turn 1 was rendered once, at turn 1 + + +@pytest.mark.asyncio +async def test_without_trajectories_a_trajectory_gate_is_unknown_and_never_nudges(monkeypatch): + called = [] + + async def judge(*a, **kw): + called.append(1) + return False, "should not run" + + monkeypatch.setattr(mg, "_judge", judge) + records = [] + t = Turn(Env(world()), records, 1) # no trajectories + await post_turn(t, TRAJ_PARAMS) + gate = records[-1]["gates"][0] + assert gate["passed"] is None and gate["why"].startswith("unknown") and not called + assert records[-1]["decision"] == "hold" and t.notes == [mg.HOLD_NOTE] # nothing checked: hold, never pass + + +def test_the_evidence_cuts_the_oldest_turns_before_the_step_first(): + texts = [(1, "a" * 100), (2, "b" * 100), (3, "c" * 100)] + log = mg._evidence(texts, range(3, 4), 260) + assert "Turn 1" not in log and "Turn 2 =====" in log and "Turn 3 (THIS STEP)" in log + + + +@pytest.mark.asyncio +async def test_a_step_turn_whose_trajectory_wasnt_fetched_makes_the_gate_unknown_not_a_fail(monkeypatch): + mg._RENDERED.clear() + called = [] + + async def judge(*a, **kw): + called.append(1) + return False, "should not run" + + monkeypatch.setattr(mg, "_judge", judge) + records = [] + t = Turn(Env(world()), records, 1, trajectories={None: None}) # turn 1's fetch failed: its url is None + await post_turn(t, TRAJ_PARAMS) + gate = records[-1]["gates"][0] + assert gate["passed"] is None and "turn(s) [1]" in gate["why"] and not called + # Nothing could be checked: no nudge on missing evidence, and no move on either; the hold counts toward max_nudges. + assert t.notes == [mg.HOLD_NOTE] and records[-1]["decision"] == "hold" and "next_index" not in records[-1] + assert mg._state(records)["nudges"] == 1 + + +@pytest.mark.asyncio +async def test_the_note_that_opens_a_milestone_carries_its_line_so_any_user_sim_can_send_it(): + w = world() + w["drive_list"] = {"files": [SHEET]} + env, records = Env(w), [] + t = Turn(env, records, 1) + await post_turn(t, LINED) + assert t.notes == ["M1 is done. Open M2 now: send this line: Now put what you found on the cut-list card. " + "Don't email anyone yet."] + + +@pytest.mark.asyncio +async def test_a_gates_declared_type_is_the_summarys_even_when_a_judge_checks_it(monkeypatch): + # A task's rubric can call a criterion an action and still have it judged on the trajectory. + mg._RENDERED.clear() + + async def judge(spec, statement, text, *, model=None, system=mg.JUDGE_SYSTEM, max_chars=40000): + return True, "judged on the log" + + monkeypatch.setattr(mg, "_judge", judge) + params = copy.deepcopy(TRAJ_PARAMS) + params["milestones"][0]["gates"][0]["type"] = "action" + turn = Turn(Env(world()), [], 1, trajectories=TRAJ) + await post_turn(turn, params) + + assert turn.summary["milestones"][0]["gates"] == {"m1-sheet": {"passed": True, "type": "action"}} + assert turn.summary["milestones"][1]["gates"] == {"m2-linear": {"passed": True, "type": "content"}} # no type given: from its check + + +class ErrEnv(Env): + """Env whose ``failing`` tools answer with a tool error.""" + + def __init__(self, state, failing=()): + super().__init__(state) + self.failing = set(failing) + + async def call_tool(self, tool, args, role): + if tool in self.failing: + self.calls.append((tool, args, role)) + return {"isError": True, "content": [{"type": "text", "text": "rate limited"}]} + return await super().call_tool(tool, args, role) + + +def _two_counts(first_open=True): + """M1 passes at once; M2 watches two tools with different starting counts.""" + return {"role": "r", "milestones": [ + {"id": "M1", "gates": [{"id": "m1", "nudge": "n", "check": {"call": {"tool": "ok"}, "expect": "exists"}}]}, + {"id": "M2", "line": "next", "skip_if_done": False, "gates": [ + {"id": "q-a", "nudge": "n", "check": {"no_new": [{"tool": "a", "path": "items"}]}}, + {"id": "q-b", "nudge": "n", "check": {"no_new": [{"tool": "b", "path": "items"}]}}]}]} + + +@pytest.mark.asyncio +async def test_two_no_new_gates_keep_their_own_baselines(): + state = {"ok": "yes", "a": {"items": []}, "b": {"items": list(range(10))}} + records = [] + await post_turn(Turn(Env(state), records, 1), _two_counts()) # M1 passes; M2's baselines: a 0, b 10 + assert records[-1]["baselines"] == {"M2:q-a:0": 0, "M2:q-b:0": 10} + state["a"] = {"items": [1, 2]} # two added where b's count would have hidden them + await post_turn(Turn(Env(state), records, 2), _two_counts()) + assert {g["id"]: g["passed"] for g in records[-1]["gates"]} == {"q-a": False, "q-b": True} + + +@pytest.mark.asyncio +async def test_a_baseline_that_cant_be_read_leaves_its_gate_unknown_and_the_step_running(): + state = {"ok": "yes", "a": {"items": []}, "b": {"items": []}} + records = [] + await post_turn(Turn(ErrEnv(state, failing={"b"}), records, 1), _two_counts()) + assert records[-1]["baselines"] == {"M2:q-a:0": 0} + await post_turn(Turn(Env(state), records, 2), _two_counts()) + verdicts = {g["id"]: (g["passed"], g["why"][:20]) for g in records[-1]["gates"]} + assert verdicts["q-a"][0] is True and verdicts["q-b"] == (None, "unknown: no baseline") + + +@pytest.mark.asyncio +async def test_an_artifact_read_that_errors_is_not_the_artifacts_text(): + params = {"role": "r", "milestones": [{"id": "M1", "artifacts": {"doc": { + "find": {"tool": "docs", "path": "files"}, "read": {"tool": "doc_read", "args": {"id": "{id}"}}}}, + "gates": [{"id": "g", "nudge": "n", "check": {"artifact": "doc", "expect": "exists"}}]}]} + records = [] + await post_turn(Turn(ErrEnv({"docs": {"files": [{"id": "d1"}]}}, failing={"doc_read"}), records, 1), params) + gate = records[-1]["gates"][0] + assert gate["passed"] is False and "tool error reading 'doc'" in gate["why"] + + +@pytest.mark.asyncio +async def test_a_milestone_that_passes_on_the_final_turn_is_passed_in_the_summary(): + params = {"role": "r", "milestones": [ + {"id": "M1", "gates": [{"id": "g", "nudge": "n", "check": {"call": {"tool": "ok"}, "expect": "exists"}}]}]} + turn = Turn(Env({"ok": "yes"}), [], 1, last=True) + await post_turn(turn, params) + row = turn.summary["milestones"][0] + assert (row["status"], row["closed_turn"]) == ("passed", 1) + + +@pytest.mark.parametrize("check, problem", [ + ({"artifact": "x", "format": {"max_paragraphs": "2"}}, "whole number"), + ({"artifact": "x", "format": {"contains_all": "robert"}}, "list of text"), + ({"call": {"tool": "t"}, "expect": {"count": {"min": "1"}}}, "whole number"), + ({"call": {"tool": "t"}, "expect": {"contains": 3}}, "must be text"), + ({"no_new": [{"tool": "t", "baseline_count": "0"}]}, "whole number"), +]) +def test_a_value_of_the_wrong_type_is_refused_at_load(check, problem): + params = {"role": "r", "milestones": [{"id": "M1", "artifacts": {"x": {"find": {"tool": "f"}}}, + "gates": [{"id": "g", "nudge": "n", "check": check}]}]} + with pytest.raises(ValueError, match=problem): + mg.check_params(params) + + +@pytest.mark.asyncio +async def test_a_trajectory_in_a_format_the_hook_cant_read_leaves_the_gate_unknown(monkeypatch): + mg._RENDERED.clear() + called = [] + + async def judge(*a, **k): + called.append(a) + return True, "x" + + monkeypatch.setattr(mg, "_judge", judge) + other = {"s3://t/g1.json": [{"type": "tool_use", "tool_name": "sheets_create", "parameters": {}}, + {"type": "message", "role": "assistant", "content": "Done."}]} + turn = Turn(Env(world()), [], 1, trajectories=other) + await post_turn(turn, TRAJ_PARAMS) + gate = turn._records[-1]["gates"][0] + assert gate["passed"] is None and "format this hook reads" in gate["why"] and not called + + +def test_a_turns_sim_fields_are_read_from_its_own_step_only(): + turn = Turn(Env(world()), [], 1) + turn.step_id = "now" + turn.metadata = {"usersim_turn_outputs": {"earlier": [{"turn": 1, "fields": {"milestone": "M3"}}], + "now": [{"turn": 1, "fields": {"milestone": "M1"}}]}} + assert mg._sim_field(turn, "milestone") == "M1" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("field, passed", [("body", False), (None, True)]) +async def test_a_field_artifact_counts_the_fields_own_paragraphs(field, passed): + draft = {"id": 1, "to": "a@x", "body": "Para one.\n\nPara two.\n\nPara three."} + artifact = {"find": {"tool": "list_drafts", "pick": "last"}, **({"field": field} if field else {})} + params = {"role": "r", "milestones": [{"id": "M1", "artifacts": {"draft": artifact}, "gates": [ + {"id": "short", "nudge": "n", "check": {"artifact": "draft", "format": {"max_paragraphs": 2}}}]}]} + records = [] + await post_turn(Turn(Env({"list_drafts": [draft]}), records, 1), params) + # As JSON the body's blank lines are escaped, so the whole item reads as one paragraph and passes wrongly. + assert records[-1]["gates"][0]["passed"] is passed + + +@pytest.mark.asyncio +async def test_the_last_milestone_is_checked_again_after_the_wrap_up_and_the_summary_shows_what_the_agent_left(): + # M2 is let go, then the agent fixes it while answering the wrap-up: the final check finds it done. + w = world() + w["drive_list"] = {"files": [SHEET]} + env, records = Env(w), [] + await post_turn(Turn(env, records, 1), PARAMS) # M1 passes + await post_turn(Turn(env, records, 2), PARAMS) # M2 nudged + await post_turn(Turn(env, records, 3), PARAMS) # M2 let go; wrap-up sent + w["trello_comments"] = {"comments": [{"text": "Vaultly cancelled"}]} # done while answering the wrap-up + t4 = Turn(env, records, 4) + assert await post_turn(t4, PARAMS) == {"end": "milestones_done"} + assert records[-1]["decision"] == "done" and records[-1]["milestone"] == "M2" + assert all(g["passed"] for g in records[-1]["gates"]) + assert _status(t4)[1] == ("M2", "passed", 2, 4, 1) # passed in the end, after the wrap-up + + +@pytest.mark.asyncio +async def test_the_wrap_up_after_every_milestone_passed_says_so(): + w = world() + w["drive_list"] = {"files": [SHEET]} + w["trello_comments"] = {"comments": [{"text": "Vaultly cancelled"}]} + env, records = Env(w), [] + await post_turn(Turn(env, records, 1), PARAMS) # M1 passes, and M2 is already done: skipped, then the wrap-up + wrap = next(r for r in records if r.get("wrap_up")) + assert wrap["note"].endswith(mg.DEFAULT_FINAL) and mg.DEFAULT_FINAL_GAVE_UP not in wrap["note"] + + +@pytest.mark.asyncio +async def test_a_milestone_with_a_gate_it_couldnt_check_is_held_not_passed(): + state = {"ok": "yes", "a": {"items": []}, "b": {"items": []}} + records = [] + await post_turn(Turn(ErrEnv(state, failing={"b"}), records, 1), _two_counts()) # M2's b baseline unread + t2 = Turn(Env(state), records, 2) + await post_turn(t2, _two_counts()) + assert records[-1]["decision"] == "hold" and t2.notes == [mg.HOLD_NOTE] + + +@pytest.mark.asyncio +async def test_a_no_new_gate_keeps_a_failure_one_call_found_when_another_has_no_baseline(): + params = {"role": "r", "milestones": [ + {"id": "M1", "gates": [{"id": "m1", "nudge": "n", "check": {"call": {"tool": "ok"}, "expect": "exists"}}]}, + {"id": "M2", "line": "next", "skip_if_done": False, "gates": [{"id": "q", "nudge": "hold off", "check": { + "no_new": [{"tool": "a", "path": "items"}, {"tool": "b", "path": "items"}]}}]}]} + state = {"ok": "yes", "a": {"items": []}, "b": {"items": []}} + records = [] + await post_turn(Turn(ErrEnv(state, failing={"b"}), records, 1), params) + state["a"] = {"items": [1]} + await post_turn(Turn(Env(state), records, 2), params) + gate = records[-1]["gates"][0] + assert gate["passed"] is False and gate["why"] == "new: a +1" + + +@pytest.mark.asyncio +async def test_a_milestone_broken_while_the_agent_answers_the_wrap_up_is_undone_in_the_summary(): + w = world() + w["drive_list"] = {"files": [SHEET]} + w["trello_comments"] = {"comments": [{"text": "Vaultly cancelled"}]} + env, records = Env(w), [] + await post_turn(Turn(env, records, 1), PARAMS) # M1 passes; M2 already done: skipped; wrap-up + assert next(r for r in records if r.get("wrap_up"))["next_index"] == 1 # the final check reads M2, the last + w["trello_comments"] = {"comments": []} # the agent removes its comment while answering the wrap-up + t2 = Turn(env, records, 2) + await post_turn(t2, PARAMS) + assert records[-1]["milestone"] == "M2" + assert _status(t2)[1][:2] == ("M2", "undone") and t2.summary["done"] == 1 diff --git a/tst/unit/task_step/test_prompt_agent_atif_copies.py b/tst/unit/task_step/test_prompt_agent_atif_copies.py index 5541fdd83..c1282bf97 100644 --- a/tst/unit/task_step/test_prompt_agent_atif_copies.py +++ b/tst/unit/task_step/test_prompt_agent_atif_copies.py @@ -559,3 +559,26 @@ async def test_an_error_code_the_sdk_wouldnt_send_isnt_kept_as_the_reason(monkey response = await run.execute(run.context(), max_conversation_turns=1) assert [(atif["status"], atif["reason"]) for atif in _atifs(response)] == [("unavailable", "http_409")] + + +@pytest.mark.asyncio +async def test_post_turn_hooks_read_each_turns_native_trajectory_while_the_runs_copies_wait(monkeypatch, tmp_path): + from tst.unit.task_step.test_prompt_agent_post_turn_hooks import _hook + run = _Run(monkeypatch, tmp_path) + context = run.context() + hook = _hook("reads", """ + async def post_turn(turn, params): + texts = [await turn.read_trajectory(n) for n in range(1, len(turn.trajectory_urls) + 1)] + turn.record({"urls": list(turn.trajectory_urls), "read": [t is not None for t in texts]}) + return None + """) + + response = await run.execute(context, post_turn_hooks=[{"file_artifact_id": hook, "params": {}}]) + + records = context.metadata["post_turn_hooks"]["solve"] + assert [r["read"] for r in records] == [[True], [True, True]] # this turn's work, while the conversation runs + assert all(url is not None and isinstance(run.read(url), list) for url in records[-1]["urls"]) # native shots + # The step's own record is still the run's copies. + assert [turn["format"] for turn in response.target_agent_per_turn_trajectories] == [ATIF, ATIF] + assert response.target_agent_per_turn_trajectory_object_urls == [t["atif"]["url"] for t in + response.target_agent_per_turn_trajectories] diff --git a/tst/unit/task_step/test_prompt_agent_built_in_user_sim.py b/tst/unit/task_step/test_prompt_agent_built_in_user_sim.py index fcd838481..8ed6b7ff7 100644 --- a/tst/unit/task_step/test_prompt_agent_built_in_user_sim.py +++ b/tst/unit/task_step/test_prompt_agent_built_in_user_sim.py @@ -564,3 +564,89 @@ async def judge(self, candidate, history, call_config, instructions=None, **_): await _gated().execute(ctx) assert len(seen) == 1 and seen[0] and "Hannah" in seen[0] + + +# ---- a milestone user keeps replying while a hook's note is in play ------------------------------------------------- +NOTE_HOOK = """ + async def post_turn(turn, params): + return None if turn.last else await turn.ask_user(note="check who the reply went to.") +""" + + +def _noted(turns: int = 3) -> PromptAgentTaskStep: + from tst.unit.task_step.test_prompt_agent_post_turn_hooks import _hook + return _step(turns=turns, post_turn_hooks=[{"file_artifact_id": _hook("noted", NOTE_HOOK), "params": {}}]) + + +def _to_agent(peers, ctx) -> list[str]: + return [r[2]["params"]["message"]["parts"][0]["text"] for r in peers.requests(ctx) + if r[1] == f"{AGENT}/a2a" and r[2].get("method") == "message/send"] + + +def _asked_user(peers, ctx) -> list[str]: + return [r[2]["params"]["message"]["parts"][0]["text"] for r in peers.requests(ctx) + if r[1] == f"{USER}/a2a" and r[2].get("method") == "message/send"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("preset", ["milestone", "chat"]) +async def test_a_user_who_always_answers_and_says_no_reply_is_asked_again_in_the_answers_own_format( + monkeypatch, preset): + peers = Peers(monkeypatch, {AGENT: [text("Sent it to Leonard."), text("Added Arthur."), text("ok")], + USER: [said("no_reply"), said("reply", "who else should be on it?"), + said("reply", "thanks")]}) + ctx = await _context(monkeypatch, preset=preset) + + result = await _noted().execute(ctx) + + assert _to_agent(peers, ctx)[:2] == ["plan my parents' visit", "who else should be on it?"] + person = {"preset": preset} + assert _asked_user(peers, ctx)[1] == user_sim_versions.retry_line(person) # not one of reply | done: format retry + assert '"no_reply"' not in user_sim_versions.retry_line(person) + first = _reads(ctx)[0] + assert (first["outcome"], first["retried"]) == ("reply", True) + assert "user_sim_note_retries" not in ctx.metadata and result.prompt_responses[-1].error_type is None + + +@pytest.mark.asyncio +async def test_a_milestone_user_who_keeps_answering_no_reply_to_a_note_ends_the_run_as_a_user_sim_error(monkeypatch): + # The format retry first, then the guard's tries, each with its own format retry: none of them a reply. + Peers(monkeypatch, {AGENT: [text("Sent it to Leonard.")], USER: [said("no_reply")] * (2 + 2 * pa.NOTE_REPLY_TRIES)}) + ctx = await _context(monkeypatch, preset="milestone") + + result = await _noted().execute(ctx) + + response = result.prompt_responses[-1] + assert response.error_type == "user_sim_error" and "no_reply" in response.error_message + assert len(ctx.metadata["user_sim_note_retries"]["talk"]) == pa.NOTE_REPLY_TRIES + + +@pytest.mark.asyncio +async def test_without_a_preset_a_no_reply_to_a_note_still_ends_the_run(monkeypatch): + peers = Peers(monkeypatch, {AGENT: [text("Sent it to Leonard.")], USER: [said("no_reply")]}) + ctx = await _context(monkeypatch) + + result = await _noted().execute(ctx) + + assert _to_agent(peers, ctx) == ["plan my parents' visit"] + assert "user_sim_note_retries" not in ctx.metadata and result.prompt_responses[-1].error_type is None + + +@pytest.mark.asyncio +async def test_a_milestone_users_gate_rewrite_that_comes_back_as_no_reply_is_asked_again(monkeypatch): + from tst.unit.task_step.test_prompt_agent_post_turn_hooks import _hook + peers = Peers(monkeypatch, {AGENT: [text("Sent it to Leonard."), text("Added Arthur."), text("ok")], + USER: [said("reply", _SWAP), said("no_reply"), said("reply", "who else should be on it?"), + said("reply", "thanks")]}) + ctx = await _context(monkeypatch, preset="milestone") + hook = _hook("noted-gated", NOTE_HOOK) + + step = _step(turns=3, user_sim_gate={"patterns": True, "judge_model": "judge"}, + post_turn_hooks=[{"file_artifact_id": hook, "params": {}}]) + result = await step.execute(ctx) + + # The gate held the swap back; its rewrite came back as no_reply, which a milestone user may not give, so it was + # asked again in the answer's own format, and the turn went on. + assert _to_agent(peers, ctx)[:2] == ["plan my parents' visit", "who else should be on it?"] + assert _asked_user(peers, ctx)[2] == user_sim_versions.retry_line({"preset": "milestone"}) + assert "user_sim_invalid" not in ctx.metadata and result.prompt_responses[-1].error_type is None diff --git a/tst/unit/task_step/test_prompt_agent_post_turn_hooks.py b/tst/unit/task_step/test_prompt_agent_post_turn_hooks.py index 0a0cd9f03..b6781c034 100644 --- a/tst/unit/task_step/test_prompt_agent_post_turn_hooks.py +++ b/tst/unit/task_step/test_prompt_agent_post_turn_hooks.py @@ -153,6 +153,46 @@ async def test_a_hook_that_is_not_an_async_post_turn_fails_the_step_before_the_a assert peers.raw == [] +CHECKS_PARAMS = """ + def check_params(params): + if "role" not in params: + raise ValueError("needs role") + + async def post_turn(turn, params): + turn.record({"role": params["role"]}) + return None +""" + + +@pytest.mark.asyncio +async def test_a_hook_that_refuses_its_params_fails_the_step_before_the_agent_is_prompted(monkeypatch): + peers = EnvPeers(monkeypatch, {AGENT: []}) + + with pytest.raises(ValueError, match="post-turn hook 'checks' refused its params: needs role"): + await _step(_hook("checks", CHECKS_PARAMS)).execute(_context()) + + assert peers.raw == [] + + +@pytest.mark.asyncio +async def test_a_hook_whose_params_pass_its_check_runs(monkeypatch): + EnvPeers(monkeypatch, {AGENT: [text("done")]}) + ctx = _context() + + await _step(_hook("checks", CHECKS_PARAMS), turns=1, params={"role": "r"}).execute(ctx) + + assert [r["role"] for r in _recorded(ctx)] == ["r"] + + +@pytest.mark.asyncio +async def test_a_check_params_that_is_async_fails_the_step(monkeypatch): + EnvPeers(monkeypatch, {AGENT: []}) + source = "async def check_params(params):\n pass\n\nasync def post_turn(turn, params):\n return None\n" + + with pytest.raises(ValueError, match="check_params must be `def check_params"): + await _step(_hook("async-check", source)).execute(_context()) + + @pytest.mark.asyncio async def test_a_hook_with_a_dataclass_and_postponed_annotations_loads_and_close_unregisters_it(): source = """ @@ -193,6 +233,41 @@ async def test_a_hook_message_is_the_agents_next_prompt_and_no_user_side_is_aske assert _stored(ctx, peers)["messages"][2] == {"role": "user", "parts": text("wake 1")} +@pytest.mark.asyncio +async def test_a_hooks_summary_is_one_object_per_hook_the_latest_kept(monkeypatch): + EnvPeers(monkeypatch, {AGENT: [text("one"), text("two"), text("three")]}) + ctx = _context() + counts = _hook("counts", """ + async def post_turn(turn, params): + turn.summarize({"turns": turn.number, "last": turn.last}) + return {"message": "go on"} + """) + quiet = _hook("quiet", """ + async def post_turn(turn, params): + if turn.number == 1: + turn.summarize({}) + return None + """) + + await _step(quiet, counts, turns=3).execute(ctx) # quiet first: a hook that answers ends the turn's hooks + + assert ctx.metadata["post_turn_hook_summaries"] == {"talk": {"counts": {"turns": 3, "last": True}, "quiet": {}}} + assert "post_turn_hooks" not in ctx.metadata # a summary is not a record + + +@pytest.mark.asyncio +async def test_a_summary_that_is_not_an_object_fails_the_turn(monkeypatch): + EnvPeers(monkeypatch, {AGENT: [text("one")]}) + ctx = _context() + hook = _hook("bad", """ + async def post_turn(turn, params): + turn.summarize(["M1"]) + """) + + with pytest.raises(Exception, match="a hook's summary is an object"): + await _step(hook, turns=1).execute(ctx) + + @pytest.mark.asyncio async def test_an_end_closes_the_conversation_recording_its_closing_message(monkeypatch): peers = EnvPeers(monkeypatch, {AGENT: [text("one")]}) @@ -618,6 +693,66 @@ async def test_with_no_armed_env_clock_stored_messages_carry_none(monkeypatch): assert all("env_clock" not in m for m in _stored(ctx, peers)["messages"]) +@pytest.mark.asyncio +async def test_a_hook_sees_each_turns_trajectory_so_far_and_can_read_it(monkeypatch): + from agent_env.a2a_agent import A2AAgent + from agent_env.config import get_config + from agent_env.task_step.task_steps import prompt_agent as pa + + EnvPeers(monkeypatch, {AGENT: [text("one"), text("two"), text("three")]}) + ctx = _context() + ctx.deployed_agents[0].a2a_card = {"capabilities": {"extensions": [{"uri": A2AAgent.EXT_TRAJECTORY, "params": {}}]}} + stored = {"task-1": b'[{"turn": 1}]', "task-3": b'[{"turn": 3}]'} # turn 2's agent returned none + + async def fetch(url, ext, task_id, prefix, name, *, sandbox_type, headers, card=None): + if task_id not in stored: + return pa.StoredTrajectory() + return pa.StoredTrajectory(get_config().get_object_store().put(f"traj/{task_id}.json", stored[task_id])) + + monkeypatch.setattr(pa, "fetch_native_trajectory", fetch) + hook = _hook("reads", """ + async def post_turn(turn, params): + urls = turn.trajectory_urls + texts = [await turn.read_trajectory(n) for n in range(1, len(urls) + 1)] + try: + await turn.read_trajectory(len(urls) + 1) + ahead = "read" + except IndexError: + ahead = "refused" + turn.record({"count": len(urls), "missing": [n for n, u in enumerate(urls, 1) if u is None], + "texts": texts, "ahead": ahead}) + return {"message": f"wake {turn.number}"} + """) + + await _step(hook, turns=3).execute(ctx) + + assert [(e["count"], e["missing"], e["texts"], e["ahead"]) for e in _recorded(ctx)] == [ + (1, [], ['[{"turn": 1}]'], "refused"), + (2, [2], ['[{"turn": 1}]', None], "refused"), + (3, [2], ['[{"turn": 1}]', None, '[{"turn": 3}]'], "refused"), + ] + + +@pytest.mark.asyncio +async def test_an_agent_that_offers_no_trajectories_hands_a_hook_none(monkeypatch): + EnvPeers(monkeypatch, {AGENT: [text("one")]}) + ctx = _context() + hook = _hook("none", """ + async def post_turn(turn, params): + try: + await turn.read_trajectory(turn.number + 1) + ahead = "read" + except IndexError: + ahead = "refused" + turn.record({"urls": list(turn.trajectory_urls), "this_turn": await turn.read_trajectory(turn.number), + "ahead": ahead}) + return None + """) + + await _step(hook, turns=1).execute(ctx) + + # A turn that happened has no trajectory (None), not an error; one that hasn't is still refused. + assert [(e["urls"], e["this_turn"], e["ahead"]) for e in _recorded(ctx)] == [([], None, "refused")] @pytest.mark.asyncio async def test_a_note_passed_after_the_user_side_was_asked_raises_instead_of_being_dropped(): diff --git a/tst/unit/task_step/test_user_sim_presets.py b/tst/unit/task_step/test_user_sim_presets.py new file mode 100644 index 000000000..dbf212e23 --- /dev/null +++ b/tst/unit/task_step/test_user_sim_presets.py @@ -0,0 +1,134 @@ +"""The built-in user sim's presets: chat keeps today's single-session prompt except its answer format, always_on keeps +today's prompt byte for byte, milestone adds how the user takes a post-turn hook's note, each names the features a judge's rules may depend on, and a preset that doesn't fit +the task's other steps is refused when the task loads.""" + +from __future__ import annotations + +import hashlib + +import pytest + +from agent_env.task import Task +from agent_env.task_step.task_steps.agent import user_sim_versions as usv +from agent_env.task_step.task_steps.agent.deploy_user_sim_agent import recorded_instructions +from tst.unit.task_step.test_deploy_user_sim_agent import HANNAH, PERSON, PROMPT, _Deploy, _published, _step + +PROMPT_AGENT = {"id": "talk", "type": "prompt_agent", "prompt": "sort the weekend", "agent_name": "solver", + "user_agent_name": "hannah", "max_conversation_turns": 6} +HOOK = [{"file_artifact_id": "milestone-gates", "params": {}}] + + +def _person(**over) -> dict: + return {**PERSON, **over} + + +# ---- the prompt ---------------------------------------------------------------------------------------------------- +@pytest.mark.asyncio +async def test_an_always_on_preset_keeps_todays_prompt_byte_for_byte(monkeypatch): + deploy = _Deploy(monkeypatch) + context = await deploy.run(_step(preset="always_on")) + + assert deploy.fields("system_prompt") == [PROMPT] + record = context.metadata["user_sims"]["hannah"] + assert record["prompt_sha256"] == hashlib.sha256(PROMPT.encode()).hexdigest() + assert record["preset"] == "always_on" + + +def test_a_chat_preset_writes_todays_single_session_prompt_but_always_answers(): + single = _person(done_ends_run=True) + chat = usv.system_prompt({**single, "preset": "chat"}) + assert chat == usv.system_prompt(single).replace(usv.ANSWER_LINE, usv.answer_line({"preset": "chat"})) + assert usv.ANSWER_LINE not in chat # the persona's own lines may still mention it; the answer format doesn't + + +@pytest.mark.parametrize("preset, allowed", [(None, ["reply", "no_reply", "done"]), ("always_on", ["reply", "no_reply", "done"]), + ("chat", ["reply", "done"]), ("milestone", ["reply", "done"])]) +def test_the_answer_format_offers_no_reply_only_to_a_user_who_may_stay_quiet(preset, allowed): + person = _person(done_ends_run=preset != "always_on", **({"preset": preset} if preset else {})) + fmt = usv.setup(usv.VERSION, person)["output_format"] + assert fmt["schema"]["properties"]["outcome"]["enum"] == allowed + read = {"time": "2026-11-16T09:00:00Z", "assistant_messages": [{"at": "2026-11-16T09:00:00Z", "text": "done?"}], + "phone": [], "you_sent": [], "done_ends_run": preset != "always_on"} + rendered = usv.render(person, [], read) + assert rendered.endswith("Answer in JSON: " + usv.answer_line(person)) + assert ("don't reply" in rendered) == ("no_reply" in allowed) + if preset is None: + assert fmt is usv.OUTPUT_FORMAT # today's, unchanged + + +def test_a_milestone_preset_tells_the_user_how_to_take_a_hooks_note_and_when_it_is_done(): + chat = usv.system_prompt(_person(done_ends_run=True)) + milestone = usv.system_prompt(_person(done_ends_run=True, preset="milestone")) + + assert usv.MILESTONE_LINES in milestone and usv.MILESTONE_LINES not in chat + assert usv.DONE_MILESTONE in milestone and usv.DONE_ENDS_RUN not in milestone + + +@pytest.mark.asyncio +async def test_the_prompt_rebuilt_from_the_record_is_the_one_the_milestone_user_got(monkeypatch): + deploy = _Deploy(monkeypatch) + context = await deploy.run(_step(preset="milestone", multi_day=False)) + record = context.metadata["user_sims"]["hannah"] + + assert recorded_instructions(record, {}) == deploy.fields("system_prompt")[0] + + +# ---- features ------------------------------------------------------------------------------------------------------ +def test_features_follow_the_sections_the_persona_fills_in_and_the_preset(): + plain = {"name": "Ada Park", "description": {"who_you_are": ["You run finance."]}, "done_ends_run": True} + assert usv.features(plain) == frozenset() + assert usv.features({**plain, "description": {**plain["description"], "already_told": ["The budget is 5k."]}, + "permissions": {"ask_first": ["sending money"]}}) == {"told_lines", "permission_rules"} + assert usv.features({**plain, "done_ends_run": False}) == {"phone"} + assert usv.features({**plain, "preset": "milestone"}) == {"milestones", "hook_notes"} + assert set(usv.features(_person(done_ends_run=False))) <= set(usv.FEATURES) + + +@pytest.mark.asyncio +async def test_the_record_carries_the_features_for_the_judge(monkeypatch): + record = await _published(monkeypatch, _step(preset="milestone", multi_day=False)) + + assert record["preset"] == "milestone" + assert {"milestones", "hook_notes"} <= set(record["features"]) + assert "phone" not in record["features"] + + +@pytest.mark.asyncio +async def test_a_step_without_a_preset_records_none_and_its_features(monkeypatch): + record = await _published(monkeypatch, _step()) + + assert record["preset"] is None and "phone" in record["features"] + + +# ---- checks -------------------------------------------------------------------------------------------------------- +@pytest.mark.parametrize("fields, problem", [ + ({"preset": "weekly"}, "is not one of"), + ({"preset": "milestone", "multi_day": True}, "multi_day must be false"), + ({"preset": "chat", "multi_day": True}, "multi_day must be false"), +]) +def test_a_bad_preset_is_refused(fields, problem): + with pytest.raises(ValueError, match=problem): + _step(**fields) + + +def _task(*steps: dict) -> Task: + sim = {"id": "user", "type": "deploy_user_sim_agent", "a2a_agent_id": "sim-image", "agent_name": "hannah", + "model": "sim-model", "opening_prompt": PERSON["opening"]["text"], "persona": HANNAH} + return Task.from_dict({"id": "t", "version": 1, "steps": [{**sim, **steps[0]}, *steps[1:]]}) + + +def test_a_milestone_user_with_a_hooked_conversation_loads(): + task = _task({"preset": "milestone", "multi_day": False}, {**PROMPT_AGENT, "post_turn_hooks": HOOK}) + assert [s.type for s in task.steps] == ["deploy_user_sim_agent", "prompt_agent"] + + +@pytest.mark.parametrize("steps, problem", [ + (({"preset": "milestone", "multi_day": False}, PROMPT_AGENT), "has no post_turn_hooks"), + (({"preset": "milestone", "multi_day": False},), "no prompt_agent step talks to it"), + (({"preset": "chat", "multi_day": False}, + {"id": "week", "type": "always_on", "user_sim": "hannah", "prompt_id": "ask", "agent_name": "solver"}), + "one conversation, but always_on"), +]) +def test_a_preset_that_doesnt_fit_the_task_is_refused_when_it_loads(steps, problem): + with pytest.raises(ValueError, match=problem): + _task(*steps) diff --git a/tst/unit/test_clean_install_wheel.py b/tst/unit/test_clean_install_wheel.py index 44522dbdd..7a0631810 100644 --- a/tst/unit/test_clean_install_wheel.py +++ b/tst/unit/test_clean_install_wheel.py @@ -73,6 +73,7 @@ def test_the_gate_checks_the_folder_of_every_shipped_bundle(): "desktop": "src/agent_env/examples/desktop", "drivers": "src/agent_env/drivers", "echo-mcp": "src/agent_env/examples/echo-mcp", "hello": "src/agent_env/examples/hello", "mail-mcp": "src/agent_env/examples/mail-mcp", + "milestone-gates": "src/agent_env/examples/milestone-gates", "next-env-event": "src/agent_env/examples/next-env-event"}