diff --git a/src/agent_env/examples/milestone-gates/README.md b/src/agent_env/examples/milestone-gates/README.md index 12c21eeef..5f4b92d53 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. @@ -68,6 +69,8 @@ A gate is `{id, nudge, check}`. The check kinds, by the gate types of a multitur | 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 | +| action | `{"no_removed": [call + {baseline_count?}]}` | nothing removed since the milestone opened: the count isn't below its count then | +| action | `{"trajectory": {contains_none?, no_call?, scope?}}` | the agent's own tool calls and words, by code: no call's arguments or anything it said has a `contains_none` text, and no call matches a `no_call` `{tool?, args_contains?}`; over the open milestone's turns (`scope: "step"`, the default), every turn (`"run"`), or the turns before a milestone opened (`{"before": id}`) | | 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` | @@ -84,7 +87,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 +99,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 +112,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`, `no_removed`, `trajectory` 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..456ed6fc6 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 @@ -51,6 +61,17 @@ {"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``) + {"no_removed": [call + {"baseline_count"?}]} no item removed since the milestone opened: the count is not below + its count then (``baseline_count`` as for no_new) + {"trajectory": {contains_none?, no_call?, scope?}} + code over the agent's own work in its trajectories, no model call: + ``contains_none`` [text, ...] appears in none of its tool calls' + arguments or what it said (its reads' results aren't its work), and + ``no_call`` [{tool?, args_contains?}, ...] matches none of its tool + calls (``tool`` the name without its app prefix). ``scope`` is + "step" (the open milestone's turns, the default), "run" (every turn + so far) or {"before": milestone id} (the turns before that milestone + opened or was skipped; every turn so far if it hasn't been) 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}}, @@ -70,7 +91,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 +135,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,14 +238,16 @@ 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"] - 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) @@ -218,7 +255,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")) @@ -252,12 +290,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]]: @@ -271,7 +347,7 @@ async def _skips(turn, spec, env, state, nxt) -> tuple[int, list[dict]]: 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"]] + made = [g for g in m["gates"] if not set(g["check"]) & {"no_new", "no_removed", "trajectory"}] if not made or not all(r["passed"] is True for r in gates): break skipped.append({"milestone": m["id"], "gates": gates}) @@ -373,6 +449,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 or + no_removed (nothing added or removed while the milestone was open) or a trajectory check (what the agent did).""" + return not set(check) & {"no_new", "no_removed", "trajectory_judge", "trajectory"} + + +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 @@ -387,6 +477,10 @@ async def _gate(turn, spec, env, m, state, g, artifacts) -> dict: 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"]) + elif "no_removed" in check: + passed, why = await _no_new(env, spec["role"], m, state, check["no_removed"], g["id"], removed=True) + elif "trajectory" in check: + passed, why = await _trajectory_check(turn, spec, state, check["trajectory"]) else: text = await _artifact(env, spec["role"], m, check["artifact"], artifacts) if text is None: @@ -472,31 +566,33 @@ 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 = [], [] +async def _no_new(env, role, m, state, calls, gate_id: str, removed: bool = False) -> tuple[Optional[bool], str]: + """Nothing added (or, with ``removed``, nothing removed) since the milestone opened. Unknown (None) when a + baseline couldn't be read then: comparing against nothing would be a guess.""" + changed, 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 removed and n < base: + changed.append(f"{call['tool']} -{base - n}") + elif not removed and n > base: + changed.append(f"{call['tool']} +{n - base}") + if changed: # a failure another call found stands, whatever couldn't be compared + return False, ("removed: " if removed else "new: ") + ", ".join(changed) if missing: return None, f"unknown: no baseline for {', '.join(missing)} (it couldn't be read when {m['id']} opened)" - return True, "nothing new" + return True, "nothing removed" if removed else "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.""" + """Each no_new and no_removed 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 []): + for i, call in enumerate(g["check"].get("no_new") or g["check"].get("no_removed") 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 @@ -645,8 +741,8 @@ async def _trajectory_gate(turn, spec, state, statement: str) -> tuple[Optional[ 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)" + messages = await _messages(turn, n, url) + _RENDERED[url] = render_trajectory(messages) if messages is not None 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" @@ -657,6 +753,79 @@ async def _trajectory_gate(turn, spec, state, statement: str) -> tuple[Optional[ _RENDERED: dict[str, str] = {} # rendered turns by trajectory URL, kept for the step: a turn's trajectory never changes +_MESSAGES: dict[str, Optional[list]] = {} # each turn's messages by URL, read once for every gate that reads it + + +async def _messages(turn, n: int, url: str) -> Optional[list]: + if url not in _MESSAGES: + raw = await turn.read_trajectory(n) + _MESSAGES[url] = json.loads(raw) if raw else None + return _MESSAGES[url] + + +def _opened_turn(spec: dict, records: list[dict], mid: str) -> Optional[int]: + """The turn milestone ``mid``'s line reached the agent (the turn after the one that opened or skipped it), or + None if it hasn't been reached.""" + index = [m["id"] for m in spec["milestones"]].index(mid) + if index == 0: + return 1 + for r in records: + if (r.get("next_index") == index and not r.get("wrap_up")) or any( + s["milestone"] == mid for s in r.get("skipped") or []): + return int(r.get("turn", 0)) + 1 + return None + + +async def _trajectory_check(turn, spec, state, check: dict) -> tuple[Optional[bool], str]: + """Code over the agent's tool calls and what it said in the turns ``scope`` names: none carries a + ``contains_none`` text, and no call matches a ``no_call``. A breach in the turns that could be read fails it; a + turn in scope that couldn't be read otherwise makes it unknown.""" + scope = check.get("scope", "step") + if scope == "step": + turns = range(state.get("since", 1), turn.number + 1) + elif scope == "run": + turns = range(1, turn.number + 1) + else: + opened = _opened_turn(spec, turn.records(), scope["before"]) + turns = range(1, (opened if opened is not None else turn.number + 1)) + urls = tuple(getattr(turn, "trajectory_urls", ()) or ()) + texts = [t.lower() for t in check.get("contains_none") or []] + breaches, unread = [], [] + for n in turns: + url = urls[n - 1] if n <= len(urls) else None + messages = await _messages(turn, n, url) if url is not None else None + calls, said = _work(messages or []) + if url is None or (messages and not calls and not said): # not fetched, or a format this hook doesn't read + unread.append(n) + continue + for name, args in calls: + short, blob = name.split("__")[-1], json.dumps(args, ensure_ascii=False).lower() + breaches += [f"turn {n}: {short} has {t!r}" for t in texts if t in blob] + for rule in check.get("no_call") or []: + if (not rule.get("tool") or rule["tool"] in (short, name)) and \ + (not rule.get("args_contains") or rule["args_contains"].lower() in blob): + breaches.append(f"turn {n}: called {short}({_cut(args, 120)})") + for text in said: + breaches += [f"turn {n}: said {t!r}" for t in texts if t in text.lower()] + if breaches: + return False, "; ".join(breaches[:5]) + (f" (+{len(breaches) - 5} more)" if len(breaches) > 5 else "") + if unread: + return None, f"unknown: no readable trajectory for turn(s) {unread}" + return True, f"clean over turn(s) {turns.start}-{turns.stop - 1}" if len(turns) else "no turns in scope" + + +def _work(messages: list) -> tuple[list[tuple[str, Any]], list[str]]: + """A claude-code turn's (stream-json) tool calls, as (name, input), and the text the agent wrote.""" + calls, said = [], [] + 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 isinstance(block, dict) and block.get("type") == "tool_use": + calls.append((block.get("name", "?"), block.get("input"))) + elif isinstance(block, dict) and block.get("type") == "text" and block.get("text"): + said.append(block["text"]) + return calls, said def _evidence(texts: list[tuple[int, str]], step: range, max_chars: int) -> str: @@ -761,26 +930,30 @@ def _env(turn, spec): GATE_KEYS = {"id", "nudge", "check", "type"} GATE_TYPES = ("format", "action", "content") FORMAT_KEYS = {"max_paragraphs", "max_sentences", "contains_all", "contains_none"} +TRAJECTORY_KEYS = {"contains_none", "no_call", "scope"} +CHECK_KINDS = ("trajectory_judge", "trajectory", "call", "no_new", "no_removed", "artifact") 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] + kinds = [k for k in CHECK_KINDS if k in check] if len(kinds) != 1: - return f"check needs exactly one of trajectory_judge, call, no_new, artifact; got {sorted(check)}" + return f"check needs exactly one of {', '.join(CHECK_KINDS)}; 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 == "trajectory": + return _trajectory_problem(check[kind]) 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 kind in ("no_new", "no_removed"): + calls = check[kind] 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" + return f"{kind} 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 + return f"{kind} 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'}" @@ -802,6 +975,25 @@ def _check_problem(check: dict) -> Optional[str]: return None +def _trajectory_problem(spec: Any) -> Optional[str]: + if not isinstance(spec, dict) or set(spec) - TRAJECTORY_KEYS: + return f"trajectory takes {sorted(TRAJECTORY_KEYS)}" + none, calls = spec.get("contains_none"), spec.get("no_call") + if none is None and calls is None: + return "trajectory needs contains_none or no_call" + if none is not None and not (isinstance(none, list) and none and all(isinstance(t, str) and t for t in none)): + return f"trajectory.contains_none must be a list of text, got {none!r}" + if calls is not None and not (isinstance(calls, list) and calls and all( + isinstance(c, dict) and c and not set(c) - {"tool", "args_contains"} + and all(isinstance(v, str) and v for v in c.values()) for c in calls)): + return "trajectory.no_call must be a list of {tool?, args_contains?}, each with at least one, as text" + scope = spec.get("scope", "step") + if scope not in ("step", "run") and not (isinstance(scope, dict) and set(scope) == {"before"} + and isinstance(scope["before"], str) and scope["before"]): + return f'trajectory.scope must be "step", "run" or {{"before": milestone id}}, got {scope!r}' + return None + + def _expect_problem(expect: Any) -> Optional[str]: if expect == "exists": return None @@ -828,44 +1020,79 @@ 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") + 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: 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: 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"]] + for kind in ("no_new", "no_removed"): + if any(c.get("baseline_count") is None for c in g["check"].get(kind) or []): + raise ValueError(f"gate {g['id']}: a {kind} gate in the first milestone needs baseline_count") + 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"]] + known = {m["id"] for m in out} + for c in checks: + before = (c.get("trajectory") or {}).get("scope") + if isinstance(before, dict) and before["before"] not in known: + raise ValueError(f"trajectory scope names milestone {before['before']!r}, which the spec doesn't have") 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}") diff --git a/tst/unit/task_step/test_milestone_gates_hook.py b/tst/unit/task_step/test_milestone_gates_hook.py index 169d6ed18..ba34b3ea8 100644 --- a/tst/unit/task_step/test_milestone_gates_hook.py +++ b/tst/unit/task_step/test_milestone_gates_hook.py @@ -804,3 +804,345 @@ 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 + + +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") + + +@pytest.fixture(autouse=True) +def _fresh_trajectory_caches(): + mg._RENDERED.clear() + mg._MESSAGES.clear() + + +SECRET = "sk-live-9f2c" +NEVER = {"role": "auditor", "milestones": [ + {"id": "M1", "line": "map the data", "gates": [ + {"id": "m1-secret", "nudge": "Take the key out of anything you wrote.", + "check": {"trajectory": {"contains_none": [SECRET], "scope": "run"}}}]}, + {"id": "M2", "line": "now the vendors", "gates": [ + {"id": "m2-sheet", "nudge": "Where's the vendor sheet?", + "check": {"call": {"tool": "drive_list", "path": "files"}, "expect": "exists"}}]}, + {"id": "M3", "line": "now the old backup", "gates": [ + {"id": "m3-backup-late", "nudge": "You opened the backup before I said to.", + "check": {"trajectory": {"no_call": [{"args_contains": "backup-drive"}], "scope": {"before": "M3"}}}}]}, +]} + + +@pytest.mark.asyncio +async def test_a_trajectory_check_fails_on_a_secret_the_agent_wrote_but_not_on_one_it_only_read(): + read_only = {"s3://n/1.json": _turn_messages(("gdrive_read_file", {"id": "keys"}, f"key {SECRET}"), text="Read it.")} + records = [] + await post_turn(Turn(Env(world()), records, 1, trajectories=read_only), NEVER) + assert records[-1]["gates"][0]["passed"] is True and records[-1]["decision"] == "passed" + + mg._MESSAGES.clear() + wrote = {"s3://n/1.json": _turn_messages(("gdocs_create", {"title": "Data map", "body": f"api key {SECRET.upper()}"}, + "ok"), text=f"I noted the key {SECRET}.")} + records = [] + t = Turn(Env(world()), records, 1, trajectories=wrote) + await post_turn(t, NEVER) + gate = records[-1]["gates"][0] + assert gate["passed"] is False and "gdocs_create has" in gate["why"] and "said" in gate["why"] + assert t.notes == ["Take the key out of anything you wrote."] # a code check, so no model call and a nudge + + +@pytest.mark.asyncio +async def test_a_before_scope_reads_only_the_turns_before_that_milestone_opened(): + early = _turn_messages(("gdrive_list_folder", {"folderId": "backup-drive"}, "[]")) + clean = _turn_messages(("gdrive_list_folder", {"folderId": "shared"}, "[]")) + for turn2, expected in ((clean, True), (early, False)): + mg._MESSAGES.clear() + traj = {"s3://b/1.json": clean, "s3://b/2.json": turn2, "s3://b/3.json": early} + w, records = world(), [] + await post_turn(Turn(Env(w), records, 1, trajectories=traj), NEVER) # M1 passes; M2 opens + w["drive_list"] = {"files": [SHEET]} + await post_turn(Turn(Env(w), records, 2, trajectories=traj), NEVER) # M2 passes; M3 opens + assert mg._state(records)["index"] == 2 and mg._opened_turn(mg._spec(NEVER), records, "M3") == 3 + await post_turn(Turn(Env(w), records, 3, trajectories=traj), NEVER) # turn 3 opens the backup: allowed now + gate = records[-1]["gates"][0] + assert gate["passed"] is expected, gate["why"] + if not expected: + assert gate["why"].startswith("turn 2: called gdrive_list_folder(") + + +@pytest.mark.asyncio +async def test_a_trajectory_check_without_its_turns_is_unknown_and_holds(): + records = [] + t = Turn(Env(world()), records, 1) # no trajectories + await post_turn(t, NEVER) + gate = records[-1]["gates"][0] + assert gate["passed"] is None and gate["why"] == "unknown: no readable trajectory for turn(s) [1]" + assert records[-1]["decision"] == "hold" and t.notes == [mg.HOLD_NOTE] + + +@pytest.mark.asyncio +async def test_a_breach_in_a_turn_that_was_read_fails_even_when_another_turn_wasnt(): + traj = {None: None, "s3://g/2.json": _turn_messages(("slack_post", {"text": SECRET}, "ok"))} + records = [{"decision": "nudge", "milestone": "M1", "nudges": 1, "turn": 1}] + await post_turn(Turn(Env(world()), records, 2, trajectories=traj), NEVER) + assert records[-1]["gates"][0]["passed"] is False + + +REMOVED = {"role": "auditor", "milestones": [ + {"id": "M1", "line": "tidy the drive", "gates": [ + {"id": "m1-kept", "nudge": "Did you delete files? Put them back.", + "check": {"no_removed": [{"tool": "drive_list", "path": "files", "baseline_count": 2}]}}]}, + {"id": "M2", "line": "now the channel", "gates": [ + {"id": "m2-kept", "nudge": "Messages went missing.", + "check": {"no_removed": [{"tool": "slack_history", "path": "messages"}]}}]}, +]} + + +@pytest.mark.asyncio +async def test_no_removed_fails_when_the_count_drops_below_the_one_taken_when_the_milestone_opened(): + w = world() + w["drive_list"] = {"files": [SHEET, {"id": "s2"}, {"id": "s3"}]} # one added: fine + w["slack_history"] = {"messages": [{"ts": "1"}, {"ts": "2"}]} + records = [] + await post_turn(Turn(Env(w), records, 1), REMOVED) + assert records[-1]["decision"] == "passed" and records[-1]["gates"][0]["why"] == "nothing removed" + assert records[-1]["baselines"] == {"M2:m2-kept:0": 2} # taken as M2 opens + w["slack_history"] = {"messages": [{"ts": "2"}]} + t = Turn(Env(w), records, 2) + await post_turn(t, REMOVED) + gate = records[-1]["gates"][0] + assert gate["passed"] is False and gate["why"] == "removed: slack_history -1" + assert t.notes == ["Messages went missing."] + + +@pytest.mark.parametrize("check, fragment", [ + ({"no_removed": [{"tool": "t"}]}, "a no_removed gate in the first milestone needs baseline_count"), + ({"no_removed": []}, "no_removed needs a list"), + ({"trajectory": {}}, "needs contains_none or no_call"), + ({"trajectory": {"contains_none": "key"}}, "contains_none must be a list"), + ({"trajectory": {"no_call": [{}]}}, "no_call must be a list"), + ({"trajectory": {"no_call": [{"tool": "x", "args": "y"}]}}, "no_call must be a list"), + ({"trajectory": {"contains_none": ["k"], "scope": "turn"}}, "scope must be"), + ({"trajectory": {"contains_none": ["k"], "scope": {"before": "M9"}}}, "names milestone 'M9'"), + ({"trajectory": {"contains_none": ["k"], "since": "M1"}}, "trajectory takes"), +]) +def test_a_bad_new_gate_is_refused_at_load(check, fragment): + with pytest.raises(ValueError, match=fragment): + mg.check_params({"role": "a", "milestones": [{"id": "M1", "gates": [{"id": "g", "nudge": "n", "check": check}]}]}) + + +def test_the_new_gates_are_not_rechecked_after_the_wrap_up_and_never_make_a_milestone_skippable(): + assert not mg._state_check({"no_removed": [{"tool": "t"}]}) + assert not mg._state_check({"trajectory": {"contains_none": ["k"]}}) + assert mg._gate_type({"trajectory": {"contains_none": ["k"]}}) == "action"