From 254fa27a8f9e72e4dc54273dc3c4b126ed81e4eb Mon Sep 17 00:00:00 2001 From: kaihackney-scale Date: Wed, 25 Nov 2026 00:02:41 -0500 Subject: [PATCH 1/2] feat(milestone-gates): revisions of a milestone, each with its own gates A milestone entry can now name the milestone it revises (`group`), for a long task that asks for the same work again, changed. Revisions follow their milestone one after another and are checked at load; each is opened, nudged and given up on like any milestone, and by default never skipped as done. `carry_gates: true` re-checks the previous revision's gates (and keeps its artifacts), a gate with the same id overriding the carried one. The summary nests revisions under their milestone with a roll-up (furthest revision reached, its status, nudges, revisions done); a task without revisions keeps its summary's shape. After the wrap-up the hook also re-checks the latest revision of every earlier milestone on its state gates, so one the agent broke later is `undone`. Co-Authored-By: Claude Opus 5.5 --- .../examples/milestone-gates/README.md | 57 ++++- .../artifacts/milestone-gates/hook.py | 161 ++++++++++++--- .../task_step/test_milestone_gates_hook.py | 195 ++++++++++++++++++ 3 files changed, 381 insertions(+), 32 deletions(-) diff --git a/src/agent_env/examples/milestone-gates/README.md b/src/agent_env/examples/milestone-gates/README.md index 12c21eeef..73938788b 100644 --- a/src/agent_env/examples/milestone-gates/README.md +++ b/src/agent_env/examples/milestone-gates/README.md @@ -48,7 +48,8 @@ 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` +- `milestones`: `[{id, line?, type?, blocking?, max_nudges?, skip_if_done?, show?, group?, carry_gates?, artifacts, + gates}]`, in order (`group` and `carry_gates`: see Revisions below). `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. @@ -84,7 +85,7 @@ doesn't define, a gate `type` outside format, action and content, repeated 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 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. It checks every earlier milestone's state gates again too (see Revisions below). 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 @@ -96,7 +97,7 @@ without going through its records (`turn.summarize`), at "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 +A milestone's `status` is `not_reached`, `open`, `passed`, `skipped` (done before it opened), `undone` (done, then found broken by the check after the wrap-up), `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 @@ -109,3 +110,53 @@ gates need the agent to offer per-turn trajectories (`turn.trajectory_urls`); wi 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. + +## Revisions + +A long task often asks for the same piece of work again, changed: a report, then "make it tables", then "it's going +public now, take out the internal numbers". Each ask is a revision of the milestone, with gates of its own. Write it as +the next entry with `group` naming the milestone it revises (or an earlier revision of it): + +```json +"milestones": [ + {"id": "M1", "artifacts": {"report": {"find": {"tool": "docs_list", "path": "files", "where": {"name": "report"}}, + "read": {"tool": "doc_read", "args": {"id": "{id}"}}}}, + "gates": [ + {"id": "m1-report", "nudge": "I don't see the report.", "check": {"artifact": "report", "expect": "exists"}}, + {"id": "m1-total", "nudge": "Does it have the quarter's total?", + "check": {"artifact": "report", "judge": "The report gives the quarter's total spend."}}]}, + {"id": "M1-r2", "group": "M1", "carry_gates": true, "line": "Can you put that in tables?", + "gates": [{"id": "m1-tables", "nudge": "It's still hard to scan.", + "check": {"artifact": "report", "format": {"contains_all": ["|"]}}}]}, + {"id": "M1-r3", "group": "M1", "carry_gates": true, "max_nudges": 2, "blocking": false, + "line": "This is going out publicly now, so no internal numbers.", + "gates": [{"id": "m1-total", "nudge": "Keep the total, but nothing internal-only.", + "check": {"artifact": "report", "judge": "The report gives the total and no internal-only figures."}}]}, + {"id": "M2", "line": "Now send it to the team.", + "gates": [{"id": "m2-sent", "nudge": "Did it go out?", + "check": {"call": {"tool": "gmail_sent", "path": "messages"}, "expect": {"count": {"min": 1}}}}]}] +``` + +- A milestone's revisions come right after it, in order; `check_params` refuses a `group` that names no earlier + milestone, or a revision that doesn't follow its milestone or that milestone's last revision. +- Each revision is opened, nudged, let go and ended like any milestone, with its own `line`, `max_nudges` and + `blocking`. Giving up is per revision: a revision let go after `max_nudges` opens the next entry, the next revision + or the next milestone, and a `blocking` revision that never passes ends the conversation + (`gate_never_passed:`). +- A revision is never skipped as already done unless it sets `skip_if_done: true`: it asks for a change, and work + that already passes its gates may still be the work from before. +- `carry_gates: true` checks the previous revision's gates too, and keeps its artifacts, so a revision can't pass by + breaking what the one before it got right. A gate the revision writes with the id of a carried one replaces it (above, + M1-r3's `m1-total`); any other repeated gate id is refused. Without `carry_gates` a revision checks only its own gates. + +After the wrap-up the hook checks the last milestone again, and the latest revision of every earlier milestone (the +latest entry, for a milestone without revisions) on its state gates: `call`, `artifact` checks and judges, not `no_new` +or `trajectory_judge`, which are about the turns it was open. One found broken is `undone`. Passing there doesn't +mark a revision that was let go as passed, since its other gates weren't checked again. + +In the summary a milestone with revisions holds them in `revisions`, each the usual row with its `revision` number +(1 is the milestone as first written) and its carried gates marked `"carried": true`; the milestone's own row rolls them +up: the `status` and `closed_turn` of the furthest revision reached (`reached_revision`), the turn the first opened, the +nudges of all of them and `revisions_done`. The summary's `done` and `total` count milestones, `revisions_done` and +`revisions_total` revisions, and `reached_revision` names the furthest revision. A task without revisions has the +same summary as before. 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 index 60dd555e4..386c13df1 100644 --- a/src/agent_env/examples/milestone-gates/artifacts/milestone-gates/hook.py +++ b/src/agent_env/examples/milestone-gates/artifacts/milestone-gates/hook.py @@ -31,12 +31,22 @@ 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]}] + milestones [{id, line?, type?, skip_if_done?, blocking?, max_nudges?, show?, group?, carry_gates?, + 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. + ``group`` makes an entry a revision of an earlier milestone (its id): a change asked of work already + done, with gates of its own. A milestone's revisions follow it one after another, each opened, + nudged, given up on and ended like any milestone, and by default never skipped. ``carry_gates: + true`` checks the previous revision's gates (and keeps its artifacts) too, but for any gate the + revision writes with the same id, which replaces it. The summary nests revisions under their + milestone. + +After the wrap-up is answered, the last milestone is checked once more, and so is the latest revision of every earlier +milestone, on its state gates only (not no_new or trajectory_judge, which are about the turns it was open): one found +broken is ``undone``. 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 @@ -70,7 +80,9 @@ # 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"} +MILESTONE_KEYS = {"id", "line", "type", "skip_if_done", "blocking", "max_nudges", "show", "artifacts", "gates", "group", + "carry_gates"} +DONE = ("passed", "skipped") # the statuses that count a milestone done 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 " @@ -112,11 +124,23 @@ async def _post_turn(turn, spec): 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. + # Check the work once more: the agent may have changed it while answering the wrap-up, or broken an earlier + # milestone's work since, and the summary should match what it left, as the task's final rubric will. + env = _env(turn, spec) m = milestones[state["index"]] - gates = await _run_gates(turn, spec, _env(turn, spec), m, state) - turn.record({"decision": "done", "milestone": m["id"], "gates": gates}) + gates = await _run_gates(turn, spec, env, m, state) + record = {"decision": "done", "milestone": m["id"], "gates": gates} + earlier = [] + for o in _latest_revisions(spec): + if o["group"] == m["group"]: + continue + kept = [g for g in o["gates"] if _state_check(g["check"])] + if kept: + earlier.append({"milestone": o["id"], "gates": await _run_gates( + turn, spec, env, {**o, "gates": kept}, {**state, "baselines": {}})}) + if earlier: + record["final_checks"] = earlier + turn.record(record) 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"}) @@ -203,10 +227,11 @@ def _gate_type(check: dict) -> str: 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), + undone (done, then found broken by the check after 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.""" + reached, how many were done, and the end reason once the hook ended the conversation. With revisions, each + milestone's row holds its revisions' rows and rolls them up (``_rollup``).""" if not spec["enabled"]: return {"enabled": False} milestones = spec["milestones"] @@ -252,12 +277,50 @@ def verdicts(row, gates): 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 + # An earlier milestone's latest revision, checked on its state gates only: those passing don't prove a + # revision let go is done, so the check can only find one broken. + for f in r.get("final_checks") or []: + earlier = by_id.get(f["milestone"]) + if earlier is None: + continue + verdicts(earlier, f["gates"]) + if any(g["passed"] is False for g in f["gates"]) and earlier["status"] in ("passed", "skipped"): + earlier.update(status="undone", closed_turn=turn) 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} + for m, row in zip(milestones, rows): + for gid in [g["id"] for g in m["gates"] if g.get("carried")]: + if gid in row["gates"]: + row["gates"][gid]["carried"] = True + groups: dict[str, list[dict]] = {} + for m, row in zip(milestones, rows): + groups.setdefault(m["group"], []).append(row) + if all(len(revs) == 1 for revs in groups.values()): # no revisions: one row per milestone, as always + 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 DONE for row in rows), "total": len(rows), + "end": end, "milestones": rows} + out = [revs[0] if len(revs) == 1 else _rollup(head, revs) for head, revs in groups.items()] + reached = [row for row in out if row["status"] != "not_reached"] + return {"enabled": True, "reached": reached[-1]["id"] if reached else None, + "reached_revision": (reached[-1].get("reached_revision", reached[-1]["id"]) if reached else None), + "done": sum(row["status"] in DONE for row in out), "total": len(out), + "revisions_done": sum(row["status"] in DONE for row in rows), "revisions_total": len(rows), + "end": end, "milestones": out} + + +def _rollup(head: str, revs: list[dict]) -> dict: + """A milestone with revisions: its revisions' rows (numbered from 1, the milestone as first written), under the + status of the furthest one reached, as that's the work the user last asked for.""" + for k, rev in enumerate(revs, 1): + rev["revision"] = k + reached = [rev for rev in revs if rev["status"] != "not_reached"] + top = reached[-1] if reached else None + return {"id": head, "status": top["status"] if top else "not_reached", + "opened_turn": reached[0]["opened_turn"] if reached else None, + "closed_turn": top["closed_turn"] if top else None, "nudges": sum(rev["nudges"] for rev in revs), + "reached_revision": top["id"] if top else None, "revisions_done": sum(rev["status"] in DONE for rev in revs), + "revisions": revs} async def _skips(turn, spec, env, state, nxt) -> tuple[int, list[dict]]: @@ -373,6 +436,20 @@ async def _run_gates(turn, spec, env, m, state) -> list[dict]: return sorted(out, key=lambda r: order[r["id"]]) +def _state_check(check: dict) -> bool: + """A gate on the state the agent left, which still means something after its milestone closed: not a no_new + (nothing added while the milestone was open) or a trajectory_judge (what the agent did during it).""" + return "no_new" not in check and "trajectory_judge" not in check + + +def _latest_revisions(spec: dict) -> list[dict]: + """Each milestone's last revision (a milestone without revisions is its own), in order.""" + last: dict[str, dict] = {} + for m in spec["milestones"]: + last[m["group"]] = m + return list(last.values()) + + 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 @@ -828,24 +905,44 @@ def _spec(params: dict) -> dict: milestones = params.get("milestones") if not isinstance(milestones, list) or not milestones: raise ValueError("milestone-gates needs milestones") - out = [] + out, authored = [], [] # authored: (gate id, overrides a carried gate) for every gate the spec writes 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: + mid = m.get("id") or f"M{i + 1}" + if any(mid == o["id"] for o in out): + raise ValueError(f"milestone ids must be unique: {mid!r} is repeated") + prev = out[-1] if out else None + group, carry = m.get("group"), m.get("carry_gates", False) + if not isinstance(carry, bool): + raise ValueError(f"milestone {mid}: carry_gates must be true or false") + if group is not None: + # A revision names the milestone it revises: an earlier one of the group just before it, so a + # milestone's revisions run one after another. + named = next((o for o in out if o["id"] == group), None) + if named is None: + raise ValueError(f"milestone {mid}: group {group!r} names no earlier milestone") + if named["group"] != prev["group"]: + raise ValueError(f"milestone {mid}: a revision of {named['group']} must follow it or its last " + f"revision, not {prev['id']}") + elif carry: + raise ValueError(f"milestone {mid}: carry_gates needs group (the milestone it revises)") + own = m.get("gates") or [] + if not own: + raise ValueError(f"milestone {mid} has no gates") + carried = {g["id"]: g for g in prev["gates"]} if carry else {} + artifacts = {**(prev["artifacts"] if carry else {}), **(m.get("artifacts") or {})} + for g in own: 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") + raise ValueError(f"milestone {mid}: 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 {}): + if art is not None and art not in artifacts: raise ValueError(f"gate {g['id']} names artifact {art!r}, not in its milestone's artifacts") problem = _check_problem(g["check"]) if problem: @@ -854,17 +951,23 @@ def _spec(params: dict) -> dict: 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"]] + authored.append((g["id"], g["id"] in carried)) + # Carried gates keep their place; one the revision overrides (same id) takes its place, new ones follow. + mine = {g["id"]: g for g in own} + gates = [mine.pop(gid) if gid in mine else {**g, "carried": True} for gid, g in carried.items()] + gates += list(mine.values()) + revision = prev["revision"] + 1 if group is not None else 1 + out.append({"id": mid, "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"), + # a revision asks for a change to work already done, so by default it's never skipped as done + "skip_if_done": bool(m.get("skip_if_done", group is None)), + "group": prev["group"] if group is not None else mid, "revision": revision, + "artifacts": artifacts, "gates": gates}) + ids = [gid for gid, override in authored if not override] 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}") + raise ValueError(f"gate ids must be unique (a revision with carry_gates may reuse one it carries, to " + f"override it); repeated: {repeated}") 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()): diff --git a/tst/unit/task_step/test_milestone_gates_hook.py b/tst/unit/task_step/test_milestone_gates_hook.py index 169d6ed18..b92aada1d 100644 --- a/tst/unit/task_step/test_milestone_gates_hook.py +++ b/tst/unit/task_step/test_milestone_gates_hook.py @@ -804,3 +804,198 @@ async def test_a_milestone_broken_while_the_agent_answers_the_wrap_up_is_undone_ await post_turn(t2, PARAMS) assert records[-1]["milestone"] == "M2" assert _status(t2)[1][:2] == ("M2", "undone") and t2.summary["done"] == 1 + + +# ---- revisions ---------------------------------------------------------------------------------------------------- + +REPORT = {"report": {"find": {"tool": "docs", "path": "files"}, "read": {"tool": "doc_read", "args": {"id": "{id}"}}}} + + +def _revised(**r2) -> dict: + """M1, then its revision M1-r2 (carrying M1's gates, overriding m1-total), then M2.""" + return {"role": "r", "milestones": [ + {"id": "M1", "artifacts": REPORT, "gates": [ + {"id": "m1-report", "nudge": "Where's the report?", "check": {"artifact": "report", "expect": "exists"}}, + {"id": "m1-total", "nudge": "Does it have the total?", + "check": {"artifact": "report", "format": {"contains_all": ["total"]}}}, + {"id": "m1-quiet", "nudge": "Don't email yet.", + "check": {"no_new": [{"tool": "gmail_sent", "path": "messages", "baseline_count": 0}]}}]}, + {"id": "M1-r2", "group": "M1", "carry_gates": True, "line": "Make it a table; it's going public now.", + "max_nudges": 1, "blocking": False, "gates": [ + {"id": "m1-table", "nudge": "Can it be a table?", + "check": {"artifact": "report", "format": {"contains_all": ["|"]}}}, + {"id": "m1-total", "nudge": "Keep the total, not the internal number.", + "check": {"artifact": "report", "format": {"contains_all": ["total"], "contains_none": ["internal"]}}}], + **r2}, + {"id": "M2", "line": "Now post it on the card.", "gates": [ + {"id": "m2-card", "nudge": "Is it on the card?", + "check": {"call": {"tool": "trello_comments", "path": "comments"}, "expect": {"count": {"min": 1}}}}]}]} + + +def report_world(text="Report\ntotal 40 (internal 12)"): + return {"docs": {"files": [{"id": "d1"}]}, "doc_read": text, "gmail_sent": {"messages": []}, + "trello_comments": {"comments": []}} + + +def _load_error(milestones) -> str: + with pytest.raises(ValueError) as e: + mg.check_params({"role": "r", "milestones": milestones}) + return str(e.value) + + +def _m(mid, gate="g", **kw): + return {"id": mid, "gates": [{"id": f"{mid}-{gate}", "nudge": "n", "check": {"call": {"tool": "t"}, "expect": "exists"}}], + **kw} + + +def test_a_revision_must_name_an_earlier_milestone_and_follow_it(): + assert "names no earlier milestone" in _load_error([_m("M1", group="M9")]) + assert "names no earlier milestone" in _load_error([_m("M1"), _m("M2", group="M3"), _m("M3")]) + # M1's revision after M2 has opened: its revisions must run one after another + assert "must follow it or its last revision" in _load_error([_m("M1"), _m("M2"), _m("M1-r2", group="M1")]) + assert "carry_gates needs group" in _load_error([_m("M1"), _m("M2", carry_gates=True)]) + assert "carry_gates must be true or false" in _load_error([_m("M1"), _m("M1-r2", group="M1", carry_gates="yes")]) + + +def test_a_revision_may_name_its_milestone_or_an_earlier_revision_of_it(): + spec = mg._spec({"role": "r", "milestones": [_m("M1"), _m("M1-r2", group="M1"), _m("M1-r3", group="M1-r2"), + _m("M2")]}) + assert [(m["id"], m["group"], m["revision"], m["skip_if_done"]) for m in spec["milestones"]] == [ + ("M1", "M1", 1, True), ("M1-r2", "M1", 2, False), ("M1-r3", "M1", 3, False), ("M2", "M2", 1, True)] + + +def test_only_a_carrying_revision_may_reuse_a_gate_id_and_then_it_overrides_that_gate(): + reuse = [_m("M1"), {**_m("M1-r2", group="M1"), "gates": _m("M1")["gates"]}] + assert "gate ids must be unique" in _load_error(reuse) + reuse[1]["carry_gates"] = True + mg.check_params({"role": "r", "milestones": reuse}) + assert "gate ids must be unique" in _load_error([_m("M1"), _m("M2"), {**_m("M3"), "gates": _m("M1")["gates"]}]) + + +def test_carried_gates_keep_their_place_an_override_takes_its_and_new_gates_follow(): + spec = mg._spec(_revised()) + r2 = spec["milestones"][1] + assert [(g["id"], g.get("carried", False)) for g in r2["gates"]] == [ + ("m1-report", True), ("m1-total", False), ("m1-quiet", True), ("m1-table", False)] + assert r2["gates"][1]["nudge"] == "Keep the total, not the internal number." + assert r2["artifacts"] == REPORT # carried with the gates that read it + assert [g["id"] for g in spec["milestones"][2]["gates"]] == ["m2-card"] # a new milestone carries nothing + + +def test_a_revision_without_carry_gates_checks_only_its_own_gates_and_may_read_its_own_artifacts(): + params = _revised(carry_gates=False) + assert "not in its milestone's artifacts" in _load_error(params["milestones"]) + params["milestones"][1]["artifacts"] = REPORT + assert "gate ids must be unique" in _load_error(params["milestones"]) # m1-total, reused without carrying + params["milestones"][1]["gates"][1]["id"] = "m1-public" + assert [g["id"] for g in mg._spec(params)["milestones"][1]["gates"]] == ["m1-table", "m1-public"] + + +@pytest.mark.asyncio +async def test_a_revision_opens_after_its_milestone_even_when_already_done_and_nudges_on_a_carried_gate(): + w = report_world("| total | 40 |") # already a table with no internal number + env, records = Env(w), [] + t1 = Turn(env, records, 1) + await post_turn(t1, _revised()) + assert t1.notes == ["M1 is done. Open M1-r2 now: send this line: Make it a table; it's going public now."] + w["docs"] = {"files": []} # the agent deletes the report while revising it + t2 = Turn(env, records, 2) + await post_turn(t2, _revised()) + assert t2.notes == ["Where's the report?"] # M1's own gate, carried into the revision + assert records[-1]["milestone"] == "M1-r2" and records[-1]["decision"] == "nudge" + + +@pytest.mark.asyncio +async def test_a_revision_let_go_opens_the_next_milestone(): + env, records = Env(report_world()), [] + await post_turn(Turn(env, records, 1), _revised()) # M1 passes + await post_turn(Turn(env, records, 2), _revised()) # M1-r2 nudged: still internal, no table + t3 = Turn(env, records, 3) + await post_turn(t3, _revised()) # max_nudges 1, not blocking: let go + assert t3.notes == ["M1-r2 isn't done, but let it go. Open M2 now: send this line: Now post it on the card."] + m1 = t3.summary["milestones"][0] + assert (m1["status"], m1["reached_revision"], m1["revisions_done"]) == ("gave_up", "M1-r2", 1) + assert [(r["revision"], r["status"]) for r in m1["revisions"]] == [(1, "passed"), (2, "gave_up")] + + +@pytest.mark.asyncio +async def test_a_blocking_revision_that_never_passes_ends_the_run(): + env, records = Env(report_world()), [] + for n in (1, 2, 3): + returned = await post_turn(Turn(env, records, n), _revised(blocking=True)) + assert returned == {"end": "gate_never_passed:M1-r2"} + + +async def _run_revised(w, final_text=None): + """M1 passes, M1-r2 is nudged then passes, M2 passes and the wrap-up goes out, then the final check.""" + env, records, turns = Env(w), [], [] + + async def turn(n): + turns.append(Turn(env, records, n)) + return await post_turn(turns[-1], _revised()) + + await turn(1) + await turn(2) + w["doc_read"] = "| total | 40 |" + await turn(3) + w["trello_comments"] = {"comments": [{"text": "posted"}]} + await turn(4) + if final_text is not None: + w["doc_read"] = final_text + env.calls.clear() + returned = await turn(5) + return returned, records, turns, env + + +@pytest.mark.asyncio +async def test_the_summary_nests_revisions_under_their_milestone(): + returned, records, turns, _ = await _run_revised(report_world()) + assert returned == {"end": "milestones_done"} + s = turns[-1].summary + assert {k: s[k] for k in ("reached", "reached_revision", "done", "total", "revisions_done", "revisions_total", + "end")} == {"reached": "M2", "reached_revision": "M2", "done": 2, "total": 2, + "revisions_done": 3, "revisions_total": 3, "end": "milestones_done"} + m1, m2 = s["milestones"] + assert {k: m1[k] for k in ("id", "status", "opened_turn", "closed_turn", "nudges", "reached_revision", + "revisions_done")} == {"id": "M1", "status": "passed", "opened_turn": 1, "closed_turn": 3, + "nudges": 1, "reached_revision": "M1-r2", "revisions_done": 2} + assert [(r["id"], r["revision"], r["status"], r["opened_turn"], r["closed_turn"], r["nudges"]) + for r in m1["revisions"]] == [("M1", 1, "passed", 1, 1, 0), ("M1-r2", 2, "passed", 2, 3, 1)] + r2_gates = m1["revisions"][1]["gates"] + assert r2_gates["m1-report"] == {"passed": True, "type": "action", "carried": True} + assert "carried" not in r2_gates["m1-table"] and "carried" not in r2_gates["m1-total"] + assert (m2["status"], "revisions" in m2) == ("passed", False) # a milestone without revisions is one row + + +@pytest.mark.asyncio +async def test_after_the_wrap_up_every_milestones_latest_revision_is_checked_and_a_broken_one_is_undone(): + returned, records, turns, env = await _run_revised(report_world(), final_text="total 40 (internal 12)") + done = records[-1] + assert done["decision"] == "done" and done["milestone"] == "M2" + [m1] = done["final_checks"] + assert m1["milestone"] == "M1-r2" + # state gates only: m1-quiet (no_new) is about the turns M1-r2 was open, so it isn't checked again + assert [(g["id"], g["passed"]) for g in m1["gates"]] == [ + ("m1-report", True), ("m1-total", False), ("m1-table", False)] + assert not any(tool == "gmail_sent" for tool, _, _ in env.calls) + s = turns[-1].summary + assert [(r["id"], r["status"]) for r in s["milestones"][0]["revisions"]] == [("M1", "passed"), ("M1-r2", "undone")] + assert (s["milestones"][0]["status"], s["done"], s["revisions_done"]) == ("undone", 1, 2) + + +@pytest.mark.asyncio +async def test_after_the_wrap_up_an_earlier_milestone_without_revisions_is_checked_too(): + w = world() + w["drive_list"] = {"files": [SHEET]} + env, records = Env(w), [] + params = copy.deepcopy(PARAMS) + params["milestones"][1]["skip_if_done"] = False + await post_turn(Turn(env, records, 1), params) # M1 passes + w["trello_comments"] = {"comments": [{"text": "Vaultly cancelled"}]} + await post_turn(Turn(env, records, 2), params) # M2 passes: wrap-up + w["drive_list"] = {"files": []} # the agent removes M1's sheet while answering the wrap-up + t3 = Turn(env, records, 3) + assert await post_turn(t3, params) == {"end": "milestones_done"} + assert [g["id"] for g in records[-1]["final_checks"][0]["gates"]] == ["m1-sheet", "m1-cols"] + assert _status(t3) == [("M1", "undone", 1, 3, 0), ("M2", "passed", 2, 2, 0)] + assert "reached_revision" not in t3.summary # a task without revisions keeps its summary's shape From 7ad6b3a1416f26daecbd82cc9344dd0c45175b44 Mon Sep 17 00:00:00 2001 From: kaihackney-scale Date: Wed, 25 Nov 2026 12:25:25 -0500 Subject: [PATCH 2/2] fix(milestone-gates): refuse a gate id twice in one entry; each revision's row shows its own gate types A carrying revision could write two gates with one inherited id: both counted as overrides and only the last ran. An entry's own gate ids must now be unique. The summary looked gate types up by gate id alone, so an override with another check showed its type on the earlier revision too; types are now per entry. Co-Authored-By: Claude Opus 5.5 --- .../artifacts/milestone-gates/hook.py | 10 ++++++-- .../task_step/test_milestone_gates_hook.py | 23 +++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) 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 index 386c13df1..dcbd5c793 100644 --- a/src/agent_env/examples/milestone-gates/artifacts/milestone-gates/hook.py +++ b/src/agent_env/examples/milestone-gates/artifacts/milestone-gates/hook.py @@ -235,7 +235,8 @@ def _summary(spec: dict, records: list[dict]) -> dict: 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"]} + # By milestone entry and gate: a revision may override a gate with another check, and each row shows its own. + types = {(m["id"], 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) @@ -243,7 +244,8 @@ def _summary(spec: dict, records: list[dict]) -> dict: end = None def verdicts(row, gates): - row["gates"].update({g["id"]: {"passed": g["passed"], "type": types.get(g["id"])} for g in gates}) + row["gates"].update({g["id"]: {"passed": g["passed"], "type": types.get((row["id"], g["id"]))} + for g in gates}) for r in records: turn, row = r.get("turn"), by_id.get(r.get("milestone")) @@ -931,6 +933,10 @@ def _spec(params: dict) -> dict: own = m.get("gates") or [] if not own: raise ValueError(f"milestone {mid} has no gates") + own_ids = [g.get("id") for g in own if isinstance(g, dict) and g.get("id")] + twice = sorted({gid for gid in own_ids if own_ids.count(gid) > 1}) + if twice: # two gates of one id: one override would replace the other, and its check would never run + raise ValueError(f"milestone {mid}: gate ids must be unique within a milestone; repeated: {twice}") carried = {g["id"]: g for g in prev["gates"]} if carry else {} artifacts = {**(prev["artifacts"] if carry else {}), **(m.get("artifacts") or {})} for g in own: diff --git a/tst/unit/task_step/test_milestone_gates_hook.py b/tst/unit/task_step/test_milestone_gates_hook.py index b92aada1d..d90f75717 100644 --- a/tst/unit/task_step/test_milestone_gates_hook.py +++ b/tst/unit/task_step/test_milestone_gates_hook.py @@ -999,3 +999,26 @@ async def test_after_the_wrap_up_an_earlier_milestone_without_revisions_is_check assert [g["id"] for g in records[-1]["final_checks"][0]["gates"]] == ["m1-sheet", "m1-cols"] assert _status(t3) == [("M1", "undone", 1, 3, 0), ("M2", "passed", 2, 2, 0)] assert "reached_revision" not in t3.summary # a task without revisions keeps its summary's shape + + +def test_a_carrying_revision_that_overrides_one_gate_twice_is_refused_at_load(): + params = _revised() + total = params["milestones"][1]["gates"][1] + params["milestones"][1]["gates"].append({**total, "nudge": "Keep the total somewhere."}) + with pytest.raises(ValueError, match=r"M1-r2: gate ids must be unique within a milestone; repeated: \['m1-total'\]"): + mg.check_params(params) + + +@pytest.mark.asyncio +async def test_each_revisions_row_shows_the_type_of_the_check_it_ran(): + params = _revised() + params["milestones"][0]["gates"][1]["type"] = "content" # M1's m1-total, overridden in M1-r2 by a format check + env, records = Env(report_world()), [] + t1 = Turn(env, records, 1) + await post_turn(t1, params) # M1 passes; M1-r2 opens + m1, r2 = t1.summary["milestones"][0]["revisions"] + assert m1["gates"]["m1-total"]["type"] == "content" + t2 = Turn(env, records, 2) + await post_turn(t2, params) + m1, r2 = t2.summary["milestones"][0]["revisions"] + assert (m1["gates"]["m1-total"]["type"], r2["gates"]["m1-total"]["type"]) == ("content", "format")