Skip to content

fix(harness): remove quoted-space write command and surface its error output - #3269

Open
aMetric wants to merge 1 commit into
agentscope-ai:mainfrom
aMetric:fix/sandbox-write-quoting-and-error
Open

aMetric wants to merge 1 commit into
agentscope-ai:mainfrom
aMetric:fix/sandbox-write-quoting-and-error

Conversation

@aMetric

@aMetric aMetric commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Refs #3262 (part d — error visibility). Part a (the quoted-space command) landed on main via #3871, so this PR no longer touches command construction.

What does this PR do?

The Windows-host quoting defect from #3262 / #3850 is fixed on main (e190a8d1b, #3871): write() and move() now compute the parent directory in Java and pass it to mkdir -p as a single-quoted literal. This branch has been rebased onto that commit, so what remains is the other half of the original issue — what the model is told when a sandbox mutation fails.

  • Failure detail surfaced. write() returned a bare Failed to write file '<path>' and dropped checkResult.output() — the only place in the file that discarded it. It now appends the sandbox's own diagnostic, matching the upload branch's convention.
  • Detail is bounded. Raw output is clamped to 500 chars, keeping the tail (that is where shells put the actual error line after a command's preamble). The cut backs off one char when it lands on a low surrogate, so the JSON sent to the model never carries a lone surrogate.
  • Mutations fail closed. ExecuteResponse.exitCode() is an Integer. The previous result.exitCode() != 0 unboxed a null and threw NPE in move()/delete(); write() treated a null status as success and went on to upload. All three now report no exit status reported instead of guessing.
  • One detail path. executeFailureMessage() now delegates to the same failureDetail() helper, so ls/read/edit/grep/glob inherit the clamp and the explicit null-status wording rather than embedding arbitrarily long output.

Verification

New tests in BaseSandboxFilesystemTest (canned-response group, runs on every platform):

  • write_commandHasNoDoubleQuotedSpanContainingSpace — regression guard: no generated write()/move() command may contain a double-quoted span with a space;
  • write_failureMessageCarriesExecuteOutput — the container's dash syntax error appears in the failure message;
  • write_failureMessageClampsHugeOutput — 50K of stderr is clamped and flagged [output truncated];
  • write_failureMessageHandlesNullOutput / move_failureMessageHandlesNullOutput — null output falls back to the exit code;
  • write_failureMessageHandlesNullExitCode / move_failureMessageHandlesNullExitCode / delete_failureMessageHandlesNullExitCode — unknown status fails closed with no exit status reported;
  • write_failureMessageFallsBackToExitCodeWhenOutputBlank — blank output falls back to the exit code.

Full mvn -pl agentscope-harness test: 1601 tests, 0 failures, 37 skipped (Linux/Docker-only), spotless:apply clean.

Risk

Low: failure paths only — no command construction, no success-path behavior. The only observable change on the happy path is none; everything else adds information to a message that previously had less.

@CLAassistant

CLAassistant commented Sep 23, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@codecov

codecov Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 65.51724% with 10 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...gent/filesystem/sandbox/BaseSandboxFilesystem.java 65.51% 5 Missing and 5 partials ⚠️

📢 Thoughts on this report? Let us know!

+ "d=$(dirname "
+ escapedPath
+ ")\" 2>&1";
+ "); mkdir -p \"$d\" 2>&1";

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.

Same #3262 failure mode is still open in move(). ~line 441 of this file builds "mkdir -p $(dirname " + escapedTo + ") && mv ..." — here the substitution is unquoted, so a toPath whose parent contains a space word-splits: mkdir -p a b creates two junk directories and the following mv then fails. It is a different quoting defect from the one this PR fixes, but it is the same "path with a space breaks sandbox filesystem ops" family the issue is about. Applying the same d=$(dirname X); mkdir -p "$d" idiom (which also keeps the no-double-quoted-span-with-space invariant) would close it, and the new scanner test could then be extended to the other command builders in this class so this cannot regress again. Not a blocker for this PR's own change, which I verified is correct.

checkResult.output() != null && !checkResult.output().isBlank()
? checkResult.output().strip()
: "exit code " + checkResult.exitCode();
return WriteResult.fail("Failed to write file '" + filePath + "': " + detail);

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.

Surfacing the container's error output instead of a bare Failed to write file '...' is exactly right — this is what was missing to diagnose #3262. One thing to consider: detail is the raw command output and is passed through unbounded into a tool result the model sees, while this project elsewhere treats ~80 K chars as the point where tool results become context-overflow territory (ToolResultEvictionConfig.DEFAULT_MAX_RESULT_CHARS). A failed mkdir will not produce that much output today, so this is a nit about keeping the invariant local rather than dependent on which commands can fail: clamping detail (e.g. first ~500 chars) would make this message safe regardless of what execute returns.

@oss-maintainer

Copy link
Copy Markdown
Collaborator

Summary

Fixes the quoted-space failure in BaseSandboxFilesystem.write() by keeping the dirname result in a variable (d=$(dirname ...); mkdir -p "$d") so no double-quoted span in the command contains a literal space, and appends the container's real error output to the write-failure message. Verified against current main: FilesystemUtils.shellQuote single-quotes the path (' → '\''), a command substitution in an assignment is not subject to word splitting, and the trailing-newline strip makes "$d" byte-identical to the old "$(dirname ...)" — so the change is behaviour-preserving on POSIX hosts while removing the span that the Windows argv → command-line → docker.exe re-parse corrupts. CLA signed and build (ubuntu-latest), build (windows-latest), Check License, Check Module Sync and codecov/patch are all green on this head.

Two findings, neither a blocker: the same family of space-in-path breakage is still live in move() (inline), and the newly-surfaced error detail is unbounded into a model-visible tool result (inline nit). Good call on the invariant scanner test rather than only a behavioural assertion.


Automated review by github-manager-bot

aMetric added a commit to aMetric/agentscope-java that referenced this pull request Sep 23, 2026
…ror output (agentscope-ai#3262)

Review follow-up on agentscope-ai#3269:

- move(): 'mkdir -p $(dirname <to>)' left the substitution unquoted, so a
  parent path with a space word-split (mkdir -p a b creates junk dirs);
  now uses the same d=$(dirname <to>); mkdir -p "$d" idiom as write(),
  keeping the no-double-quoted-span-with-space invariant
- the failure detail surfaced by write() (and now move()) is clamped to
  500 chars via clampDetail — the raw execute() output was passed through
  unbounded into a tool result the model sees
- the double-quoted-span scanner test now also covers move()'s command;
  new test asserts huge command output is clamped with a note
@aMetric

aMetric commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

Both review findings addressed in a4b6988:

  • move() same-family defect fixed: mkdir -p $(dirname <to>) → d=$(dirname <to>); mkdir -p "$d" — the unquoted substitution word-split on parent paths with spaces, exactly as flagged. Same idiom as write(), so the no-double-quoted-span-with-space invariant holds; the scanner regression test now covers move()'s constructed command too.
  • detail clamped: new clampDetail() caps the raw execute() output embedded in failure messages at 500 chars with an [output truncated] note, applied in both write() and move() — the invariant no longer depends on which commands can fail loudly. Covered by write_failureMessageClampsHugeOutput (50K-char output → <700-char message).

Full agentscope-harness suite passes locally (1047 tests).

@oss-maintainer oss-maintainer 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.

Summary

Re-reviewed a4b69884. Both follow-ups from the previous round are in: move() now uses the same quote-free-spread d=$(dirname …); mkdir -p "$d" idiom (closing the word-split path of #3262), and the raw container output embedded in failure messages is clamped by clampDetail(). CI is green on both ubuntu and windows runners and the CLA is signed. The analysis is unchanged for write(): FilesystemUtils.shellQuote single-quotes the path, so keeping the dirname result in a variable really does remove the last double-quoted span that could contain a space.

One regression introduced by the new commit is worth fixing before merge (clampDetail() is not null-safe while move() calls it without the guard the write() path has), plus a note that the scanner test only exercises the move() command.


Automated review by github-manager-bot

* message safe regardless of what {@code execute} returns — the project treats ~80K chars
* as context-overflow territory for tool results, so error details get a tight local bound.
*/
private static String clampDetail(String output) {

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.

[Warning] clampDetail() dereferences output immediately (output.strip()), but the new move() call site passes result.output() with no null guard, unlike the write() path which checks != null && !isBlank() first.

A null output is reachable through the sandbox execution layer: SandboxBackedFilesystem.execute() returns new ExecuteResponse(e.getMessage(), 124, false) for ExecTimeoutException, and Throwable.getMessage() may be null — so a timeout inside move() now fails with an NPE thrown out of the filesystem API instead of a WriteResult.fail(...).

Suggest normalising inside the helper so no caller has to repeat the guard:

private static String clampDetail(String output) {
    if (output == null || output.isBlank()) {
        return "";
    }
    String stripped = output.strip();
    ...
}

(and let move() fall back to the exit code when the returned detail is blank, mirroring write()).

fs.write(RT, "dir with space/file.txt", "content");

// Review follow-up: move() builds commands with the same idiom — scan it too.
fs.lastCommand = null;

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.

[Info] Nice that the scanner now covers move() as well — but note that fs.lastCommand = null discards the command that write() just built, so the assert only ever inspects the move() command. If the write() builder regresses back to mkdir -p "$(dirname …)", this test still passes.

Suggest running the span scan over both commands (e.g. capture the write command into a local variable before the move() call, and assert on each) so the guard covers both builders in one test.

aMetric added a commit to aMetric/agentscope-java that referenced this pull request Sep 24, 2026
…agentscope-ai#3262)

Review follow-up on agentscope-ai#3269:

- clampDetail() now handles null output inside the helper: move() passes
  result.output() unguarded and the execution layer can produce null
  (ExecTimeoutException via a null Throwable.getMessage()) — that path
  would have thrown an NPE out of the filesystem API
- the double-quoted-span scanner asserts on BOTH the write() and move()
  commands (previously the move() call overwrote lastCommand, so a
  regression in write()'s builder would still pass)
- new tests: write/move failure paths with null output (exit-code
  fallback, no NPE)
@aMetric

aMetric commented Sep 24, 2026

Copy link
Copy Markdown
Contributor Author

Both findings fixed in 43940fa:

  • Null-safety moved inside clampDetail(): null -> "no output" — move() passes result.output() unguarded and the execution layer can produce null (ExecTimeoutException via a null Throwable.getMessage()), which would have thrown an NPE out of the filesystem API. The guard now lives in the helper so no caller has to repeat it. New tests cover null output on both the write() and move() failure paths.
  • Scanner asserts on both commands: the test captures write()'s command before calling move() and runs the span scan on each — a regression in either builder now fails it (assertNotNull guards the capture itself).

@oss-maintainer oss-maintainer 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.

Summary

Re-reviewed the new commit 43940faf — both points from my previous pass are addressed correctly: clampDetail() now short-circuits on null (with a comment explaining why), and the quoting regression test now asserts on the write() and move() commands separately instead of overwriting fs.lastCommand. Added write/move_failureMessageHandlesNullOutput cover the intended branch. Thanks for the quick turnaround.

Findings

  • [Warning] BaseSandboxFilesystem.java:465 — move() and write() now produce different strings for the same null-output condition ("no output" vs "exit code <n>"); and the sibling if (result.exitCode() != 0) on L458 still unboxes a nullable Integer, which is the same class of NPE this commit just removed from clampDetail().
  • [Info] BaseSandboxFilesystemTest.java:306 — the new move() null test uses a non-null exit code, so the null-exitCode branch stays uncovered.
  • [Info] (not in diff, so no anchor) executeFailureMessage() at L486-492 passes result.output() through unclamped and is used by five call sites — ls (L103), read (L157, L182), grep (L360), glob (L402). Those paths can still put arbitrary-length raw container output into a model-visible tool result, which is exactly what MAX_DETAIL_CHARS was introduced to bound here. Routing them through the same clamp (they can just call clampDetail(detail)) would close the last gap; happy to see it in a follow-up rather than blocking this PR.

Verdict

Not blocking: the two anchored points are small and local. Once move()'s exitCode guard is in parity with write(), this is good to go from my side.


Automated review by github-manager-bot

+ "' to '"
+ toPath
+ "': "
+ clampDetail(result.output()));

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.

[Warning] Two follow-ups on the new move() failure path.

  1. clampDetail(null) now returns "no output", but write() short-circuits to "exit code <n>" for the same condition (L224-228). Same root cause, two different tool-result strings — a shared detailOrExitCode(result) helper would keep them uniform (and executeFailureMessage() could use it too).
  2. The sibling if (result.exitCode() != 0) on L458 still unboxes a nullable Integer: ExecuteResponse.exitCode() is an Integer, so a null exit code throws NPE here — the exact class of failure this commit just made clampDetail() immune to. write() already guards it (checkResult.exitCode() != null && checkResult.exitCode() != 0). Suggested parity: if (result.exitCode() == null || result.exitCode() != 0).

"command contains a double-quoted span with a space: " + cmd);
i = close + 1;
}
}

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.

[Info] move_failureMessageHandlesNullOutput passes exitCode = 124, so it covers the null-output branch but not the null-exitCode branch described above. One more case with new ExecuteResponse("boom", null, false) would pin the whole null-tolerance contract for move().

@oss-maintainer oss-maintainer 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.

Summary


Automated review by github-manager-bot

+ "d=$(dirname "
+ escapedPath
+ ")\" 2>&1";
+ "); mkdir -p \"$d\" 2>&1";

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.

The new command still ends with a double-quoted $d expansion (mkdir -p "$d"), and issue #3262's own diagnosis is that the Windows argv -> command-line -> docker.exe round trip DROPS inner double quotes. The command is safe only because no space sits inside those particular quotes, but $d is a runtime value that can contain spaces (the parent of dir with space/file.txt), so if the quotes are stripped before sh -c the container receives mkdir -p $d, word-splits it into mkdir -p dir with space, exits 0 after creating junk directories, and the write then fails later inside uploadFiles with a misleading error. Single quotes are evidently preserved by that transport (they are literal characters on Windows), so the transport-proof construction is to derive the parent directory in Java and emit it as a single-quoted literal (mkdir -p 'dir with space'), which also removes the shell variable entirely. At minimum, please confirm on the reporter's Windows host - with both a space-free and a space-containing parent - before closing #3262, because the new tests only assert the textual shape of the command, never the round trip.

// inner double quotes; any double-quoted span containing a space then breaks apart
// into argv separators and the in-container shell sees a syntax error (#3262).
assertNoDoubleQuotedSpanWithSpace(writeCmd);
assertNoDoubleQuotedSpanWithSpace(moveCmd);

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.

assertNoDoubleQuotedSpanWithSpace(moveCmd) can never fail for move(): the pre-change command was mkdir -p $(dirname X) && mv ..., which contains no double quote at all, so this assertion passes both before and after the fix and gives the move() half of the change no regression coverage. The move bug being fixed is behavioral - the unquoted $(dirname 'dir with space/b.txt') word-splits, so mkdir -p silently creates dir, with and space in the CWD and the following mv fails. Please add a behavioral assertion using the existing LocalShellSandboxFilesystem nested class (Linux-only) under @TempDir: move a file to dir with space/b.txt and assert success plus Files.exists(...); for write() that fixture returns no upload response, so assert the side effect instead (fs.write(RT, tmp + '/dir with space/f.txt', ...) followed by Files.isDirectory(...) on the parent). Note also that the helper pairs quotes positionally, so it mis-pairs on commands containing nested or embedded quoted spans (e.g. edit()'s python3 -c program) and should not be treated as a general guard.

+ " "
+ escapedTo;
ExecuteResponse result = execute(runtimeContext, cmd, null);
if (result.exitCode() != 0) {

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.

result.exitCode() != 0 auto-unboxes a nullable Integer: ExecuteResponse explicitly permits a null exit code (isSuccess() checks for it, and this very test file already exercises new ExecuteResponse("unknown state", null, false) for ls/read). An execution layer that reports an unknown exit code therefore NPEs here, before clampDetail's null handling can run - the same failure path this PR sets out to make null-safe. Use !result.isSuccess() or the existing executeFailureMessage(result, "moving", toPath) instead; delete() has the identical unboxing at line 435. The new move_failureMessageHandlesNullOutput test passes exit code 124 (non-null), so it does not cover this case.

+ "' to '"
+ toPath
+ "': "
+ clampDetail(result.output()));

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.

move() routes the detail through clampDetail unconditionally, so a null output collapses to the literal no output and the exit code - the only diagnostic for the timeout case (124) - is dropped, whereas write() falls back to exit code <n>. Make the two failure messages consistent (fall back to the exit code when the output is null or blank) and tighten move_failureMessageHandlesNullOutput, which only asserts error().length() > 0 and therefore cannot detect a message-content regression.

@Override
public WriteResult write(RuntimeContext runtimeContext, String filePath, String content) {
String escapedPath = FilesystemUtils.shellQuote(filePath);
// No double-quoted span may contain a space: on a Windows host the argv →

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.

The comment states a class-wide invariant (No double-quoted span may contain a space), but edit() further down the same file still builds python3 -c "<program containing spaces and newlines>" - the second construct #3262 blames for edit_file failing on Windows hosts, deliberately deferred here to #3084/#3226. Please note that deferral in the comment or as a TODO so the new rule is not mistaken for full coverage of the class.

String stripped = output.strip();
return stripped.length() <= MAX_DETAIL_CHARS
? stripped
: stripped.substring(0, MAX_DETAIL_CHARS) + "... [output truncated]";

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.

stripped.substring(0, MAX_DETAIL_CHARS) can cut a surrogate pair, leaving a lone surrogate in the model-facing tool result (and an unpaired surrogate in the JSON sent downstream). Truncate on a code-point boundary instead, e.g. stripped.substring(0, stripped.offsetByCodePoints(0, Math.min(stripped.codePointCount(0, stripped.length()), MAX_DETAIL_CHARS))).

@oss-maintainer oss-maintainer 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.

Summary

Re-review after the latest merge. The previously raised items are addressed: move() now uses the same quote-free d=$(dirname ...); mkdir -p "$d" idiom, the failure message surfaces the container output, clampDetail is null-safe, and the command scanner covers both write() and move() commands with dedicated tests (null output, blank output, huge output, syntax-error passthrough). CI is green on ubuntu and windows, CLA signed.

Two leftovers inline (neither blocking a merge on correctness grounds): the write()/move() null-output fallback asymmetry (different error strings, exit code lost in the move() blank-output case) and head- vs tail-truncation of the clamped detail.


Automated review by github-manager-bot

return WriteResult.fail("Failed to write file '" + filePath + "'");
String detail =
checkResult.output() != null && !checkResult.output().isBlank()
? clampDetail(checkResult.output())

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.

[Warning] The null/blank handling asymmetry from the previous review is still there: write() falls back to "exit code <n>" when output is null or blank, while move() routes everything through clampDetail(), which turns a null output into "no output" and silently drops the exit code (move() also does not show it). Same root cause, two different tool-result strings, and in the blank-output case move() loses the exit code entirely. Suggest one shared detailOrExitCode(ExecuteResponse) helper used by both failure paths.

if (output == null) {
return "no output";
}
String stripped = output.strip();

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.

[Info] Truncation keeps the head of the output. For shell failures the interesting part (the actual error line) is usually at the end, so a long noisy output truncated at 500 chars will often keep the useless prefix and drop the cause. Consider keeping the tail (or head+tail), e.g. "[output truncated] " + last 500 chars, so the surfaced detail matches what the previous review asked for (diagnosability).

@oss-maintainer

Copy link
Copy Markdown
Collaborator

Review summary (accompanies my inline review comments: #3269 (review))

Summary

Re-review after the latest merge. The previously raised items are addressed: move() now uses the same quote-free d=$(dirname ...); mkdir -p "$d" idiom, the failure message surfaces the container output, clampDetail is null-safe, and the command scanner covers both write() and move() commands with dedicated tests (null output, blank output, huge output, syntax-error passthrough). CI is green on ubuntu and windows, CLA signed.

Two leftovers inline (neither blocking a merge on correctness grounds): the write()/move() null-output fallback asymmetry (different error strings, exit code lost in the move() blank-output case) and head- vs tail-truncation of the clamped detail.


Automated review by github-manager-bot

aMetric added a commit to aMetric/agentscope-java that referenced this pull request Sep 28, 2026
…ate clamped detail (agentscope-ai#3262)

Review follow-up on agentscope-ai#3269:

- move() now uses the same null/blank-output fallback as write():
  exit-code fallback when output is null/blank, and a null-exitCode
  guard (result.exitCode() != null && ... != 0) matching the safety
  write()'s pre-check path already has
- clampDetail() switches from head-truncation to tail-truncation
  ([output truncated] ...<tail>) so the most useful diagnostic content
  (usually at the end) is preserved
- test: move_failureMessageHandlesNullOutput now asserts the exit code
  is in the message, symmetric with write_failureMessageHandlesNullOutput

@oss-maintainer oss-maintainer 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.

Summary

Re-review after 0d3f81c47b. Both points from my previous round are addressed correctly: move() now mirrors write()'s output-or-exit-code fallback, and clampDetail() keeps the tail of the output, which is where the actual shell error line lives. Nice.

Two things worth a follow-up before this is ready, both in the code the new commit just touched:

  • [Warning] BaseSandboxFilesystem.java:458 — the new exitCode() != null && guard makes an unknown exit code fall through to WriteResult.ok(), i.e. move() reports success for a move it could not confirm. write() survives the same shape only because uploadFiles() still reports the error afterwards; move() has no back-stop. Failing closed (or at least pinning the null case with a test) keeps the contract honest.
  • [Info] BaseSandboxFilesystem.java:553 — tail truncation still slices on UTF-16 code units, so the retained detail can begin with a lone surrogate (carry-over from the earlier truncation thread, now on the other end of the string).
  • [Info] BaseSandboxFilesystemTest.java:328 — the huge-output test uses a uniform payload, so it cannot tell head- from tail-truncation; add a distinguishable tail to lock in the new behavior.

No blocker on the original #3262 fix itself — the quote-free-spread construction for write()/move() and the error surfacing look right, and the double-quoted-span scanner is a good guard. Commenting rather than approving only because of the silent-success path above; once that is settled this looks good to go, and CI still needs a maintainer approval run (mergeStateStatus=BLOCKED).


Automated review by github-manager-bot

+ escapedTo;
ExecuteResponse result = execute(runtimeContext, cmd, null);
if (result.exitCode() != 0) {
if (result.exitCode() != null && result.exitCode() != 0) {

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.

Good catch on the null deref from the last round, but the guard now flips the failure mode: when result.exitCode() is null the condition is false and move() returns WriteResult.ok(toPath) — a move whose exit status is unknown gets reported to the model as a success. write() has the same shape, but there the fall-through still runs uploadFiles(), which reports the real error; move() has no such back-stop.

ExecuteResponse.isSuccess() already defends against a null exit code, and the tests here construct one, so the API does permit it. Suggest failing closed instead of silently succeeding:

Integer exitCode = result.exitCode();
if (exitCode == null || exitCode != 0) {
    String detail =
            result.output() != null && !result.output().isBlank()
                    ? clampDetail(result.output())
                    : "exit code " + exitCode;
    return WriteResult.fail("Error moving '" + fromPath + "' to '" + toPath + "': " + detail);
}

If you keep the current semantics, please add a new ExecuteResponse("...", null, false) case to move_... so the intended behavior for an unknown exit code is at least pinned by a test (right now the null-exit-code branch is the one path neither the code nor the tests describe).

String stripped = output.strip();
return stripped.length() <= MAX_DETAIL_CHARS
? stripped
: "[output truncated] ..." + stripped.substring(stripped.length() - MAX_DETAIL_CHARS);

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.

Keeping the tail is the right call for shell errors. One leftover from the earlier truncation note: stripped.substring(stripped.length() - MAX_DETAIL_CHARS) still counts UTF-16 code units, so when the cut lands between a surrogate pair the retained detail starts with a lone surrogate, which then gets serialized into the tool-result JSON. A code-point-safe cut is cheap here:

int from = stripped.length() - MAX_DETAIL_CHARS;
if (Character.isLowSurrogate(stripped.charAt(from))) {
    from++;
}
return "[output truncated] ..." + stripped.substring(from);


@Test
void write_failureMessageClampsHugeOutput() {
String huge = "x".repeat(50_000);

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.

This test would pass with the old head-truncation too: "x".repeat(50_000) is uniform, and the assertions only check the length bound and the marker. Mixing in a distinguishable tail makes it actually guard the behavior you just changed, e.g.

String huge = "x".repeat(50_000) + "LASTLINE";
...
assertTrue(result.error().contains("LASTLINE"), "clamped detail should keep the tail: " + result.error());
assertFalse(result.error().contains("xxxx"), "head should be dropped");

@oss-maintainer

oss-maintainer commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

One more thing, this time from CI rather than the code: build (ubuntu-latest) fails on 0d3f81c47b, and it is a formatting check on the file this PR touches, not a test failure:

[ERROR] Failed to execute goal com.diffplug.spotless:spotless-maven-plugin:3.4.0:check on project agentscope-harness:
        The following files had format violations:
            src/main/java/io/agentscope/harness/agent/filesystem/sandbox/BaseSandboxFilesystem.java
            @@ -461,12 +461,7 @@  ... clampDetail(result.output()) : "exit code " + result.exitCode();
                                    return WriteResult.fail("Error moving '" + fromPath + ... );

Spotless wants the new move() failure message collapsed back onto fewer lines, so mvn -pl agentscope-harness spotless:apply (then commit) should turn the build green. build (windows-latest) shows CANCELLED because it was skipped once agentscope-harness failed, and Core / AG-UI pass, so nothing here points at your logic.

Full log: https://github.com/agentscope-ai/agentscope-java/actions/runs/36410469581

Correction to my review summary above: the workflows have already run on this head — the blocker is this Spotless violation plus a still-required approving review, not a held first-time-contributor approval.


Automated review by github-manager-bot

@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR currently conflicts with main and cannot be merged. Please rebase (or merge main into fix/sandbox-write-quoting-and-error) and resolve the conflicts:

git fetch origin
git checkout fix/sandbox-write-quoting-and-error
git rebase origin/main
# resolve conflicts, then:
git push --force-with-lease

Once main is back in sync, @mention me for a re-review if you would like one. This is a one-time reminder.


Automated notification by github-manager-bot

aMetric added a commit to aMetric/agentscope-java that referenced this pull request Sep 29, 2026
…ror output (agentscope-ai#3262)

Review follow-up on agentscope-ai#3269:

- move(): 'mkdir -p $(dirname <to>)' left the substitution unquoted, so a
  parent path with a space word-split (mkdir -p a b creates junk dirs);
  now uses the same d=$(dirname <to>); mkdir -p "$d" idiom as write(),
  keeping the no-double-quoted-span-with-space invariant
- the failure detail surfaced by write() (and now move()) is clamped to
  500 chars via clampDetail — the raw execute() output was passed through
  unbounded into a tool result the model sees
- the double-quoted-span scanner test now also covers move()'s command;
  new test asserts huge command output is clamped with a note
aMetric added a commit to aMetric/agentscope-java that referenced this pull request Sep 29, 2026
…agentscope-ai#3262)

Review follow-up on agentscope-ai#3269:

- clampDetail() now handles null output inside the helper: move() passes
  result.output() unguarded and the execution layer can produce null
  (ExecTimeoutException via a null Throwable.getMessage()) — that path
  would have thrown an NPE out of the filesystem API
- the double-quoted-span scanner asserts on BOTH the write() and move()
  commands (previously the move() call overwrote lastCommand, so a
  regression in write()'s builder would still pass)
- new tests: write/move failure paths with null output (exit-code
  fallback, no NPE)
aMetric added a commit to aMetric/agentscope-java that referenced this pull request Sep 29, 2026
…ate clamped detail (agentscope-ai#3262)

Review follow-up on agentscope-ai#3269:

- move() now uses the same null/blank-output fallback as write():
  exit-code fallback when output is null/blank, and a null-exitCode
  guard (result.exitCode() != null && ... != 0) matching the safety
  write()'s pre-check path already has
- clampDetail() switches from head-truncation to tail-truncation
  ([output truncated] ...<tail>) so the most useful diagnostic content
  (usually at the end) is preserved
- test: move_failureMessageHandlesNullOutput now asserts the exit code
  is in the message, symmetric with write_failureMessageHandlesNullOutput
@aMetric
aMetric force-pushed the fix/sandbox-write-quoting-and-error branch from 80a2007 to d5bede1 Compare September 29, 2026 01:13

@oss-maintainer oss-maintainer 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.

Summary

Rebase of the #3262 quoted-space fix onto current main, plus surfaced failure details and a 500-char clamp on raw command output. The shell idiom (d=$(dirname ...); mkdir -p "$d") avoids the Windows docker.exe re-parse problem cleanly, the clamp is null-safe and keeps the diagnostic tail, and the new failure-message tests cover null / blank / huge output. Not mergeable yet: the test file does not compile, and spotless:check is red on both OS builders.

Findings

  • [Critical] BaseSandboxFilesystemTest.java:423 — a stray } closes the outer test class early; brace balance goes from 0 at 0d3f81c4 to -1 here, and a syntax-only javac rejects the file. spotless:check aborts before test compilation, so CI has not surfaced it yet.
  • [Warning] BaseSandboxFilesystem.java:468 — the added null guard makes move() report WriteResult.ok() for an unknown exit status, while delete() (line 445) still unboxes unguarded.
  • [Warning] BaseSandboxFilesystem.java:474 — google-java-format violation, the direct cause of the red build (ubuntu-latest) / build (windows-latest).
  • [Warning] BaseSandboxFilesystemTest.java:271 — unrelated de-indent of the #2571 section comment.
  • [Info] BaseSandboxFilesystem.java:564 — the clamp covers only write()/move(); read()/edit()/glob()/grep()/delete() still interpolate unbounded output.

Suggestions

  1. Delete the brace at line 423 and restore the indentation on line 271.
  2. mvn spotless:apply -pl agentscope-harness, re-push, and confirm both builders now compile the tests — that is the run that will show finding 1 was real.
  3. Pick one null-exit-code contract for this class and apply it to move() and delete() together; for a filesystem mutation, "unknown" should read as a failure rather than as success.

The fix itself is sound and the test coverage you added around it is thorough — the blockers here are a rebase artifact and a format run.


Automated review by github-manager-bot

result.error().contains("3"),
"failure message should fall back to the exit code: " + result.error());
}
}

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.

Stray } — this test file no longer compiles. Line 422 already closes write_failureMessageFallsBackToExitCodeWhenOutputBlank(), so this brace closes CannedResponseTests and the next line ( }, 424) closes BaseSandboxFilesystemTest itself. Everything after it — LocalShellIntegrationTests, FakeSandboxFilesystem, FixedResponseFilesystem, LocalShellSandboxFilesystem — is then parsed as top-level types, which makes private static final class FakeSandboxFilesystem an illegal top-level modifier and leaves one unmatched } at EOF. Brace balance is 0 at main and at the previously reviewed 0d3f81c4, but -1 here; a syntax-only javac on the file ends with error: class, interface, enum, or record expected on the last line. spotless:check aborts the build before test compilation, so CI has not surfaced this yet — it will appear as soon as the format violation is fixed. Deleting this brace should ship in the same push as the spotless fix.

}

// ==================== Bug reproduction: edit python program collapsed into one line
// ==================== Bug reproduction: edit python program collapsed into one line

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.

Unrelated formatting damage: this #2571 section comment lost its 8-space indent (the continuation on 272 still has it). Please restore it so the diff stays scoped to the #3262 change.

+ escapedTo;
ExecuteResponse result = execute(runtimeContext, cmd, null);
if (result.exitCode() != 0) {
if (result.exitCode() != null && result.exitCode() != 0) {

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.

Adding the null guard changes behaviour, not just robustness: when result.exitCode() == null the condition is false, so move() now returns WriteResult.ok(toPath) for an unknown exit status instead of throwing on the unboxing. For a move that is the worst direction to fail — the model is told the file moved when mv may never have run. The clampDetail javadoc says a null output is a real case (timeout via a null Throwable.getMessage()), so null status should be a failure here:

Integer code = result.exitCode();
if (code == null || code != 0) {
    String detail = code == null ? "no exit status reported"
            : (result.output() != null && !result.output().isBlank()
                    ? clampDetail(result.output()) : "exit code " + code);
    return WriteResult.fail("Error moving '" + fromPath + "' to '" + toPath + "': " + detail);
}

Whatever contract you pick, delete() (line 445) still does an unguarded result.exitCode() != 0 and interpolates result.output() unbounded, so the class is inconsistent on both counts.

: "exit code " + result.exitCode();
return WriteResult.fail(
"Error moving '" + fromPath + "' to '" + toPath + "': " + result.output());
"Error moving '"

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.

spotless:check fails on this statement — google-java-format wants the concatenation on one line. CI evidence: [ERROR] Failed to execute goal com.diffplug.spotless:spotless-maven-plugin:3.4.0:check (default) on project agentscope-harness: The following files had format violations: src/main/java/.../BaseSandboxFilesystem.java @@ -471,12 +471,7 @@, which is what turns build (ubuntu-latest) and build (windows-latest) red. mvn spotless:apply -pl agentscope-harness should clear it — and that will also let the test compile surface the brace problem above.

return stripped.length() <= MAX_DETAIL_CHARS
? stripped
: "[output truncated] ..."
+ stripped.substring(stripped.length() - MAX_DETAIL_CHARS);

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.

clampDetail is the right shape: null-safe, keeps the tail (where shell diagnostics actually land), tight local bound, and the MAX_DETAIL_CHARS javadoc explains why 500. Two non-blocking notes: (a) the clamp covers only write()/move() — read(), edit(), glob(), grep() and delete() still interpolate result.output() unbounded, so the context guarantee is per-method rather than per-filesystem; folding it into execute() (or into the ExecuteResponse consumer) would make it uniform. (b) The marker sits before the tail ("[output truncated] ... " + tail), so a reader cannot tell how much was dropped — "… <N> chars omitted …" would be easier to diagnose.

@aMetric

aMetric commented Oct 15, 2026

Copy link
Copy Markdown
Contributor Author

@oss-maintainer re-review requested — the findings from your 09-29 review are resolved on the current head a28898e:

  • Stray closing brace in BaseSandboxFilesystemTest.java removed; the test file compiles again.
  • spotless:check is green — both build (ubuntu-latest) and build (windows-latest) pass, and they gate on the format check before tests run.
  • c06c433 also lands the follow-ups: fail-closed move()/delete() for an unknown exit code (no more silent success on a null status) and surrogate-pair-safe tail truncation in clampDetail.

All checks are green on this head, and the branch is mergeable with main.

@aMetric

aMetric commented Oct 24, 2026

Copy link
Copy Markdown
Contributor Author

@oss-maintainer Friendly follow-up on my comment above (Oct 15) — the findings from your 09-29 review are all resolved on the current head (a28898e): the stray brace and formatting are fixed, move()/delete() now fail closed on unknown exit codes, and the tail clamp is surrogate-safe. CI is green on both ubuntu and windows. Could you take another look when you have a chance? Happy to address anything else.

@aMetric
aMetric force-pushed the fix/sandbox-write-quoting-and-error branch from a28898e to eeb8eba Compare November 2, 2026 01:52
…wn exit codes

The quoted-space command fix for agentscope-ai#3262 / agentscope-ai#3850 is already on `main` (agentscope-ai#3871), so this
branch now carries only the half that is still missing: what the model is told when a
sandbox filesystem mutation fails.

- `write()`, `move()` and `delete()` now append the sandbox's own diagnostic to the
  failure message. Before this, `write()` returned a bare `Failed to write file '<path>'`
  and `move()`/`delete()` embedded the raw stdout/stderr verbatim.
- Raw output is clamped to 500 chars keeping the tail, where shells put the actual error
  line after a command's preamble. The cut backs off one char when it lands on a low
  surrogate so the JSON sent to the model never carries a lone surrogate.
- Mutations fail closed when `execute()` reports no exit status. `exitCode()` is an
  `Integer`, so the previous `result.exitCode() != 0` unboxed a null and threw NPE in
  `move()`/`delete()`, while `write()` treated a null status as success and went on to
  upload.
- `executeFailureMessage()` shares the same detail path, so `ls`/`read`/`edit`/`grep`/
  `glob` inherit the clamp and the explicit `no exit status reported` wording.

Tests: 7 new cases in `BaseSandboxFilesystemTest` (detail carried, clamp, null output,
null exit code for write/move/delete) plus a regression guard asserting no double-quoted
span containing a space is ever generated for `write()` or `move()`. Full
`agentscope-harness` suite: 1601 tests, 0 failures, 37 skipped (Linux/Docker-only).
@aMetric
aMetric force-pushed the fix/sandbox-write-quoting-and-error branch from eeb8eba to 04f30f5 Compare November 2, 2026 02:06
@aMetric

aMetric commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main and re-scoped — this is no longer a duplicate of #3871.

While this branch sat, e190a8d1b (#3871, fixes #3850) landed the part-a quoting fix: write() and move() now compute the parent directory in Java and pass it to mkdir -p as a single-quoted literal. I kept that version of the command construction and dropped my own d=$(dirname ...) idiom rather than fight it. The PR body is updated to match.

What is left is part d of #3262, plus two related gaps the rebase made obvious:

  • write() discarded checkResult.output() and returned a bare Failed to write file '<path>'. It now carries the sandbox's own diagnostic, clamped to 500 chars keeping the tail (that is where the shell puts the error line), surrogate-safe at the cut.
  • ExecuteResponse.exitCode() is an Integer. On main today, move() and delete() do if (result.exitCode() != 0) — that unboxes a null and throws NPE when the execution layer reports no status. write() gets the null treatment wrong in the other direction: it reads as success and falls through to the upload. All three now fail closed with no exit status reported.
  • executeFailureMessage() delegates to the same failureDetail() helper, so ls/read/edit/grep/glob inherit the clamp and the null-status wording.

9 canned-response tests cover this (detail carried, 50K clamp, null output, null exit code × write/move/delete, blank-output fallback, and a guard that no generated write()/move() command contains a double-quoted span with a space). mvn -pl agentscope-harness test: 1601 tests, 0 failures, 37 skipped. CI on head 04f30f531: all lanes green, MERGEABLE, and the spotless/compile findings from your 09-29 review are gone.

The only thing still blocking is that 09-29 CHANGES_REQUESTED — could you re-review so it can clear?

@jujn jujn added the P1 紧急不重要 label Nov 4, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P1 紧急不重要

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants