Skip to content

fix(capture): support Messages harnesses and gated system suffixes - #5771

Merged
yfw merged 8 commits into
NVIDIA-NeMo:mainfrom
aroshanghias-nvd:aroshanghias/claude-subagent-capture-20261106
Nov 18, 2026
Merged

yfw merged 8 commits into
NVIDIA-NeMo:mainfrom
aroshanghias-nvd:aroshanghias/claude-subagent-capture-20261106

Conversation

@aroshanghias-nvd

@aroshanghias-nvd aroshanghias-nvd commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Claude Code uses Messages requests and may append system updates, such as token-budget instructions, after tool results. Source-history capture previously rejected Messages, and appended system updates prevented continuation matching. Sandboxed runners also lost capture mode and resolved relative working directories outside their sandbox.

This PR:

  • Supports Messages source-history capture and builds completion replay evidence with the same Anthropic converter used at ingress. Served tool calls are recorded as separate function-call items with their actual ids, matching the harness's returned Responses history. Responses and Chat retain their existing replay representation. Supported Messages blocks include text, image, tool_use, tool_result, thinking and redacted_thinking; unsupported blocks still fail conversion.
  • Serves Messages content unchanged. Source-history replay omits blank text blocks to match client echoes, while local fingerprint capture retains an unchanged echo and its original token arrays. Thinking blocks, signatures, meaningful whitespace, and the all-blank fallback are preserved.
  • Adds token_id_capture.allow_system_suffix, default false, for appended system messages in source_history mode. Enable it only with a worker that verifies the rendered historical prefix remains a prefix of the full rendered request before reusing captured tokens. Older workers must leave it disabled.
  • Propagates the capture-enabled boolean into sandboxed harness runners without forwarding capture credentials. Relative execution overrides resolve inside provider-allocated local workspaces; caller-owned workdirs retain their host-relative semantics and are not joined twice.

The matching NeMo-RL worker change is RL #5138. It enables the gate and checks rendered-prefix stability. If a template relocates a new system instruction into the historical prefix, the worker uses the full prompt as a new root. Merge this Gym PR before RL #5138. This is a bounded follow-up to #4128; no separate issue is needed. Dependency pins and lockfiles are unchanged.

Validation of the current-main refresh

  • Rebased onto main b568156dfb1d9a78e9102cccf20bb0bc94eac320. Includes Christian's contributed fixes, preserving his authorship.
  • Reproduced all three reported regressions on the previous head: missing Messages tool-call evidence, unresolved local fingerprint continuation, and repo/repo sandbox execution.
  • 4,155 CPU tests passed, 13 skipped: model capture/converters, vLLM gateway, configuration, local provider, harness and Claude Code suites. Coverage includes JSON and buffered SSE continuations, preserved token arrays and token-item index, actual tool-call ids/per-item fingerprints, all-blank fallback, meaningful whitespace/thinking/signatures, and allocated/caller-owned workdirs.
  • The isolated checkpoint timing test that failed in CI passed locally. No checkpoint code was changed. The existing non-blocking harness-compliance findings concern its pre-existing run()/session interface, outside this fix.
  • Full pre-commit passed, including private guardwords and import layering. Fern validation: zero errors, one warning. Dependency pins and lockfiles are unchanged.
  • No new live-model or learner run was performed for this refresh. The live evidence below belongs to earlier revisions.

Previously published live validation

See the live-validation follow-up. These runs preceded this rebase and are not claimed as fresh GPU validation of the rebased head.

  • Actual Claude CLI, real model, production capture worker and TransferQueue: three two-call sessions produced three initial roots and three parented token-in continuations. All six calls finished with stop. Two nonempty model-generated thinking blocks were echoed in later requests, and captured prefixes of 2,987 / 4,407 / 4,761 tokens were preserved exactly. This was generation-only, without a learner.
  • A separate GRPO training step retained token-in continuity for all 13 requests containing assistant history, with TMPE 1.00734. That batch did not exercise thinking replay; the dedicated real-model check above covered it. This is not a new 20-step qualification.
  • Earlier validation passed 578 Gym tests with two skips and 56 focused RL tests. The RL validation container's configured typecheck reported a missing ZMQSocketPool export from TransferQueue in unchanged NIXL code; the overall typecheck was not green.

@copy-pr-bot

copy-pr-bot Bot commented Nov 6, 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.

Comment thread nemo_gym/models/model_call_capture.py Resolved
Comment thread nemo_gym/models/model_call_capture.py Resolved
@aroshanghias-nvd

Copy link
Copy Markdown
Contributor Author

@ananthsub Addressed the seven review comments in 528da74:

  • Removed the unreachable dialect-rejection block and updated both source-history guides.
  • Restored token stripping for Responses/Chat before joining the served completion with historical request items.
  • Clarified the replay docstring and inner-agent capture comment.
  • Asserted the exact runner capture settings; added thinking-enabled streaming/non-streaming continuity cases, strict-match and root-reason assertions, and direct replay-helper tests.

Validation: 484 focused tests passed, 2 platform skips, and pre-commit passed. The private guardword scan skipped because its catalog is unavailable. Removing token stripping fails both new Responses/Chat regression cases; either incorrect runner configuration fails the strengthened runner test. Fern validation could not run because Node/npm is unavailable in this environment. No new GPU run was performed for this revision.

The analogous harness_exa_search capture-mode propagation remains a separate follow-up, as suggested.

@ananthsub

Copy link
Copy Markdown
Contributor

@aroshanghias-nvd thanks for the updates. Could you run one short live test of Claude Code with thinking enabled on this head (528da74) before merge?

The new reasoning=True cases show the server links a continuation when the echoed history repeats the served thinking turn exactly, but the test client always echoes perfectly. What they can't show is what the real CLI sends back:

  • thinking blocks with an empty signature,
  • whitespace-only text blocks between reasoning and tool calls.

If the CLI drops or rewrites either one, every call is rooted as no_prefix_match. Nothing fails, but token-in continuity is lost.

The root reasons from the capture manifest for a few multi-turn rollouts would settle it. Most continuations should show as candidates parented to the previous call, not no_prefix_match roots.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added bug Something isn't working area:agent Agent harnesses and Responses API agent behavior needs-review PR is ready for code review and waiting on a reviewer labels Nov 7, 2026
@aroshanghias-nvd

Copy link
Copy Markdown
Contributor Author

@ananthsub You were right about the whitespace case. I checked Claude Code 2.1.303 against 528da74 with thinking enabled and two actual Bash tool turns per rollout:

  • The CLI preserves thinking blocks with signature: "".
  • It drops standalone whitespace-only text blocks. On the unfixed head, three whitespace rollouts produced six no_prefix_match continuations. Ordinary-text and no-text controls each linked both continuations.

Fixed in 140f110: omit blank text blocks from mixed Messages responses before capture records the served completion. Meaningful text is not trimmed; thinking, signatures and tool calls are unchanged. The all-blank response behavior is preserved.

With the fix, three CLI rollouts (ordinary text, whitespace-only text, empty text) all completed: three first_call roots, six parented candidate admissions committed as token_in, and no ledger failures. This used the real CLI and Gym HTTP/capture routes with a deterministic backend and synthetic token records; it is not a real-model or learner qualification. The local suite passed 575 tests with two skips; pre-commit passed, with the private guardword catalog unavailable.

A separate real-model check found that non-bare CLI requests can append a system token-budget message after tool results; eight main-agent continuations rooted as non_user_suffix. That guard is unchanged here. The run generated thinking only in terminal child calls, so it did not qualify real-model thinking replay. Broadening system-suffix admission needs a rendered-prefix safety check in RL; simply allowing it in Gym is unsafe for templates that move system messages ahead of the captured prefix.

@aroshanghias-nvd

Copy link
Copy Markdown
Contributor Author

Follow-up on the live-CLI qualification: the fixes are pushed in 970914c8, paired with RL #5138.

Appended system updates now have a default-off Gym gate. The matching RL worker enables it and verifies that the full rendered prompt starts with the separately rendered historical prefix before reusing captured tokens. A template that moves the new system instruction into the old prefix instead produces a new root with the full prompt. Older workers must leave the gate off; the Gym half should merge first.

I exercised three two-call sessions using the actual Claude CLI, a real model, the production capture worker, and TransferQueue: three initial roots and three parented token-in continuations, all six calls finishing with stop. Two nonempty model-generated thinking blocks were echoed in subsequent requests, and the captured prefixes (2,987 / 4,407 / 4,761 tokens) were preserved exactly. This was a generation-only check, with no learner.

Separately, one GRPO training step retained token-in continuity for all 13 requests containing assistant history, with TMPE 1.00734. That batch's audit correctly rejected missing thinking-replay coverage; the dedicated real-model check above closes that specific gap. This is not a fresh 20-step qualification.

Gym tests: 578 passed, 2 skipped; pre-commit passed. RL focused tests: 56 passed again after rebasing onto current main. The configured pyrefly check reported one missing ZMQSocketPool export from the validation container's TransferQueue package in unchanged NIXL code; no capture-helper errors were reported, but the overall typecheck is not green. Dependency pins and lockfiles are unchanged.

@ananthsub

Copy link
Copy Markdown
Contributor

@aroshanghias-nvd thanks for running the live checks. They settle the thinking question: empty signatures survive the round trip, blank text blocks are now dropped before capture, and the real-model sessions parented every continuation.

I re-reviewed 140f110 and 970914c. Both changes look right, and reverting either one fails its new test. Before merge, two things:

  1. Rebase. nemo_gym/models/model_call_capture.py now conflicts with main.
  2. Description. 970914c adds a new setting, token_id_capture.allow_system_suffix, and pairs it with fix(token-capture): preserve safe continuations after system updates RL#5138. Neither the title nor the description mentions it yet. Could you add what the setting allows, that it stays off unless the worker checks the rendered prefix, that this PR must merge before RL#5138, and the live-run evidence from your comment?

One small wording point: the comment above the blank-text filter in anthropic_converter.py says the blocks are omitted "before capture records the served content", but the filter runs on every Messages response, with or without capture. Something like "Messages clients drop blank text blocks when they echo history, so omit them from the served response; keep an all-blank response unchanged." would match what it does.

@aroshanghias-nvd
aroshanghias-nvd force-pushed the aroshanghias/claude-subagent-capture-20261106 branch from 970914c to a737842 Compare November 10, 2026 22:18
@aroshanghias-nvd aroshanghias-nvd changed the title fix(capture): support sandboxed Messages harnesses fix(capture): support Messages harnesses and gated system suffixes Nov 10, 2026
@aroshanghias-nvd

Copy link
Copy Markdown
Contributor Author

/ok to test a737842

@aroshanghias-nvd

Copy link
Copy Markdown
Contributor Author

Rebased in a7378429 onto current main (dff64b20), preserving its correlation-error response path. Updated the title and description to cover allow_system_suffix, its default-off rendered-prefix safety requirement, Gym-first merge order before RL #5138, and the previously posted live evidence with its validation limits. The blank-text comment now describes capture-disabled responses too.

The refreshed source passed 809 CPU tests with two platform skips, full pre-commit, and Fern validation (zero errors, one warning). The private guardword catalog was unavailable, so that audit was skipped. No new live model run was performed for this import/comment refresh.

@ananthsub

Copy link
Copy Markdown
Contributor

/ok to test a737842

@github-actions

github-actions Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

@ananthsub

Copy link
Copy Markdown
Contributor

@aroshanghias-nvd CI ran on a737842 and found one failure from this PR, and main has moved again. Three things before merge:

  1. Failing test. test_public_capture_projection_fields_match_the_supported_schema requires every TokenCaptureSettings field to be listed in _CAPTURE_PUBLIC_FIELDS in nemo_gym/config/secret_utils.py (or be one of the three credential-bearing exceptions). allow_system_suffix is a plain boolean, so adding it to the public set should fix it.
  2. Rebase. feat(vllm_model): Dynamo frontend dialect and dynamo_worker capture handler #4817 added the dynamo_worker staging backend and now conflicts with this PR in nemo_gym/models/token_capture/config.py. The conflict is in the _validate block, next to the new allow_system_suffix check.
  3. Dynamo with the system-suffix setting. After that rebase, source_history accepts dynamo_worker as well as vllm_worker, so allow_system_suffix would be accepted with either backend. RL#5138 adds the rendered-prefix check to the vLLM worker path. Does the Dynamo worker go through the same check? If not, could the validator also require external_staging_backend == "vllm_worker" when allow_system_suffix is on, so a Dynamo deployment can't turn it on without the check? @jthomson04, since you added the Dynamo backend in feat(vllm_model): Dynamo frontend dialect and dynamo_worker capture handler #4817, could you confirm whether the Dynamo worker's prefix splice would need the same change?

@aroshanghias-nvd
aroshanghias-nvd force-pushed the aroshanghias/claude-subagent-capture-20261106 branch from a737842 to 8f6610e Compare November 13, 2026 23:26
@aroshanghias-nvd

Copy link
Copy Markdown
Contributor Author

Pushed 8f6610ed, rebased onto main 37241f4e:

  • Added allow_system_suffix to _CAPTURE_PUBLIC_FIELDS and verified public projection preserves its boolean value while unknown capture fields remain masked.
  • Resolved the config conflict while preserving Dynamo source-history support with the gate off.
  • Required external_staging_backend=vllm_worker when allow_system_suffix is enabled, in addition to the existing source_history requirement. This does not claim Dynamo has the matching rendered-prefix proof.

Both the public-field omission and Dynamo opt-in acceptance reproduced before the fix. The refreshed source passed 1,117 CPU tests (two platform skips), full pre-commit including guardwords/import layering, and Fern validation (zero errors, one warning). The four backend/gate combinations are covered. No dependency pins or lockfiles changed. This was configuration-validation and rebase qualification, not a new live-model run.

@cmunley1

Copy link
Copy Markdown
Contributor

/ok to test 8f6610e

@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team November 15, 2026 22:22

@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

I found two RISKs: relative sandbox creation directories are resolved twice, and blank-text filtering breaks continuation matching for local fingerprint capture.

I inspected all 19 changed files and their affected callers and tests. The current source addresses the earlier public-field omission and restricts system-suffix opt-in to vLLM staging. This was a static review. I did not execute tests or validate the paired NeMo-RL worker.

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

Comment thread nemo_gym/models/anthropic_converter.py Resolved
@cmunley1

Copy link
Copy Markdown
Contributor

I reviewed 8f6610ed and reproduced both bot findings, plus one more gap. A patch on top of this head is below (one commit with tests, applies with git am). I did not push it to the branch.

  1. Messages evidence has no tool-call ids (completion_items). Replay now goes through the converter, but completion_items still reads a Messages response with response_to_output_items, which keeps text and tool_use blocks in one message item. A Messages call then records [reasoning, message] with ids [None, None], while a harness returns [reasoning, message, function_call]. NeMo RL's default returned_history selection compares those per-item fingerprints, so it cannot line up a Claude Code call, and served tool-call ids never reach the item-id witness. The patch builds Messages evidence from completion_replay_items, with string message content turned into output_text parts so the detectors still read the text.
  2. Blank-text filter and ordinary capture (bot finding 2, reproduced: the served echo and the captured items get different fingerprints). The patch serves Messages responses unchanged, as on main, and drops blank text blocks only where source-history reads the served turn back (completion_replay_items). Claude Code still continues (it drops blank blocks when it echoes, and the Messages API rejects them), and an unchanged echo links again under fingerprint capture.
  3. Local sandbox relative workdir (bot finding 1, reproduced: SandboxSpec(workdir="repo") then exec("pwd") raises FileNotFoundError: repo/repo). The patch joins a relative cwd only when the provider allocated the workspace, which keeps the harness runner fix. For a caller-supplied workdir, an explicit relative cwd stays host-relative, as on main.

Validation: each new test fails on 8f6610ed and passes with the patch. 4,205 tests across tests/unit_tests/models, vllm_model, config, the local provider, harness_agent and claude_code_agent pass, and pre-commit passes on the changed files. The core shard 1 failure (test_restoring_many_sessions_rewrites_their_owners_without_holding_up_the_event_loop, event-loop gap 0.77 s) is a timing test this PR does not touch, and it passes locally.

The converter-based replay also held up in a NeMo RL forest training canary with Claude Code 2.1.261 and Qwen3-8B: 66% of captured calls continued their parent.

Patch
From 36b5116aaa467a3983f9401f447f22310e875a2f Mon Sep 17 00:00:00 2001
From: Christian Munley <[email protected]>
Date: Mon, 16 Nov 2026 15:52:19 -0800
Subject: [PATCH] fix(capture): serve Messages content unchanged and record its
 tool calls

- Serve Messages responses as generated. Source-history replay drops blank
  text blocks when it reads the served turn, as Messages clients echo it, so
  ordinary capture still links an unchanged echo.
- Describe a Messages call's output evidence by the items its echo converts
  to, so served tool-call ids and per-item fingerprints match the Responses
  items a harness returns.
- Resolve a relative exec cwd inside the workspace only when the local
  provider allocated it. A caller's workdir is also the facade's default cwd.

Signed-off-by: Christian Munley <[email protected]>
---
 .../pages/model-server/model-call-capture.mdx |  2 +-
 nemo_gym/models/anthropic_converter.py        |  4 ---
 nemo_gym/models/token_capture/completion.py   | 21 ++++++++---
 nemo_gym/sandbox/providers/local/provider.py  |  4 ++-
 .../tests/test_framework_context.py           |  7 ++--
 .../models/test_anthropic_converter.py        | 22 ------------
 .../models/test_completion_evidence.py        | 32 +++++++++++++++++
 tests/unit_tests/models/test_token_capture.py | 35 ++++++++++++++++++-
 .../unit_tests/sandbox/test_local_provider.py | 13 +++++++
 9 files changed, 105 insertions(+), 35 deletions(-)

diff --git a/fern/versions/latest/pages/model-server/model-call-capture.mdx b/fern/versions/latest/pages/model-server/model-call-capture.mdx
index db12e69b9..e567e37bf 100644
--- a/fern/versions/latest/pages/model-server/model-call-capture.mdx
+++ b/fern/versions/latest/pages/model-server/model-call-capture.mdx
@@ -157,7 +157,7 @@ ordinary rollout output for framework reconstruction instead of Gym's single-cha
 | Responses history item kinds | `message`, `reasoning`, `function_call`, and `function_call_output`. |
 | Other Responses history items, including `web_search_call`, `custom_tool_call`, `custom_tool_call_output`, and opaque `compaction` | Refused with HTTP 422 before capture intent. |
 | Chat Completions with explicit history | Supported, including buffered SSE; one choice. Omitted or null `n` means one. |
-| Messages with explicit history | Supported, including buffered SSE. |
+| Messages with explicit history | Supported, including buffered SSE. Responses are served as generated; capture reads a served turn without its blank text blocks, as Messages clients echo it. |
 | Messages content block kinds | `text`, `image`, `tool_use`, `tool_result`, `thinking`, and `redacted_thinking`, converted to Responses history items. Other block kinds, such as `server_tool_use`, are unsupported. |
 | Responses `previous_response_id` or `conversation` | Refused with HTTP 422; full input must be visible. |
 | Chat `n` other than null or 1 | Refused with HTTP 422. |
diff --git a/nemo_gym/models/anthropic_converter.py b/nemo_gym/models/anthropic_converter.py
index b2c2935eb..591ed5666 100644
--- a/nemo_gym/models/anthropic_converter.py
+++ b/nemo_gym/models/anthropic_converter.py
@@ -531,10 +531,6 @@ class AnthropicConverter:
             else:
                 raise NotImplementedError(f"Unsupported Responses output item for Anthropic response: {item_type}")
 
-        # Messages clients drop blank text blocks when they echo history, so omit
-        # them from the served response; keep an all-blank response unchanged.
-        content = [block for block in content if block["type"] != "text" or block["text"].strip()] or content
-
         usage = response.usage.model_dump() if response.usage is not None else None
         message = NeMoGymAnthropicMessage.model_validate(
             {
diff --git a/nemo_gym/models/token_capture/completion.py b/nemo_gym/models/token_capture/completion.py
index b4419d172..d75f0928c 100644
--- a/nemo_gym/models/token_capture/completion.py
+++ b/nemo_gym/models/token_capture/completion.py
@@ -18,16 +18,20 @@ def completion_replay_items(response: dict[str, Any]) -> list[dict]:
     """Return the served completion as the request items its echo converts to at ingress.
 
     Messages ingress uses the shared Anthropic converter, so the served assistant
-    turn goes through the same converter. Other dialects use token-free Responses
-    output items. Replay digests match the next request's prefix when the client
-    echoes the served turn unchanged, apart from fields ignored by the converter.
+    turn goes through the same converter. Messages clients drop blank text blocks
+    when they echo history (the Messages API rejects them), so they are left out;
+    an all-blank turn is kept as served. Other dialects use their token-free served
+    items. Replay digests match the next request's prefix when the client echoes
+    the served turn, apart from fields ignored by the converter.
     """
     if response.get("type") == "message" and response.get("role") == "assistant":
+        content = response.get("content") or []
+        echoed = [block for block in content if block.get("type") != "text" or block.get("text", "").strip()]
         params = AnthropicConverter().anthropic_request_to_responses(
             {
                 "model": response.get("model", ""),
                 "max_tokens": 1,
-                "messages": [{"role": "assistant", "content": response.get("content") or []}],
+                "messages": [{"role": "assistant", "content": echoed or content}],
             }
         )
         assert isinstance(params.input, list)
@@ -50,6 +54,15 @@ def completion_items(response: dict[str, Any]) -> list[dict]:
                     item.pop("id", None)
                 items.append(item)
         return strip_token_fields(items)[0]
+    if response.get("type") == "message" and response.get("role") == "assistant":
+        # Describe a Messages turn by the items its echo converts to, so served tool-call ids and
+        # per-item fingerprints match the Responses items a harness returns. Detectors read text parts.
+        return [
+            {**item, "content": [{"type": "output_text", "text": item["content"]}]}
+            if item.get("type") == "message" and isinstance(item.get("content"), str)
+            else item
+            for item in completion_replay_items(response)
+        ]
     return strip_token_fields(response_to_output_items(response))[0]
 
 
diff --git a/nemo_gym/sandbox/providers/local/provider.py b/nemo_gym/sandbox/providers/local/provider.py
index 73a2e9a78..76ca14c4c 100644
--- a/nemo_gym/sandbox/providers/local/provider.py
+++ b/nemo_gym/sandbox/providers/local/provider.py
@@ -103,7 +103,9 @@ class LocalProvider:
             raise ValueError("The local sandbox provider cannot run commands as another user")
         inst = handle.raw
         exec_cwd = Path(cwd) if cwd else inst["workspace"]
-        if cwd and not exec_cwd.is_absolute():
+        # A relative cwd stays inside a workspace this provider allocated. A caller's workdir is a host
+        # path, and the sandbox facade passes it as the default cwd, so it is not joined again.
+        if cwd and inst["owned"] and not exec_cwd.is_absolute():
             exec_cwd = inst["workspace"] / exec_cwd
         timeout = timeout_s if timeout_s is not None else self._default_timeout_s
         async with self._semaphore:
diff --git a/responses_api_models/vllm_model/tests/test_framework_context.py b/responses_api_models/vllm_model/tests/test_framework_context.py
index 5aee3bb18..5464abb60 100644
--- a/responses_api_models/vllm_model/tests/test_framework_context.py
+++ b/responses_api_models/vllm_model/tests/test_framework_context.py
@@ -1627,15 +1627,18 @@ def test_messages_replay_keeps_continuations_and_roots_edited_history(monkeypatc
 
     first = post(body)
     feedback = [{"type": "tool_result", "tool_use_id": "call-1", "content": "solved"}] if tool else "continue"
+    # Messages clients drop blank text blocks when they echo history.
+    echoed = [block for block in first["content"] if block["type"] != "text" or block["text"].strip()]
     continued = {
         **body,
         "messages": body["messages"]
-        + [{"role": "assistant", "content": first["content"]}, {"role": "user", "content": feedback}],
+        + [{"role": "assistant", "content": echoed}, {"role": "user", "content": feedback}],
     }
     post(continued)
     manifest = harness.manifest("attempt")
     if tool:
-        assert not any(block["type"] == "text" and not block["text"].strip() for block in first["content"])
+        assert any(block["type"] == "text" and not block["text"].strip() for block in first["content"])
+        assert "call-1" in [item.id for item in manifest.records[0].output_items]
     if reasoning:
         assert any(block["type"] == "thinking" for block in first["content"])
     assert harness.worker_calls[1][0].mode == "candidate"
diff --git a/tests/unit_tests/models/test_anthropic_converter.py b/tests/unit_tests/models/test_anthropic_converter.py
index b98269cdc..e32db620d 100644
--- a/tests/unit_tests/models/test_anthropic_converter.py
+++ b/tests/unit_tests/models/test_anthropic_converter.py
@@ -479,28 +479,6 @@ class TestResponsesToAnthropicResponse:
         assert message.stop_reason == "tool_use"
         assert message.content[1].input == {"a": 1}
 
-    @pytest.mark.parametrize("blank", ["", " ", "\n\t"])
-    def test_mixed_response_omits_blank_text_without_trimming_content(self, blank):
-        content = [
-            {"type": "thinking", "thinking": "keep reasoning", "signature": ""},
-            {"type": "text", "text": blank},
-            {"type": "text", "text": "  keep this text\n"},
-            {"type": "tool_use", "id": "call-1", "name": "check", "input": {}},
-        ]
-        conv, response = self._response_from_anthropic({"content": content, "stop_reason": "tool_use"})
-        # Build distinct Responses text parts: the inverse converter coalesces
-        # adjacent Anthropic text blocks before this serialization boundary.
-        payload = response.model_dump(mode="json")
-        for item in payload["output"]:
-            if item["type"] == "message":
-                item["content"] = [
-                    {"type": "output_text", "text": block["text"], "annotations": []} for block in content[1:3]
-                ]
-        response = type(response).model_validate(payload)
-        served = conv.responses_to_anthropic_response(response, model="m")
-        assert served["content"] == [content[0], content[2], content[3]]
-        assert served["stop_reason"] == "tool_use"
-
     def test_empty_output_yields_empty_content(self) -> None:
         # Defensive: a downstream response carrying no output items maps to empty content,
         # which is still a valid Anthropic Message. (Realistic empty responses arrive as an
diff --git a/tests/unit_tests/models/test_completion_evidence.py b/tests/unit_tests/models/test_completion_evidence.py
index 84eaf592d..44b2002fb 100644
--- a/tests/unit_tests/models/test_completion_evidence.py
+++ b/tests/unit_tests/models/test_completion_evidence.py
@@ -173,3 +173,35 @@ def test_messages_replay_matches_echoed_prefix():
     generic = summarize_replay(replay_context(items[:1] + strip_token_fields(response_to_output_items(served))[0]))
     assert completion.source_digest == prefix.source_digest
     assert generic.source_digest != prefix.source_digest
+
+
+def test_messages_evidence_matches_the_items_its_echo_converts_to():
+    served = {
+        "type": "message",
+        "role": "assistant",
+        "model": "test-model",
+        "content": [
+            {"type": "thinking", "thinking": "plan", "signature": ""},
+            {"type": "text", "text": " \n"},
+            {"type": "text", "text": "  keep this text\n"},
+            {"type": "tool_use", "id": "call-1", "name": "Agent", "input": {"prompt": "solve"}},
+        ],
+    }
+    # A harness returns the call as separate Responses items, with the tool call under its served id.
+    returned = [
+        {"type": "reasoning", "summary": [{"type": "summary_text", "text": "plan"}]},
+        {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "  keep this text\n"}]},
+        {"type": "function_call", "call_id": "call-1", "name": "Agent", "arguments": '{"prompt": "solve"}'},
+    ]
+    evidence = completion_items(served)
+    assert [output_item_fingerprint(item) for item in evidence] == [output_item_fingerprint(item) for item in returned]
+    assert [item.get("id") for item in evidence] == [None, None, "call-1"]
+    assert output_validation_item(evidence[1]) == {"type": "message", "content": [{"text": "  keep this text\n"}]}
+
+    # Clients drop the blank block when they echo the turn; the replay reads it the same way.
+    echoed = [block for block in served["content"] if block is not served["content"][1]]
+    items = AnthropicConverter().anthropic_request_to_responses(
+        {"model": "test-model", "max_tokens": 64, "messages": [{"role": "assistant", "content": echoed}]}
+    )
+    expected = summarize_replay(replay_context([item.model_dump(mode="json") for item in items.input]))
+    assert summarize_replay(replay_context(completion_replay_items(served))) == expected
diff --git a/tests/unit_tests/models/test_token_capture.py b/tests/unit_tests/models/test_token_capture.py
index e752c4c47..e10b37053 100644
--- a/tests/unit_tests/models/test_token_capture.py
+++ b/tests/unit_tests/models/test_token_capture.py
@@ -47,13 +47,14 @@ from nemo_gym.core.responses_api_types import (
     NeMoGymChatCompletionCreateParamsNonStreaming,
     NeMoGymResponse,
     NeMoGymResponseCreateParamsNonStreaming,
+    NeMoGymResponseFunctionToolCall,
 )
 from nemo_gym.models.base_responses_api_model import (
     BaseResponsesAPIModelConfig,
     SimpleResponsesAPIModel,
     _request_messages,
 )
-from nemo_gym.models.model_call_capture import CaptureStore
+from nemo_gym.models.model_call_capture import CaptureStore, _reconstruct_streamed_response
 from nemo_gym.models.token_capture.config import TokenCaptureConfig, token_capture_enabled_for_agent
 from nemo_gym.models.token_capture.external_capture import TOKEN_FIELDS
 from nemo_gym.models.token_capture.fingerprint import assistant_fingerprint, conversation_digest
@@ -2459,6 +2460,38 @@ def test_served_calls_link_to_their_parent(tmp_path):
     assert entries[1].parent_resolution == ParentResolutionStatus.RESOLVED
 
 
+class _BlankTextToolModel(_CapturingModel):
+    """Serve whitespace text before a tool call, as a policy can between its reasoning and the call."""
+
+    async def responses(
+        self, request: Request, body: NeMoGymResponseCreateParamsNonStreaming = Body()
+    ) -> NeMoGymResponse:
+        response = _training_response(" \n")
+        call = NeMoGymResponseFunctionToolCall(
+            type="function_call", id="call-1", call_id="call-1", name="check", arguments="{}", status="completed"
+        )
+        return response.model_copy(update={"output": [*response.output, call]})
+
+
+@pytest.mark.parametrize("stream", [False, True])
+def test_messages_echo_with_blank_text_links_to_its_parent(tmp_path, stream):
+    """Serve blank text as generated, so an unchanged Messages echo matches ordinary capture."""
+    client = TestClient(_server(_both_enabled(tmp_path), model_cls=_BlankTextToolModel).setup_webserver())
+    path = "/ng-rollout/blank0/training-token-capture/v1/messages"
+    first = [{"role": "user", "content": "task"}]
+    response = client.post(path, json={"messages": first, "stream": stream, **_MSG_ARGS})
+    served = _reconstruct_streamed_response(response.content, "messages") if stream else response.json()
+    assert [block["type"] for block in served["content"]] == ["text", "tool_use"]
+    result = {"type": "tool_result", "tool_use_id": "call-1", "content": "ok"}
+    second = first + [{"role": "assistant", "content": served["content"]}, {"role": "user", "content": [result]}]
+    client.post(path, json={"messages": second, "stream": stream, **_MSG_ARGS})
+
+    entries = TokenCaptureStore(tmp_path).read_entries("blank0")
+    assert len(entries) == 2
+    assert entries[1].parent_resolution == ParentResolutionStatus.RESOLVED
+    assert entries[1].parent_call_id == entries[0].model_call_id
+
+
 def test_separate_model_worker_instances_share_committed_lineage(tmp_path):
     config = _both_enabled(tmp_path)
     worker_a = TestClient(_server(config, num_workers=2).setup_webserver())
diff --git a/tests/unit_tests/sandbox/test_local_provider.py b/tests/unit_tests/sandbox/test_local_provider.py
index 55a227855..029c7def1 100644
--- a/tests/unit_tests/sandbox/test_local_provider.py
+++ b/tests/unit_tests/sandbox/test_local_provider.py
@@ -293,3 +293,16 @@ async def test_exec_uses_requested_sandbox_work_directory(tmp_path: Path, absolu
         assert result.stdout == "sandbox runner directory"
     finally:
         await provider.close(handle)
+
+
+async def test_relative_caller_workdir_is_the_default_exec_directory(tmp_path: Path, monkeypatch) -> None:
+    monkeypatch.chdir(tmp_path)
+    sandbox = AsyncSandbox(LocalProvider())
+    await sandbox.start(SandboxSpec(workdir="repo"))
+    try:
+        result = await sandbox.exec("pwd")
+        assert result.return_code == 0, result.stderr
+        assert Path(result.stdout.strip()).resolve() == (tmp_path / "repo").resolve()
+    finally:
+        await sandbox.stop()
+    assert (tmp_path / "repo").is_dir()
-- 
2.54.0 (Apple Git-157)

aroshanghias-nvd and others added 8 commits November 17, 2026 13:19
- Serve Messages responses as generated. Source-history replay drops blank
  text blocks when it reads the served turn, as Messages clients echo it, so
  ordinary capture still links an unchanged echo.
- Describe a Messages call's output evidence by the items its echo converts
  to, so served tool-call ids and per-item fingerprints match the Responses
  items a harness returns.
- Resolve a relative exec cwd inside the workspace only when the local
  provider allocated it. A caller's workdir is also the facade's default cwd.

Signed-off-by: Christian Munley <[email protected]>
Signed-off-by: Ali Roshan Ghias <[email protected]>
@aroshanghias-nvd
aroshanghias-nvd force-pushed the aroshanghias/claude-subagent-capture-20261106 branch from 8f6610e to b6da830 Compare November 17, 2026 21:32
@aroshanghias-nvd

Copy link
Copy Markdown
Contributor Author

Integrated Christian's patch, preserving his authorship, and rebased onto main b568156df.

All three issues reproduced on the previous head. Messages responses now remain unchanged; replay alone normalizes blank blocks, and Messages training evidence records separate tool calls with their served ids. Local fingerprint echoes retain their parent and original token arrays. The local-provider fix avoids joining a caller's creation workdir twice while retaining main's host-relative override behavior.

Added preservation checks for meaningful whitespace, thinking/signatures, all-blank turns, token arrays/token-item index, and relative/absolute caller workdirs and execution overrides. The refreshed source passed 4,155 CPU tests (13 skips), full pre-commit, and Fern validation (zero errors, one warning). The isolated checkpoint timing test also passed locally. Existing non-blocking harness-compliance findings concern its pre-existing run()/session interface; no changes were made to that interface.

No dependency pins or lockfiles changed. This refresh has no new live-model or learner qualification; the previously posted live evidence remains scoped to its earlier revisions.

@aroshanghias-nvd

Copy link
Copy Markdown
Contributor Author

/ok to test b6da830

@aroshanghias-nvd

aroshanghias-nvd commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor Author

@ananthsub could you re-review the current head, b6da830494d97e934fc03531751f97806a6dee9c, and provide formal approval if the fixes look good? The three reported regressions are addressed and the branch is rebased; the validation summary is above (4,155 CPU tests passed, 13 skips, plus pre-commit and Fern).

@cmunley1 your patch is integrated with your authorship preserved. Could you confirm that the integration matches your intended fixes? I added preservation checks for token arrays, all-blank turns, meaningful whitespace/thinking/signatures, and caller-owned workdir overrides. The two inline findings have replies with the details.

The /ok to test command above has not advanced the CI mirror to this head yet. Could an authorized vetter confirm authorization for b6da830494d97e934fc03531751f97806a6dee9c? The current mirror still points to the previous head.

@cmunley1

Copy link
Copy Markdown
Contributor

/ok to test b6da830

@yfw
yfw added this pull request to the merge queue Nov 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

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

Merged via the queue into NVIDIA-NeMo:main with commit 461f7e6 Nov 18, 2026
76 of 78 checks passed
yfw added a commit that referenced this pull request Nov 18, 2026
Main now has #5771 (allow_system_suffix), which touches the same lines in
secret_utils.py, model_call_capture.py, token_capture/config.py,
external_capture.py and sink.py. Both settings are kept. In
install_model_call_capture each argument keeps its own closing "),".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
pthombre added a commit that referenced this pull request Nov 19, 2026
main's #5771 added the allow_system_suffix check inside the source-history loop that this
branch moved into _source_history_matches, which has no capture context. Pass the flag in.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
marcromeyn added a commit to NVIDIA-NeMo/RL that referenced this pull request Nov 23, 2026
…tures Messages

NVIDIA-NeMo/Gym#5771 added source-history capture for Messages harnesses, so
a Messages request on the capture route is forwarded to the model instead of
being refused with a 422. The case asserted a limitation that is gone; the
Responses and Chat cases still cover the gaps that remain.

Signed-off-by: Marc Romeyn <[email protected]>
marcromeyn added a commit to NVIDIA-NeMo/RL that referenced this pull request Nov 23, 2026
…tures Messages

NVIDIA-NeMo/Gym#5771 added source-history capture for Messages harnesses, so
a Messages request on the capture route is forwarded to the model instead of
being refused with a 422. The case asserted a limitation that is gone; the
Responses and Chat cases still cover the gaps that remain.

Signed-off-by: Marc Romeyn <[email protected]>
marcromeyn added a commit to NVIDIA-NeMo/RL that referenced this pull request Nov 24, 2026
…tures Messages

NVIDIA-NeMo/Gym#5771 added source-history capture for Messages harnesses, so
a Messages request on the capture route is forwarded to the model instead of
being refused with a 422. The case asserted a limitation that is gone; the
Responses and Chat cases still cover the gaps that remain.

Signed-off-by: Marc Romeyn <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:agent Agent harnesses and Responses API agent behavior bug Something isn't working 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.

5 participants