Skip to content

Agentic turn simulation environment - #5027

Merged
cmunley1 merged 10 commits into
mainfrom
jk/agentic-turn-simulation-onboard
Nov 2, 2026
Merged

cmunley1 merged 10 commits into
mainfrom
jk/agentic-turn-simulation-onboard

Conversation

@jkyi-nvidia

@jkyi-nvidia jkyi-nvidia commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Adds agentic_turn_simulation, an environment for training and evaluating whole agent turns inside agent-harness
conversations.

  • Rows. Each row is a conversation up to a user message, in the format of one harness: Claude Code, OpenCode,
    Kilo Code, Cline, Hermes, OpenClaw, or a Linux sandbox tool set. Rows are recorded or synthetic.
  • Policy. The policy plays the agent for the whole turn, from the user message to its final reply or a stop tool
    such as ask_user.
  • Simulated tools. An LLM simulates each tool result in the harness's own result format. Read-backs of files the
    turn already wrote are answered in code, so the workspace stays consistent.
  • Scoring. LLM judges score the finished turn against rubrics for correctness, steerability, request and
    discard, combined by majority vote. Code gates fail turns with schema-invalid arguments, tool calls written into
    text, or foreign-script output.
  • Masking. Only infrastructure failures are masked (time cap, context overflow, simulator or judge failure), with
    mask_sample, a namespaced failure_kind and a failure_reason.

Single-step tool-use environments score one call in isolation. This one scores the whole turn with the results of
the agent's own calls, the way a careful reader would judge it.

Components:

  • resources_servers/agentic_turn_simulation/:
    • the resources server, with one Harness profile per harness (native function calling, and Cline's XML
      protocol);
    • simulator and judge prompts, rubrics and the verdict schema;
    • optional recoverable obstacles injected into web calls (off by default);
    • data scripts to clean, mix and validate rows (scripts/);
    • docs (docs/design.md, harnesses.md, data.md, training.md).
  • responses_api_agents/agentic_turn_simulation_agent/: a SimpleAgent subclass that overrides only the episode
    loop. It runs stop tools' sibling calls before ending the turn and parses Cline's XML tool calls. It runs on the
    legacy /run route; agent sessions are refused at seed.
  • One row each in the root README environment table and fern/.../environment-list.mdx.

No related issue. This is a new, self-contained environment (verified: false).

Validation

  • pytest resources_servers/agentic_turn_simulation/tests responses_api_agents/agentic_turn_simulation_agent/tests:
    964 passed on main 705696a.
  • pre-commit run --files <the 88 changed files>: all hooks pass. The guardwords hook was skipped locally (its
    private catalog was unavailable).
  • ruff check and ruff format --check (ruff 0.9.9, the pinned version) are clean.
  • The new Python files carry the Apache-2.0 SPDX header.

Rollouts

Smoke run of the 5 example rows (data/example.jsonl, one per harness) x 1 repeat. The policy is
nemotron-3.5-super-vl and the simulator + judge is glm-5.3, both served through an OpenAI-compatible hosted
endpoint:

gym env start --config resources_servers/agentic_turn_simulation/configs/agentic_turn_simulation.yaml \
  --config <models.yaml: policy_model + agentic_turn_simulation_judge_model>
gym eval run --no-serve --agent agentic_turn_simulation_agent \
  --input resources_servers/agentic_turn_simulation/data/example.jsonl --num-repeats 1 --temperature 1.0
harness stop reason steps simulated calls reward
opencode final_message 2 1 (answered in code) 1.0
hermes final_message 1 0 1.0
claude_code final_message 2 1 (answered in code) 1.0
cline attempt_completion 2 1 (LLM) 1.0
sandbox final_message 1 0 1.0

Aggregate: turn_score 1.0, steerable_rate 1.0, code_gate_rate 0.0, 0 masked, 0 failed rollouts.

  • Example rollouts and metrics from an earlier run are committed in data/example_rollouts.jsonl and
    data/example_metrics.json.
  • With a hosted OpenAI-compatible proxy that rejects assistant history carrying reasoning under both field names,
    set reasoning_field: reasoning_content on the model servers.

Compatibility and benchmark impact

None for existing environments. This is a new resources server and agent; the only shared files touched are the two
environment-list rows. The agent's _create_episode override accepts simple_agent's resources_prefix and
activation arguments and ignores them, since it runs only on the legacy route.

Checklist

  • I have read the contributing guidelines.
  • The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs.
  • Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable).
  • Documentation added or updated, or N/A with justification.
  • Pre-commit checks pass locally (pre-commit run --all-files) (so CI lint/format checks pass). (Run on the changed files; the guardwords hook was skipped locally.)
  • New source files include the required Apache-2.0 SPDX header.
  • All commits have DCO sign-off (git commit -s) (so the DCO check passes).

🤖 Generated with Claude Code

…n environment

Add the agentic_turn_simulation resources server and agent. The policy plays one whole agent turn inside an
agent-harness conversation (Claude Code, OpenCode, Kilo Code, Cline, Hermes, OpenClaw, or a Linux sandbox tool
set). An LLM simulates the tool results, and LLM judges plus code gates score the turn.

- Harness profiles for native function calling and Cline's XML protocol, with a workspace that answers read-backs
  of known files in code.
- Rubrics for correctness, steerability, request and discard; majority voting across judges.
- Code gates for schema-invalid arguments, tool calls written into text, and foreign-script output.
- Masking for infra failures only (time cap, context overflow, simulator failure).
- Optional recoverable obstacles injected into web calls.
- Data scripts to clean, mix and validate rows. The row id key is row_id; older files are still read.
- The agent accepts simple_agent's resources_prefix and activation episode arguments; it runs on the /run route.

Validation: 964 resources-server and agent tests pass on main. A smoke eval of the 5 example rows, with a hosted
policy and a hosted GLM-5.3 simulator and judge, scored every harness.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Junkeun Yi <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Oct 24, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@jkyi-nvidia jkyi-nvidia changed the title Agentic harness simulation environment Agentic turn simulation environment Oct 24, 2026
@svcnvidia-nemo-ci svcnvidia-nemo-ci added area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer labels Oct 24, 2026
@cmunley1

Copy link
Copy Markdown
Contributor

/ok to test 5a5fc8c

@github-actions

github-actions Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

@cmunley1

Copy link
Copy Markdown
Contributor

/review

@svcnvidia-nemo-ci svcnvidia-nemo-ci left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

HOLD — three BLOCKERs can silently misclassify rewards or infrastructure masks; five RISKs affect validation, simulation fidelity, data selection, or metrics.

Reviewed all 88 changed files and traced the affected agent, simulator, verifier, workspace, and test paths. This was a static review; I could not execute tests. The checks below are proposed acceptance checks, not execution results.

Note: formal approval is not available for this request, so this review is posted as a comment only.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

text = content_text(item.get("content"))
else:
continue
if SIMULATOR_FAILED in text:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

BLOCKER — Tool content can impersonate a simulator failure and suppress scoring

Failure / blast radius: On a sandbox row offering write_file and read_file, write [tool simulator failed into a file, read it back, then finish normally. Both calls succeed in code, but this substring check finds the text inside the read result's content and masks the rollout without judging it. Shell output containing the same text also triggers it. These are policy-produced data, not infrastructure failures, so legitimate samples disappear from evaluation and training.

Correction: Change _mask_reason to recognize the simulator's failure envelope, not arbitrary text within an output. After extracting each result's body, the predicate should be equivalent to:

failure = json_object(result_body)
message = (failure or {}).get("message")
is_failure = (
    (failure or {}).get("status") == "error"
    and isinstance(message, str)
    and message.startswith(SIMULATOR_FAILED + ": ")
)

Import json_object. Cline result extraction must retain support for both framed and unframed failures; normalize those results before applying the predicate. If an unframed multi-result message cannot be distinguished reliably, carry typed failure provenance from the agent instead. The invariant is that file contents and stdout cannot become infrastructure status.

Acceptance / preservation: Proposed regression: the successful write/read example must be unmasked and reach the scripted judge, even though content contains the marker. A successful bash result with the marker in stdout must behave likewise. Actual simulator_failure("HTTP 503") must still mask, including the framed and lost-session cases in the Cline tests, without invoking a judge.

"""Correctness presupposes engagement: a turn that did not address the user is not correct."""
if not verdict:
return None
if verdict.get("addresses_concern") == "no":

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

BLOCKER — An invalid steerability verdict can still award reward 1

Failure / blast radius: A judge response {"addresses_concern": null, "correct": "yes"} is parsed successfully. correct_ladder treats anything other than literal "no" as engagement, so usable returns true and /verify awards 1. The same happens after a boolean engagement value is dropped by parse_verdict, or for "addresses_concern": "maybe". This contradicts the reward contract requiring both correctness and steerability and silently accepts malformed judge votes instead of retrying/masking.

Correction: After the existing empty-verdict guard, replace the ladder decision with:

steerability = verdict.get("addresses_concern")
if steerability == "no":
    return "no"
if steerability != "yes":
    return None
value = verdict.get("correct")
return value if value in ("yes", "no") else None

Do not require every diagnostic field: a salvaged yes/yes vote remains usable, and explicit engagement no still yields ladder no even without correctness.

Acceptance / preservation: Proposed parameterized checks for null, boolean, missing-after-parsing, and invalid-string engagement must produce an unusable vote; if every attempt returns one, /verify must return mask_sample=true, failure_kind=judge_failed, never reward 1. Update the contrary usable(expected) assertion in the invalid-field test. Retain valid votes, explicit-no gating, truncated-verdict salvage, and majority/tie behavior.

if 200 <= http.status < 400:
output = (await get_response_json(http)).get("output", "")
else:
output = (await http.content.read()).decode(errors="replace")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

BLOCKER — Simulation HTTP failures become scored tool failures

Failure / blast radius: If /simulate_tool_call returns HTTP 500 with Internal Server Error, _simulate inserts that raw page into the conversation. The verifier recognizes simulator failures only through its failure marker, so a subsequent normal final reply reaches the judge and can receive an unmasked zero for an infrastructure outage. The existing agent test explicitly demonstrates this path. It violates this environment's infrastructure-only masking contract.

Correction: Import simulator_failure from the resources server's simulator module and replace the error branch with:

else:
    detail = (await http.content.read()).decode(errors="replace")
    output = simulator_failure(f"HTTP {http.status}: {detail}")

Keep recording the original HTTP status in ep.trajectory.tool_call and keep the cookie merge before this branch. This correction must work with the verifier's structured failure recognition requested separately.

Acceptance / preservation: Extend the HTTP-error and cookie tests: a 500 followed by a final policy reply must produce a simulator-failure result and an unconditionally masked verification, with no judge call. Cookies must still survive the error and update on the next successful response. Distinguish transport errors from real tool errors: an HTTP-200 result such as {"status":"error","message":"file not found"} must remain ordinary tool evidence and be judged, not automatically masked.

# backticks closed by a run of the same length on its line). A fence left open does not hide what follows it: a call
# leaked after a file's content often comes after a fence that content opened and never closed.
_CODE = re.compile(
r"(`{3,}|~{3,})[\s\S]*?\1"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

RISK — The fence regex rejects valid quoted tool markup

Failure / blast radius: The fenced-code alternative accepts a closing backtick run anywhere, rather than a Markdown closing-fence line. For example, call_in_text flags this entirely fenced example because it closes its match at the literal delimiter in the second line:

```text
The literal delimiter is ```.
<parameter=path>
```

The real closing fence is the final line. Native turns explaining templates can therefore receive deterministic call_in_text zeros despite containing no attempted call.

Correction: Replace the fenced-block recognition used by _CODE with line-aware fence handling: a closer must use the opener's character, have at least its length, and occupy a closing-fence line with only permitted indentation/trailing whitespace. A literal run inside a content line must not close it. Keep the existing indented-code and inline-span exemptions, and retain the deliberate rule that an unclosed fence hides nothing. A safe exact regex replacement is not established here; use these delimiter invariants rather than merely making the current expression greedier.

Acceptance / preservation: Proposed checks: the example above returns False; bare Done.\n<parameter=path> returns True; an unclosed fence followed by leaked markup still returns True. Retain the nested-four-backtick, double-backtick-span, indented-block, and ordinary fenced examples in the existing gate cases.

content = message.get("content") or ""
if "</think>" in content:
content = content.rsplit("</think>", 1)[1]
content = content.strip("\r\n") # keep leading spaces: they are part of e.g. line-numbered file contents

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

RISK — Raw OpenClaw reads lose file bytes before entering the workspace

Failure / blast radius: For an initially unknown OpenClaw file, a successful LLM read response containing "\nalpha\nbeta\n" is normalized here to "alpha\nbeta". _answer then passes the normalized output to OpenClawFormat.read_back, which treats it as the complete verbatim file. Later reads and edits are answered in code from that altered content. OpenClaw reads are expressly raw file text, unlike shell output whose trailing newlines are trimmed.

Correction: Make the simulator reply contract tool-aware and lossless for OpenClaw read: thread the call name through _simulate_with_llm and Harness.parse_reply (including overrides), or use a lossless encoded envelope for this tool. Preserve actual leading/trailing line breaks and whitespace-only file contents before observation. Do not globally remove normalization: Claude Code/generic reply normalization, Hermes JSON parsing, and OpenClaw exec trimming use this shared path differently. The present raw-text transport does not distinguish wrapper newlines from file newlines, so an exact parser patch needs that contract decision rather than a blanket .strip change.

Acceptance / preservation: Proposed integration regression: seed an OpenClaw row without the file, script its first read as "\nalpha\nbeta\n", and assert both the returned output and workspace.files[path] equal those exact bytes; a second read answered in code must match. Also check a whitespace-only file. Keep cut-off replies retryable, reasoning excluded, and the existing shell/JSON normalization assertions in the simulator tests.

def locate_call(self, turn: Items, call_id: str) -> tuple[str | None, bool]:
# XML calls carry no ids of their own: the call to answer is the reply's first one without a result yet.
waiting = open_calls(turn)
return (waiting[0] if waiting else None), len(waiting) > 1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

RISK — Cline drops environment details from the last executable result before a stop

Failure / blast radius: Let one Cline reply contain read_file, then ask_followup_question, then list_files. The agent correctly executes only read_file. However, open_calls includes all three converted calls, so more_follow is true and frame removes <environment_details> from the read result. No further result runs to restore it. Thus the next user-role result message lacks the editor state that should close it. A similar boundary exists around attempt_completion, which conversion replaces with message text.

Correction: Determine more_follow from the reply's remaining executable calls before its first stop, excluding the stop itself and everything after it. Because completion tools disappear during conversion, either retain explicit stop-boundary information or pass the actual remaining-call count from the agent's _simulate_calls; the converted unanswered-call count alone is insufficient. Preserve native behavior: all non-stop sibling calls still execute there, regardless of stop position.

Acceptance / preservation: Proposed integration checks: for read → ask → list and read → completion → list, exactly one tool runs and its result retains the final environment-details block. For two ordinary Cline calls, the first result omits the block and the last retains it; ask-only executes nothing. Extend the stop-boundary test beyond its current executed-count assertion, while retaining normal multi-result framing.

return Row(
row_id=row_id(metadata),
session_id=metadata.get("session_id") or row_id(metadata),
system_prompt=metadata.get("system_prompt") or hashlib.sha256(system_text(items).encode()).hexdigest(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

RISK — Deduplication ignores system instructions carried outside input messages

Failure / blast radius: Take two first-turn rows with different row/session IDs, no verifier_metadata.system_prompt, the same substantive request (for example, Write a complete parser for this configuration format), and different responses_create_params.instructions: Use Python versus Use Rust. With no system messages, both fallback hashes are the hash of empty text. effective_sessions merges them and duplicates drops one, even though the policy must produce different answers. This silently removes distinct training targets. The row contract explicitly treats instructions as part of the system prompt.

Correction: In row_features, derive the fallback grouping prompt from both request instructions and system/developer messages, retaining the explicit metadata override. A small replacement is:

params = row["responses_create_params"]
items = params["input"]
prompt = system_text(items)
instructions = params.get("instructions")
if isinstance(instructions, str) and instructions.strip():
    prompt = instructions + ("\n\n" + prompt if prompt else "")

Then hash prompt instead of system_text(items) at this line. The invariant is that omitted grouping metadata does not erase part of the policy's system context.

Acceptance / preservation: Proposed regression: the Python/Rust rows must have different fallback groups, remain separate effective sessions, and both survive validity deduplication. Identical instructions with otherwise identical rows must still deduplicate. Preserve explicit system_prompt labels and the existing different-system-message assertion in the fallback/grouping tests.


def sandbox_shell_failures(items: Items, tool_names: Collection[str] = ()) -> int:
"""bash calls that timed out or exited non-zero, from their JSON results (`status`, `exit_code`)."""
calls = {x.get("call_id"): x for x in items if x.get("type") == "function_call"}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

RISK — Reused call IDs misattribute shell-failure metrics

Failure / blast radius: A supported transcript can reuse an ID across steps: bash(c) → {"exit_code":1} → read_file(c) → {"status":"success","content":"ok"}. This whole-turn dictionary keeps only the later read call, so sandbox_shell_failures reports 0 instead of 1. The shared calls_and_outputs helper has the converse problem: it associates every matching output with a selected call collected from anywhere in the turn. Cline's shell counter also uses whole-turn ID membership. This corrupts per-turn and aggregate shell diagnostics for parsers that reuse IDs, a case the simulator already supports.

Correction: Make calls_and_outputs pair calls/results chronologically, then filter by tool name. For example, with defaultdict/deque imports:

pending = defaultdict(deque)
for item in items:
    kind = item.get("type")
    if kind == "function_call":
        pending[item.get("call_id")].append(item)
    elif kind == "function_call_output":
        queue = pending.get(item.get("call_id"))
        if not queue:
            continue
        call = queue.popleft()
        if call.get("name") in tools:
            output = item.get("output")
            yield call, output if isinstance(output, str) else ""

Route the sandbox and Cline counters through this helper instead of their dictionary/set lookups. Existing Claude Code, Hermes, OpenClaw, and Kilo counters already consume it. Do not change the workspace's already-chronological replay.

Acceptance / preservation: Proposed checks: the mixed-tool reused-ID transcript yields exactly one bash pair and one failure; two successive bash calls reusing an ID, with exit codes 1 then 0, also count one failure. Orphan outputs remain ignored and non-text outputs remain empty text. Retain existing unique-ID timeout/nonzero counts, particularly the expected total of 2 in the sandbox counter test.

… agent close hook

Three repo-wide unit tests failed on this environment, so CI's "Core + sandbox
unit tests (coverage gate)" step stopped at its first command
(scripts/ci/core_unit_tests.sh) before the coverage gate ran:

- tests/unit_tests/test_session_contract_repo.py::
  test_agents_serve_sessions_through_the_base_hooks.
  AgenticTurnSimulationAgent overrides _seed_agent_session_state to refuse
  agent sessions but inherited Simple Agent's _close_agent_session_state,
  and the contract requires a class that defines the seed hook to define
  the close hook as well. The close hook now refuses with the seed's
  message. Behavior is unchanged: the seed never binds a session, so
  nothing reaches the close hook.

- tests/unit_tests/test_task_data.py::TestSchemaPresence::
  test_every_resources_server_ships_a_schema and
  TestRepoDataMatchesSchemas::test_all_committed_rows_validate.
  Every resources server must ship a task_data.py next to app.py, and its
  committed data/example.jsonl must validate clean against it. TaskData
  declares the verifier_metadata keys the server reads (the table in
  docs/data.md) plus the provenance keys rows carry (row_id, session_id,
  source). All are optional and marked legacy_location: verifier_metadata,
  because the run request reads them only from there.

Coverage is unchanged apart from task_data.py, which the schema tests
execute in full; no core test imports the server or agent modules.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Junkeun Yi <[email protected]>
@cmunley1

Copy link
Copy Markdown
Contributor

/ok to test 81b8125

@cmunley1

Copy link
Copy Markdown
Contributor

/review

jkyi-nvidia and others added 6 commits October 30, 2026 15:28
…usage

response.usage summed every model reply, including replies cut off at their
output budget and then discarded (retried with a doubled budget, or ending the
turn as max_output_tokens). The trajectory references only kept replies, and
Gym's rollout_token_count_mismatch health check compares response.usage with
the captured calls the trajectory references, so every discarded reply made
the rollout unhealthy.

Accumulate usage only for kept replies. response.metadata.model_calls is
unchanged: it still lists every reply, discarded ones with kept=false, so
their cost stays visible. A turn with no kept reply now reports no usage, as
a turn without any reply already did.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Junkeun Yi <[email protected]>
…ence settings

The README example ran with --max-output-tokens 32768 and set
propagate_context_overflow_errors=true on the policy, with a bullet
recommending it. Gym's default for that flag (false) is kept: measured on
12,340 rollouts, the budget-shrink rescue it enables never fired.

- README and docs/data.md: the eval and profiling examples use
  --max-output-tokens 65536.
- README and docs/training.md: drop the propagate_context_overflow_errors
  override and the README bullet recommending it; docs/training.md and the
  agent README now state what the flag does without asking for it.
- README: add "Reference evaluation settings": 4 repeats, a 65,536-token
  reply budget, max_time_seconds 1,200 and max_steps 50, a GLM 5.3-class
  simulator and judge at reasoning effort high and temperature 1, and why
  simulator and judge capacity matters (the turn time cap counts wall time).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Junkeun Yi <[email protected]>
…tches its schema

usable() only needed correct_ladder() to be yes/no, so a vote whose
addresses_concern was null, missing or outside its enum still counted, and
with correct: yes it could pay reward 1 without any steerability verdict.

A verdict is now usable only when every field evaluation_schema.json
requires is present, a string, and one of the schema's enum values where it
has an enum (read from the schema, not duplicated). correct_ladder() is None
for an unusable verdict and keeps its rule for valid ones (addresses_concern
no -> no, yes -> correct). The existing judge loop retries unusable verdicts
up to judge_max_attempts and masks the rollout as judge_failed when no judge
has a usable one; voting and tie-breaking are unchanged.

The truncated-verdict salvage in parse_verdict is kept, under the same rule:
a salvaged verdict is usable only when the cut came after every required
field; otherwise the judge is retried (with its budget doubled, as before).

All 2,203 stored judge verdicts fully match the schema, so scoring on normal
data does not change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Junkeun Yi <[email protected]>
…e turn as an infra failure

A non-2xx reply from the resources server's /simulate_tool_call was inserted
into the conversation as the tool result, raw body and all, and the turn went
on to be judged: the policy was scored on an environment failure.

The agent now retries the POST (simulate_max_attempts, default 3 in all,
backing off 1 s then 2 s). If every attempt fails, the tool output is the
resources server's own failure output,
simulator_failure(f"HTTP {status}: {detail}"), which /verify already
recognizes and masks as simulator_failed without calling the judge. The
trajectory's tool-call record keeps the last HTTP status, and the cookie
merge is unchanged, so the session survives error replies and retries.

A 2xx reply is still the tool's output, including an error the simulated
tool reports (for example a missing file); such turns are judged as before.
Stored rollouts show no simulate-endpoint HTTP errors, so scoring on normal
data does not change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Junkeun Yi <[email protected]>
…olicy server reports the overflow

The README said a row that does not fit the policy's context is masked. That holds only with
propagate_context_overflow_errors: true on a vllm_model policy. With Gym's default (false) the server
returns an empty cut-off reply, the turn ends on max_output_tokens and scores 0. docs/data.md and
docs/training.md already say this; the README now matches them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Junkeun Yi <[email protected]>
@jkyi-nvidia

Copy link
Copy Markdown
Contributor Author

/ok to test 5a5fc8c

@copy-pr-bot

copy-pr-bot Bot commented Oct 30, 2026

Copy link
Copy Markdown

/ok to test 5a5fc8c

@jkyi-nvidia, there was an error processing your request: E2

See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/2/

@jkyi-nvidia

Copy link
Copy Markdown
Contributor Author

/ok to test c1623e5

@copy-pr-bot

copy-pr-bot Bot commented Oct 30, 2026

Copy link
Copy Markdown

/ok to test c1623e5

@jkyi-nvidia, there was an error processing your request: E2

See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/2/

@svcnvidia-nemo-ci svcnvidia-nemo-ci left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

SHIP WITH CARE — the five prior RISKs below remain unresolved; the three prior BLOCKER counterexamples are fixed.

Verified the fixes for invalid steerability votes in judge validation, simulation HTTP failures in the agent, and the original phrase-only masking examples in failure recognition.

Completed the follow-up against reviewed head 5a5fc8c0d5d4c90dd08f79b2c0fff9712bc0b017: checked all eight prior findings, subsequent changes, relevant regression assertions, and directly affected agent/simulator/verifier/data paths. No new regression meeting the above-moderate publication threshold was established. This was not a fresh whole-PR review.

Static inspection only; tests were not executed. Acceptance checks below are proposed, and suggested code must be verified before adoption.

Review generated by codex. This was a findings-only review. Request a full review with /review reset=true.

# backticks closed by a run of the same length on its line). A fence left open does not hide what follows it: a call
# leaked after a file's content often comes after a fence that content opened and never closed.
_CODE = re.compile(
r"(`{3,}|~{3,})[\s\S]*?\1"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

RISK — The valid fenced-example false positive remains

Failure: Prior comment 4367980631 remains unresolved. The fenced alternative closes at a matching delimiter anywhere, including the literal backticks in this content line:

```text
The literal delimiter is ```.
<parameter=path>
```

It removes only through that literal delimiter, exposing <parameter=path>. call_in_text/code_gate consequently reject a native assistant explanation, and /verify returns unmasked reward 0 without judging it. Expected: markup inside this closed code block is exempt.

Correction: Could you replace _CODE's fenced-block recognition with line-aware fence handling? A closer must occupy a closing-fence line, use the opener's character, contain at least its delimiter length, and allow only permitted indentation/trailing whitespace. An embedded delimiter must not close the block. Preserve the inline-span and indented-block exemptions and the deliberate rule that an unclosed fence hides nothing. A safe drop-in regex replacement is not established here; making the current expression greedier is insufficient.

Acceptance / preservation: Proposed checks: call_in_text returns False for the exact example, True for bare Done.\n<parameter=path>, and True for an unclosed fence followed by leaked markup. With a scripted passing judge, the example reaches /verify's judge with code_gate=None and reward 1. Retain the existing assertions: ordinary backtick/tilde blocks, four-backtick blocks quoting shorter fences, double-backtick spans and indented blocks remain exempt; real leaked calls remain gated; Cline and reference-turn text remain exempt.

content = message.get("content") or ""
if "</think>" in content:
content = content.rsplit("</think>", 1)[1]
content = content.strip("\r\n") # keep leading spaces: they are part of e.g. line-numbered file contents

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

RISK — Raw OpenClaw reads still lose file bytes

Failure: Prior comment 4367980635 remains unresolved. On an OpenClaw row without a known file, script the first read simulator response as "\nalpha\nbeta\n". This parser returns "alpha\nbeta"; the server observes that altered result, and OpenClawFormat.read_back treats it as the complete verbatim file. Later exact reads and edits operate on changed content. A whitespace-only file is rejected altogether.

Correction: Make the simulator reply contract tool-aware and lossless for OpenClaw read: thread the call name from _answer through _simulate_with_llm and Harness.parse_reply, updating overrides without changing their behavior, and provide a lossless read representation. Update the OpenClaw simulator prompt consistently. The invariant is that a successful whole-file read reaches the policy and workspace with identical, exact content. An exact parser replacement remains uncertain because raw text does not distinguish wrapper newlines from file newlines; globally removing normalization is unsafe.

Acceptance / preservation: Proposed integration regression: with an initially unknown path, return "\nalpha\nbeta\n" from its first simulated read; assert endpoint output and workspace.files[path] equal that exact string, then assert a second exact read matches. Repeat with whitespace-only content. Keep cut-off replies retryable and reasoning excluded. Preserve generic/Claude Code newline normalization and Hermes JSON parsing in the parser assertions. Distinguish OpenClaw exec: its existing assertion deliberately removes trailing newlines.

def locate_call(self, turn: Items, call_id: str) -> tuple[str | None, bool]:
# XML calls carry no ids of their own: the call to answer is the reply's first one without a result yet.
waiting = open_calls(turn)
return (waiting[0] if waiting else None), len(waiting) > 1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

RISK — Cline still removes editor state from the last result before a stop

Failure: Prior comment 4367980636 remains unresolved. For read_file → ask_followup_question → list_files in one reply, the agent executes only the read. Here, open_calls includes the question and list, so more_follow=True makes frame remove the read's <environment_details>. No later result restores it. read_file → attempt_completion → list_files also fails because conversion turns completion into text, losing the stop boundary. Expected: the final executed result closes the user message with editor state.

Correction: Carry whether another executable result follows from the agent's already-truncated call list. Suggested small contract change:

results.append(await self._simulate(
    ep, call, dumped,
    more_follow=protocol == CLINE_XML and index + 1 < len(calls),
))

Add keyword-only more_follow: bool | None = None to _simulate and include "more_follow": more_follow in its POST JSON.

  • After the server's locate_call, apply:
if body.more_follow is not None:
    more_follow = body.more_follow

This retains inference for callers omitting the field. No stop-selection change is needed.

Acceptance / preservation: Proposed agent/server checks: read → ask → list and read → completion → list execute exactly one call whose result retains the final environment block; ask-only executes none. Two ordinary Cline calls still omit the block from the first result and retain it on the last, matching existing framing assertions. Preserve native execution of every non-stop sibling regardless of stop position, as the native test asserts. The current Cline stop test manually supplies intact editor state rather than exercising its generation.

return Row(
row_id=row_id(metadata),
session_id=metadata.get("session_id") or row_id(metadata),
system_prompt=metadata.get("system_prompt") or hashlib.sha256(system_text(items).encode()).hexdigest(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

RISK — Fallback deduplication still ignores request instructions

Failure: Prior comment 4367980640 remains unresolved. Give two first-turn rows distinct row/session IDs, omit verifier_metadata.system_prompt, use the same user request (Write a complete parser for this configuration format), and set responses_create_params.instructions to Use Python versus Use Rust. Without system messages, both fallback groups hash empty text; effective_sessions merges them and duplicates drops a distinct training target. The row contract includes instructions in the system prompt.

Correction: In row_features, replace the current items assignment with:

params = row["responses_create_params"]
items = params["input"]
prompt = system_text(items)
instructions = params.get("instructions")
if isinstance(instructions, str) and instructions.strip():
    prompt = instructions + ("\n\n" + prompt if prompt else "")

Then use hashlib.sha256(prompt.encode()).hexdigest() for the fallback at this line, retaining the explicit metadata override. Update the docstring accordingly. The invariant is that fallback grouping retains instructions and system/developer-message context, consistent with runtime prompt composition.

Acceptance / preservation: Proposed regression: the Python/Rust rows have different fallback groups, remain separate effective sessions, and duplicates(rows, set()) == (set(), set()). Identical instructions with otherwise identical first-turn rows still deduplicate to one. Explicit system_prompt labels must continue to win; blank/missing instructions retain the existing fallback. Retain the existing assertion that different system-message content does not group.


def sandbox_shell_failures(items: Items, tool_names: Collection[str] = ()) -> int:
"""bash calls that timed out or exited non-zero, from their JSON results (`status`, `exit_code`)."""
calls = {x.get("call_id"): x for x in items if x.get("type") == "function_call"}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

RISK — Reused call IDs still misattribute shell-failure metrics

Failure: Prior comment 4367980641 remains unresolved. For bash(c) → {"exit_code":1} → read_file(c) → {"status":"success","content":"ok"}, this whole-turn dictionary retains only the read and reports zero shell failures instead of one. The shared helper conversely associates every matching output with a selected call collected anywhere in the turn; Cline's counter uses whole-turn ID membership too. Incorrect counts reach per-turn and aggregate shell diagnostics. Repeated IDs across steps are explicitly supported.

Correction: Add defaultdict/deque imports and replace calls_and_outputs' body with chronological pairing before tool filtering:

pending = defaultdict(deque)
for item in items:
    kind = item.get("type")
    if kind == "function_call":
        pending[item.get("call_id")].append(item)
    elif kind == "function_call_output":
        queue = pending.get(item.get("call_id"))
        if not queue:
            continue
        call = queue.popleft()
        if call.get("name") in tools:
            output = item.get("output")
            yield call, output if isinstance(output, str) else ""

Route sandbox through calls_and_outputs(items, ("bash",)) and Cline through calls_and_outputs(items, ("execute_command",)), retaining their current result parsing and failure predicates. Claude Code, Hermes, OpenClaw and Kilo already consume this helper. Leave workspace replay unchanged.

Required dependent preservation: The verifier currently removes injected results but leaves their calls. Before feeding FIFO counters, remove each excluded result's paired call too; otherwise an unanswered injected fetch can consume a later bash result sharing its ID. Import the existing chronological answered_calls helper and replace shell_items construction with:

excluded = set(failed_results)
excluded.update(
    call for call, result in answered_calls(items).items()
    if result in failed_results
)
shell_items = [x for i, x in enumerate(items) if i not in excluded]

Acceptance / preservation: Proposed checks: the mixed-tool example yields one bash pair and one failure; successive bash calls reusing an ID with exits 1 then 0 count one failure. Orphan/pre-call outputs remain ignored and non-text outputs remain empty text. Retain the unique-ID sandbox total of 2. Extend the injected-result preservation case to use the real counter: injected fetch(c), then real bash(c) exiting 1, must count exactly one real shell failure.

cmunley1
cmunley1 previously approved these changes Oct 30, 2026
@jkyi-nvidia
jkyi-nvidia enabled auto-merge October 30, 2026 23:30
@cmunley1

Copy link
Copy Markdown
Contributor

/ok to test c1623e5

@cmunley1

Copy link
Copy Markdown
Contributor

The Unit tests / Test failure comes from this PR (job, 1 failed, 13,341 passed):

tests/unit_tests/config/test_global_config.py::TestComposeUnboundAgent::test_agent_session_agent_types_match_the_agent_apps

That test collects every responses_api_agents/*/app.py that defines _seed_agent_session_state( and checks the set equals AGENT_SESSION_AGENT_TYPES. The new agentic_turn_simulation_agent/app.py defines it, but the agent is not in that set:

Extra items in the left set:
'agentic_turn_simulation_agent'

Fix: add "agentic_turn_simulation_agent", to AGENT_SESSION_AGENT_TYPES in nemo_gym/config/global_config.py (first entry, to keep it sorted). If this agent is not meant to seed agent sessions, drop _seed_agent_session_state from its app instead.

The kilocode conformance probe failure (non-blocking, model_error scenario) is unrelated. This PR does not touch kilocode and the same probe fails on main. Nemo_CICD_Test and the conformance Publish check are red only because of these two.

…efuse session episodes in _create_episode

Main's test_agent_session_agent_types_match_the_agent_apps requires every agent app that defines
_seed_agent_session_state to be listed in AGENT_SESSION_AGENT_TYPES. This agent defined it only to refuse
agent sessions, and listing it would make config composition drive it through agent sessions instead of
relaying it through /run. Follow the other SimpleAgent subclasses that do not take sessions
(gdp_pdf_agent, langchain_deepagents_agent, labbench2_vlm_agent): no session hooks, not in the set.

To keep the refusal, _create_episode now raises before any call when it gets an agent session
(in_session or a tool grant). resources_prefix and activation are not session marks: /run passes them
too when Gym's rollout checkpointing is on, and a test covers that case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Junkeun Yi <[email protected]>
@jkyi-nvidia

Copy link
Copy Markdown
Contributor Author

/ok to test a308d33

@cmunley1
cmunley1 added this pull request to the merge queue Nov 2, 2026
@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/41532479497

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/41534674799

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/41537456973

Merged via the queue into main with commit f0c9450 Nov 2, 2026
54 of 57 checks passed
@cmunley1
cmunley1 deleted the jk/agentic-turn-simulation-onboard branch November 2, 2026 23:10

This branch was previously deployed

1 inactive deployment
public — a308d33f Deployed Nov 2, 2026 by copy-pr-bot[bot] via release / finalize / notify #9297
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants