Skip to content

feat(prompt_agent): an opt-in gate on user-sim messages - #597

Merged
kaihackney-scale merged 29 commits into
mainfrom
kai/usersim-gate
Nov 24, 2026
Merged

kaihackney-scale merged 29 commits into
mainfrom
kai/usersim-gate

Conversation

@kaihackney-scale

@kaihackney-scale kaihackney-scale commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

What

prompt_agent and always_on get an opt-in user_sim_gate. When the user side is an LLM user sim, each message it would send is checked before the agent gets it. This covers a peer user sim and the built-in one deploy_user_sim_agent deploys.

{"user_sim_gate": {"judge_model": "<model>", "max_rewrites": 2, "on_fail": "fail"}}

What decides. Only the judge holds a message back.

  • judge_model: one model call. It reads the user sim's own instructions, the last turns and the candidate message. It decides whether the message is written as the user, by the same rule user_sim_judge's rogue check uses to fail a run ("spoke as the assistant").
    • The instructions are rebuilt from the user sim's user_sims record, or, in always_on, taken from the plugin's setup prompt.
  • patterns (free): phrases and shapes that belong to the assistant's side, such as a report of work done, a formatted deliverable or an offer to do the work. A match is recorded on the verdict but never holds a message back. With no judge, the gate only records.

When a message fails. The user sim is told why and asked to rewrite, up to max_rewrites times. If it still fails, on_fail decides:

  • fail (the default) treats it as a failed user sim, so the run is redone:
    • the run gets error_type: user_sim_error, with the gate's reason in the error message;
    • in prompt_agent the step also fails, after its PromptResponse is recorded, so retry_config and fail_task_on_error apply;
    • in always_on, the end reason is user_sim_error too.
  • end ends the conversation, with end reason user_sim_invalid.
  • send sends the message anyway, and the verdicts are recorded.

Judge errors.

  • A judge that can't be set up fails the step. Nothing else holds a message back, so the run never goes on unchecked.
  • A judge call that errors or returns something unparseable lets the message through, with the error recorded.

Recording.

  • Every verdict is in context.metadata["user_sim_gate"][step_id]: pattern matches, the judge's reason, any error.
  • A message that ended the run is recorded in context.metadata["user_sim_invalid"][step_id].

Cost.

  • Judge calls are in the step's usage under role judge.
  • Each call keeps its own cost: the endpoint's bill when it gives one, otherwise an estimate from the price map. The two are kept apart.
  • A call cut off by its timeout or a cancel is counted with unknown usage, so the entry is marked a lower bound.
  • In always_on, turning the gate on reserves each read's worst case out of the run's time budget, whether or not it fires.

Built-in user sim. It answers in JSON (outcome, message, used), so a rewrite is parsed as its own answer:

  • a reply goes to the gate's next check;
  • a done with text ends the conversation after the agent answers it, as before;
  • a no_reply or an empty done ends the conversation, as it would have.

The read's record (user_sim_reads) keeps the user sim's first answer as first_message, and lists each rewrite under gate_rewrites.

In always_on, each answer is checked at its read, before it's held for its response time:

  • the rewrite is asked for in the user sim's own session;
  • the read's timeline event records the verdicts, the rewrites and the first message;
  • a rewrite with nothing to send (a no_reply or an empty reply) holds the message back for good;
  • the last read's answer is never delivered, so it isn't checked;
  • a user-sim plugin's rewrite is read with the plugin's own parse, and a gate whose plugin can't read rewrites is refused when the run starts.

Other step types. A subclass of PromptAgentTaskStep that runs its own conversation refuses user_sim_gate when it loads, rather than silently ignoring it. To use the gate, it calls user_sim_gate.run_gate(...) and sets USER_SIM_GATE_SUPPORTED = True, as always_on does. prompt_agent uses the same run_gate.

Off by default. A step without user_sim_gate behaves exactly as before, and to_dict leaves the field out.

Why

An LLM playing the user can slip into the assistant's role: it answers its own question, reports work as done, or offers to do the agent's job. From then on the run no longer tests the agent. Checking each message, and asking for a rewrite, keeps those messages out of the conversation, whether or not the user sim cooperates.

Only the judge holds a message back. The patterns flagged ordinary user messages, such as "Want me to send it to you?" or a user reporting their own check. The judge uses user_sim_judge's rogue rule and sees the user sim's instructions, so the gate and the run-level check agree on what counts as out of role.

How it was tested

  • Unit tests:
    • test_user_sim_gate.py:
      • judge parsing, and the judge prompt with the user sim's instructions;
      • pattern matching, curly apostrophes included;
      • only the judge holding a message back;
      • judge setup failure, and judge call errors;
      • each judge call handed over for usage, a timed-out one included;
      • run_gate on its own (rewrite, give up, send, stop);
      • a subclass with its own loop refusing the gate.
    • test_prompt_agent_user_side.py: the real _UserSide request flow. Covers a pass, the judge failing a message the patterns pass, fail after the rewrites with fail (error type, then the raise) and end, judge setup failure before any message reaches the agent, and validation and the dict round-trip.
    • test_prompt_agent_built_in_user_sim.py: the built-in user sim held back and rewritten, failing after its rewrites, a rewrite that says nothing, and the instructions passed to the judge.
    • test_always_on_user_sim_gate.py: rewrite and deliver, fail (user_sim_error), end, a rewrite with nothing to send, a pass with no rewrite, patterns only, judge setup failure, a plugin's rewrite, no gate.
    • usage_test.py: judge calls as a judge entry, with billed and estimated costs combined, and unpriced calls marked partial.
  • E2E: gated and ungated runs of the same multi-turn tasks, through the full task (deploy, conversation, snapshot), on both prompt_agent and always_on with the built-in user sim.
    • Every run completed.
    • The gate recorded a verdict for every user-sim message.
    • Nothing failed live, so the rewrite and fail paths are covered by the unit tests only.
    • These runs were on an earlier revision, in which patterns could also hold a message back. The judge-only rule and the instructions-aware judge prompt haven't run live yet.

ruff check is clean. No screenshots: the change has no UI.

🤖 Generated with Claude Code

RetriggerView in GreptileConfidence Score: 5/5

No new blocking issue was established in this review.

Summary

Adds an optional user_sim_gate to prompt_agent and always_on.

  • User-sim messages can be checked and sent back for a rewrite.
  • Prompt-agent user sims can rewrite answers before the agent sees them.
  • Always-on checks user-sim answers before its response delay.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  Candidate[User simulator writes a message] --> Gate[Record patterns and ask the judge]
  Gate -->|Pass or judge call error| Deliver[Send message to agent]
  Gate -->|Reject| Remaining{Rewrites left?}
  Remaining -->|Yes| Rewrite[Ask user simulator to rewrite]
  Rewrite --> Gate
  Remaining -->|No| Policy{on_fail}
  Policy -->|send| Deliver
  Policy -->|end| End[End conversation]
  Policy -->|fail| Fail[Record user_sim_error]
Loading

Reviews (31) · Last reviewed commit: "Merge main into kai/usersim-gate" · Reviewed by Greptile

prompt_agent's new user_sim_gate checks each LLM user-sim message before the agent receives it: phrase
patterns for the assistant's side of a conversation, and optionally a small judge model that decides only
whose voice the message is in. A message that fails is held back and the user-sim is asked to rewrite it,
up to max_rewrites times; on_fail then fails the step, ends the conversation, or sends it anyway. Every
verdict is recorded in context.metadata["user_sim_gate"].

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e its cutoffs

`user_sim_gate={}` now enables the gate with its defaults; only None leaves it off. The patterns' length and
count cutoffs, and how much of a judge's reason and error a verdict keeps, are named class constants.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@earakely-scale

Copy link
Copy Markdown
Collaborator

🤖 Automated Claude routine — Env Pod PR Context Review. This is a bot, not Edgar Arakelyan; not a human review.

Context from outside this diff, in case it's useful: there's a second open PR adding a step type that subclasses PromptAgentTaskStep and filters its inherited fields by an explicit list, so user_sim_gate would land on it as a silently-inert field.

  • This PR: src/agent_env/task_step/task_steps/prompt_agent.py:181 adds user_sim_gate as a constructor kwarg on PromptAgentTaskStep, serialized at :309-310 / :348, and enforced inside _UserSide (:1063, :1130).
  • feat(always_on): a step that runs an assistant over days of task time, with a simulated user (FD-5364) #566 (feat(always_on): a step that runs an assistant over days of task time, with a simulated user, head 974a6aba): src/agent_env/task_step/task_steps/always_on.py:201 is class AlwaysOnTaskStep(PromptAgentTaskStep). Its __init__ takes **prompt_fields and pops a fixed drop list at :217 (max_conversation_turns, user_agent_name, user_a2a_url, post_turn_hooks, user_output_format, user_model, snapshot_config), then forwards the rest to super().__init__. Its to_dict at :303-304 starts from TaskStep.to_dict(self) — not the parent's — and copies only _PROMPT_FIELDS (:252) plus _OWN.

So in either merge order, an always_on step authored with user_sim_gate is accepted at construction (it isn't in the drop list), dropped on to_dict (it isn't in _PROMPT_FIELDS), and never consulted: always_on.py has its own _Run loop and contains no reference to _UserSide, _converse or user_sim_gate. The :588 warning only fires on the prompt_agent path, so there'd be no signal either. Deciding where it goes — a third list entry, the drop list, or out of scope — is probably cheaper now than after both land.

Related, same direction: #567 addresses the same failure mode from the prompt side — user_sim_versions.py builds a system prompt around "You are not the AI assistant … Don't do your assistant's work: never look things up for it or hand over facts it should find", and user_sim.md reports a measured effect (done collapsed into the same message 9/10 → 1/10). Worth a look if you want the gate's pattern list and that prompt to agree on what counts as the assistant's voice.


Generated by Claude Code

t and others added 2 commits November 10, 2026 13:52
…te where it would be ignored

The check-and-rewrite loop moves to user_sim_gate.run_gate, with a rewrite callback, so a step type that runs
its own conversation can apply the gate; prompt_agent's user side now calls it. A PromptAgentTaskStep subclass
that replaces prompt_agent's conversation refuses user_sim_gate at construction, instead of accepting and
ignoring it, unless it sets USER_SIM_GATE_SUPPORTED = True.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Main reworked prompt_agent's user side (the built-in user sim, end_after). The gate keeps its
history wrapper in ask(), main's end_after short-circuit opens _answer(), and the gate still
checks peer user-sim messages. A gate set with the built-in user sim is warned about, as with a
non-user-sim peer, since those messages aren't checked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
t and others added 4 commits November 12, 2026 17:18
…p errors fall back to the patterns

- AlwaysOnTaskStep.from_dict passes user_sim_gate on, so a saved step is refused as one built in
  code is, rather than running with the setting dropped.
- A judge whose setup fails (its key or endpoint) no longer ends the conversation: like a failed
  judge call, the patterns' verdict stands and the error is recorded on each verdict.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ps checking

The fallback rebuilt the gate without its judge, which a judge-only gate (patterns off) refuses,
so its setup error ended the conversation. The gate's check now takes judge_unavailable instead:
the judge isn't called, the patterns' verdict stands (a pass with patterns off), and the reason is
recorded on the verdict, as for a judge call that fails. run_gate passes it only when set, so a
check override with the old signature still works.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…agent and always_on

prompt_agent applies user_sim_gate to the user deploy_user_sim_agent deployed: a held-back answer is rewritten in its session and parsed as its own answer, and the read's record keeps the first answer and lists each rewrite. always_on applies it at each read before an answer is held: one that still fails is never delivered and ends the run (user_sim_invalid; an error with on_fail fail).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
t and others added 2 commits November 16, 2026 13:07
…ite counts toward max_replies

A conversation the gate cut off with on_fail fail now records error_type user_sim_invalid on its PromptResponse, so verifiers skip it as they skip a user-sim error. A built-in user sim's rewrite replaces the held answer in the reply count, so a done rewritten into a reply counts, and max_replies ends the conversation after it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…i/usersim-gate

# Conflicts:
#	src/agent_env/task_step/task_steps/prompt_agent.py
kaihackney-scale and others added 2 commits November 19, 2026 22:31
…es its judge

Through an endpoint, a Claude judge now drops the base's trailing /v1 (its client appends /v1/messages), and a bare
name litellm can't place goes as openai/<name>. Before, both failed every call, and the gate fell back to its
patterns alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…i/usersim-gate

# Conflicts:
#	src/agent_env/task_step/task_steps/always_on.py
…d judge calls

read_cap_seconds allowed READ_ASKS user-sim turns, and the gate's rewrites ran against the same deadline, so a slow
sim could run out of time before max_rewrites and end an otherwise working run as user_sim_error. The cap now adds a
user-sim turn per rewrite and, with a judge, a judge call per message checked; wake_reserve_seconds grows with it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@cikowski cikowski left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the shape of this: off by default, one run_gate shared by both loops, every verdict recorded, and a cut-off run marked so verifiers skip it. The flow tests are thorough. My concerns are with what the gate decides and with its inputs, not the plumbing.

  1. The any-length phrases fail normal user messages. "I don't have access to that folder", "Should I send you the spreadsheet?", "The invoice has been sent to me already", "I'll pull the numbers from my bank tonight", "I apologize for the confusion" all fail pattern_reasons today. A judge can't clear a pattern hit, so adding judge_model doesn't help, and with the default on_fail: fail three of these in a row fail the step. I'd let the judge's in_role: true clear a phrase-only hit and tighten those phrases.

  2. Settings aren't type-checked. {"max_rewrites": 1.5} and {"judge_min_chars": null} are accepted and raise TypeError mid-conversation; {"patterns": "false"} turns patterns on.

  3. message in the read record is the held-back answer in prompt_agent but the delivered rewrite in always_on. user_sim_judge reads both, so it grades different things. Please pick one.

  4. If the judge can't be set up and patterns is false, every message passes for the whole run with only a log line. A setup failure is deterministic, so I'd fail the step there and keep the fallback for failed calls.

Smaller: rate_user_satisfaction only special-cases user_sim_error, so a user_sim_invalid run is reported as "the agent's turn failed".

Heads up on ordering: this conflicts with #828 in _UserSide.ask and _ask_peer. I'd land #828 first. On the rebase, the hook's note should go on the first send only (not the rewrite request), and the judge should see it, since a user sim told what it found will say "I checked ... " and that is what this gate flags.

kaihackney-scale and others added 2 commits November 20, 2026 17:08
main sends every core model call through config/model_call.py, and no other core module may import LiteLLM. The
user-sim gate's judge now resolves its route with model_call.resolve_route (judge_call_config) and calls
model_call.complete, so its routing and cost record are core's; its own routing fix and the tests of it are dropped,
with one test that the judge goes through that path. always_on keeps main's prescribe_formats import beside the gate's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…lears phrase-only hits, typed settings

- Phrases a user says no longer count: "I don't have access", "should I send", "I'll pull", "I can send it",
  "I apologize for the", "send me the results"; "has been sent/updated" counts only at a report's length.
- With a judge, an in-role verdict clears a hit on a phrase alone (PHRASE_REASONS); a report's shape and length stays
  a failure.
- UserSimGate checks each setting's type and range when the task loads, not mid-run.
- prompt_agent's read holds the answer delivered, with first_message for the first one, as always_on's does; a
  message held back for good is a no_reply.
- A judge that can't be set up fails the step when patterns are off, in both loops; with patterns on, they still
  stand alone.
- rate_user_satisfaction skips a run the gate cut off as the user sim's doing, not the agent's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
kaihackney-scale and others added 2 commits November 20, 2026 17:19
history[-0:] is the whole list, so 0 sent the entire conversation instead of none.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
#828 (a post-turn hook's note to the user sim) landed on main and met the gate in _UserSide. Both are kept, as the
review asked: the note goes with the user sim's first message only, never with the gate's rewrite request, for a peer
user sim (_ask_peer sends the first message with it through _send_to_peer, the rewrites without) and for the built-in
one. The gate's judge is shown the note (run_gate and check take user_note; the judge's prompt says what the user found
checking the work themselves), so a user sim reporting that check isn't read as the assistant. The note is recorded
in user_side_notes on both paths, as #828 does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e-failed run isn't rated

- A rewrite is parsed with the user-sim plugin's own parse(raw), as its answers are, so a plugin with another answer
  format keeps its rewrites instead of reading them as an empty no_reply. A plugin without parse can't support
  rewrites, so user_sim_gate with one is refused when the run starts.
- rate_user_satisfaction skips an always_on run the gate failed as an error (on_fail "fail", error_type
  user_sim_invalid); a plain on_fail "end" sets no error and is still rated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sarah-chitty-1

sarah-chitty-1 commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

This was actually on my todo list to build eventually, so I'm glad you're doing it! Since I'll probably end up using it for PSI, I went through it on our runs and have a few things I'd want before it merges:

  1. Use the same rule as user_sim_judge. Its rogue check already fails a run for "spoke as the assistant", and it sees the persona and instructions. If the gate's judge saw them too, it might not need the 300-char floor, and the gate and judge would agree on what counts.
  2. Don't hold back normal user messages.
    • Patterns alone shouldn't hold a message back, just trigger the judge. Right now "I checked my bank app and I verified the charge is there." gets held back at any length, and the judge can't clear it. That's the kind of thing a user sim says after a feat(prompt_agent): let a post-turn hook give the user sim a note #828 hook note. If it keeps saying it through the rewrites, the run fails.
    • Same with the default {} (no judge): "Want me to send it to you?" gets held back, and with on_fail: fail the run fails if the rewrites keep it.
    • Curly apostrophes slip past ("I’ve checked", "I’m an AI"). GPT-5.5 uses them in ~37% of messages in our replays.
  3. Fail like user_sim_judge. Could it just use error_type: user_sim_error with the gate's reason? Then the run gets redone and the existing readers already handle it. Also, in always_on a rewrite that comes back empty or no_reply just becomes a no_reply and the run carries on. It's in the gate record but not marked as a fail; I think it should be.
  4. Recording looks good. The drafts and verdicts are all in the read record.
  5. Cost: the gate's judge calls aren't in the run's usage. And with default settings, turning the gate on takes 16 min off every always_on run's time budget (19 with a judge), even if it never fires. Worth adding the usage and noting the budget hit in the docs.

FYI the patterns flagged 0 of ~3,200 real user sim messages from our runs, so it's quiet for us now, which makes it a good time to get it right.

…s, fail a rewrite with nothing to send

- Each gate judge call goes into the step's usage as a judge entry, costed as
  its endpoint billed it (StepUsage.call), in prompt_agent and always_on.
- The patterns read curly apostrophes as straight ones.
- In always_on, a rewrite that comes back as a no_reply or an empty reply
  holds the message back for good and fails the run like a failed rewrite,
  instead of becoming a no_reply the run carries on from.
- The always_on and gate docstrings note what the gate reserves from the
  run's time budget even when it never fires.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread src/agent_env/task_step/usage.py Resolved
Resolve usage.py and usage_test.py: keep main's StepUsage.cut_off and this
branch's StepUsage.call, with both sets of tests.

StepUsage.call now gives every judge call its own cost, what the endpoint
billed, else the map's price, so a role whose calls were costed different
ways sums them all instead of only the billed ones. A call with neither marks
the entry a lower bound (partial), as cut_off does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread src/agent_env/task_step/usage.py Resolved
kaihackney-scale and others added 2 commits November 22, 2026 00:14
StepUsage.call keeps each judge call's Cost as model_call costed it, and the
role's entry combines them (_combined): reported only when every costed call
was billed, otherwise priced, an estimate, with the priced calls' source, the
assumptions any made, their uncached input and unit prices when they agree,
and the bills in reported_cost_usd. RoleUsage no longer takes reported_by.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… user sim's instructions, and a failure is a user_sim_error

- The judge decides, by user_sim_judge's rogue rule ("spoke as the
  assistant"), and is shown the user sim's own instructions (rebuilt from its
  user_sims record, or the plugin's setup prompt in always_on), so it can tell
  the user reporting their own check from the assistant reporting work. The
  judge_min_chars floor is gone.
- Pattern matches are recorded on each verdict and never hold a message back
  on their own; without a judge the gate only records them.
- A judge that can't be set up fails the step, since nothing else would hold a
  message back; a judge call that errors sends the message, with the error
  recorded.
- A message that still fails with on_fail "fail" marks the run
  error_type user_sim_error (always_on's end reason too), as a failed user sim
  does, so it is redone and existing readers handle it; the error message
  names the gate's reason. prompt_agent no longer raises for it.
  rate_user_satisfaction's user_sim_invalid special cases are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
kaihackney-scale and others added 3 commits November 22, 2026 00:37
… every rewrite

The response is still recorded as a failed user sim (error_type
user_sim_error), then the step raises, so retry_config redoes the run and
fail_task_on_error applies instead of dependent steps starting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Main's StepUsage.call (a judge's Usage, #877) keeps its name; the gate's
ModelReply-costed calls are StepUsage.reply, sharing the role start that
records the model endpoint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
kaihackney-scale and others added 2 commits November 23, 2026 02:18
…ounts in the step's usage

It may still be billed, so on_call gets it as a reply of unknown usage,
which marks the judge's usage entry a lower bound.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
usage.py: main prices a role's turns by model (_by_model, _summed); this branch costs a role with calls core made
itself from those calls alone (_combined). A role with call_costs keeps that; any other role is costed as main does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
kaihackney-scale and others added 2 commits November 23, 2026 13:15
…ts judge grades what was sent

prompt_agent stores a read before the gate checks it. A rewrite updated only the read's summary, and the user-sim
judge reads the stored read over the summary, so it graded the held-back draft. The rewrite now stores the read
again with the answer that was sent (the store is write-once: under a new key, which the summary's object_url now
names), as always_on's read already holds it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
usage.py: main records a judge call through _add_call (with cut_off_call); this branch starts a role through
_role_for_call, which reply uses. call keeps main's _add_call, and _add_call starts the role through _role_for_call,
so a role starts in one place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kaihackney-scale
kaihackney-scale merged commit 9f2f476 into main Nov 24, 2026
35 checks passed
@kaihackney-scale
kaihackney-scale deleted the kai/usersim-gate branch November 24, 2026 00:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants