Skip to content

fix(harness): contain CompositeFilesystem root ls/grep to the backend root (stacked on #3247) - #3254

Open
aiyili wants to merge 4 commits into
agentscope-ai:mainfrom
aiyili:fix/root-containment
Open

aiyili wants to merge 4 commits into
agentscope-ai:mainfrom
aiyili:fix/root-containment

Conversation

@aiyili

@aiyili aiyili commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #3253

Rebased onto current main as a single commit now that #3247 has merged — the diff below is only the containment change.

Problem

CompositeFilesystem routes root-level operations to the default backend with an absolute "/" path — ls (both "." and "/") and grep (the "/" case) — and the UNRESTRICTED resolver passes absolute paths through unchanged, so the operation anchors at the OS root: list_files(".") enumerates the drive root (#3253). glob is unaffected (already anchored).

Fix

A shared rootAnchor(path) helper normalizes {null, "/", "."} to the namespace-aware "." — mirroring the normalization LocalFilesystem.glob already applies:

  • a namespaced default backend anchors at {workspace}/{userId} — tenant isolation preserved (a blank anchor would bypass the per-user prefix and list every tenant's directory)
  • a shared-mode backend (null namespace factory) anchors at its own root

ls and grep share the helper, so all root spellings walk the same tree.

Tests

  • rootListingAndGrepAnchorAtTheCallersNamespace — sibling tenant directory (other-user/) never appears in the root listing; the caller's own tree stays visible; grep with ".", "/" and null all walk the same tree
  • sharedModeRootListingStaysInsideTheWorkspace — shared root view with an outside-the-workspace marker file that must never appear

Module suite matches upstream baseline (only the two known Windows symlink-privilege errors). The arbitrary-absolute-path gap (read/write/edit through the same backend) is tracked separately as #3258.

@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

Good catch on the containment hole, and the namespace-bypass reasoning in the comments is right: "/" does reach the UNRESTRICTED resolver unchanged. The concern is the chosen anchor — "" is also unprefixed (applyNamespacePrefix early-returns on blank keys), so in the default namespaced mode the root listing now walks the whole workspace root instead of {workspace}/{userId}, which trades an OS-root escape for a cross-tenant one. LocalFilesystem.glob already has the namespace-aware form of this normalisation (hasNamespace(rc) ? resolvePath(rc, ".") : cwd); mirroring "." here keeps both modes contained without a new convention.

The second point is consistency: ls normalises "/" and "." to "" while grep only rewrites "/", so grep(".") / grep(null) still resolve through the namespace and land on a different tree than ls("."). One shared normaliser for {null, "/", "."} across ls / grep / glob would close that.

Non-blocking: the PR only anchors the exact root spellings — arbitrary absolute paths (read_file("/etc/passwd"), list_files("/tmp")) still pass through the UNRESTRICTED default backend unchanged. That is pre-existing and out of scope for #3253, but it is the same threat model, so it is worth a follow-up issue (a ROOTED/SANDBOXED default backend for remote specs, like the shared-mode branch in #3247).

Findings

  • [Warning] CompositeFilesystem.java:204 — "" bypasses the per-user namespace too; prefer "." (namespace-aware) or gate the workspace-root view behind an opt-in.
  • [Warning] CompositeFilesystem.java:285-289 — ls/grep disagree on what the root is; grep(".") and grep(null) keep the old namespaced anchor.
  • [Info] CompositeFilesystem.java:203 — absolute-path pass-through on the UNRESTRICTED default backend is unaddressed (pre-existing, suggest follow-up issue).
  • [Info] RemoteFilesystemSpecTest.java:184-206 — whitelist assertion locks in the namespace bypass and will break when a new shared route is added; a sibling-tenant-absent assertion would pin the isolation contract instead.

Tests: two new/extended test classes covering both specs and both modes — appreciated. The LocalFilesystemSpec shared-mode javadoc explicitly documents the multi-tenant unsafety, which is the right pattern; the CompositeFilesystem root change needs the same level of intent stated (or the "." anchor).


Automated review by github-manager-bot

// A blank path anchors the default backend at its own root (LocalFilesystem's
// resolvePath resolves blank keys to the backend cwd, unprefixed); "/" would pass
// through the UNRESTRICTED resolver unchanged and enumerate the OS root (#3253).
LsResult defaultResult = defaultBackend.ls(runtimeContext, "");

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.

Anchoring the default backend at "" does close the OS-root escape, but for a namespaced default backend it also drops the namespace: LocalFilesystem.applyNamespacePrefix early-returns for blank keys (key == null || key.isBlank() -> return key), so resolvePath(rc, "") lands on cwd (the raw workspace root) instead of {workspace}/{userId}. Net effect for RemoteFilesystemSpec in its default (non-shared, namespaced) mode: list_files(".") enumerates every tenant's namespace directory (local-user/, other-user/, ...), while read_file("x") still resolves inside the caller's own namespace. That weakens tenant isolation for existing users by default, and rootListingAndGrepStayInsideTheWorkspace below bakes it in (the whitelist has no local-user entry, so the test asserts the bypass).

Suggest anchoring on the backend's own logical root the way LocalFilesystem.glob already does, i.e. namespace-aware:

// "." keeps the namespace prefix (applyNamespacePrefix -> "<ns>/."), "" does not
LsResult defaultResult = defaultBackend.ls(runtimeContext, ".");

With a namespaced UNRESTRICTED backend "." resolves to {workspace}/{userId}; with the shared-mode backend (namespace factory is null) it resolves to cwd, so both modes get a contained root and the multi-tenant default is preserved. If exposing the workspace root at "." in namespaced mode is actually intended, it deserves its own opt-in (like sharedLocalWorkspace) plus a test asserting what a non-shared root listing may and may not see.

Comment on lines +285 to +289
// Same containment anchor as the ls root branch above: "/" must not reach the
// default backend, whose UNRESTRICTED resolver would scan from the OS root (#3253).
String defaultBackendPath = "/".equals(path) ? "" : path;
GrepResult defaultResult =
defaultBackend.grep(runtimeContext, pattern, defaultBackendPath, glob);

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 grep branch only rewrites "/", so after this change ls and grep disagree, and grep disagrees with itself:

call root reached
ls("/") / ls(".") "" -> default backend cwd (workspace root, namespace bypassed)
grep("/…") "" -> cwd (workspace root)
grep(".") "." -> <ns>/. -> {workspace}/{userId}
grep(null) null -> <ns>/. -> {workspace}/{userId}

So the same logical query (list_files(".") vs grep_files(".", …), or pattern with path=null vs path="/") walks two different trees, and the "." case is exactly the one a client gets when the tool layer normalises an empty path. Please normalise null, "/" and "." to one shared constant for both ls and grep (and keep it consistent with the already-correct glob handling) instead of a per-literal ternary — one small helper (e.g. rootAnchor(path)) would also keep the two comment blocks in sync.

LsResult defaultResult = defaultBackend.ls(runtimeContext, "/");
// A blank path anchors the default backend at its own root (LocalFilesystem's
// resolvePath resolves blank keys to the backend cwd, unprefixed); "/" would pass
// through the UNRESTRICTED resolver unchanged and enumerate the OS root (#3253).

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.

Scope note: the literal "/" is fixed here, but the UNRESTRICTED default backend in RemoteFilesystemSpec still passes any absolute path straight through (resolveUnrestricted: if (target.isAbsolute()) return target;), so list_files("/etc") / read_file("/home/other/.aws/credentials") reach the host filesystem exactly as before — and the root branch only fires for the exact strings "/" and ".". This is pre-existing and arguably out of scope for #3253, but since this PR is the containment fix for that area, it is worth a follow-up issue: a remote-spec default backend probably wants SANDBOXED/ROOTED resolution (like the shared-mode branch added in #3247) rather than UNRESTRICTED, otherwise "contain to the backend root" only holds for one spelling of the root.

Comment on lines +184 to +206
Set<String> allowedTopSegments =
new HashSet<>(
List.of(
"uploads",
"memory",
"skills",
"subagents",
"knowledge",
"plans",
"agents"));
for (String root : new String[] {".", "/"}) {
LsResult ls = fs.ls(RT, root);
assertTrue(ls.isSuccess(), () -> "root listing '" + root + "': " + ls.error());
for (FileInfo fi : ls.entries()) {
String top = fi.path().split("/")[0];
assertTrue(
allowedTopSegments.contains(top),
"listing entry escaped the workspace: " + fi.path());
}
}
assertTrue(
fs.ls(RT, ".").entries().stream().anyMatch(fi -> fi.path().startsWith("uploads")),
"workspace content must remain visible in the root listing");

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 whitelist-based assertion is a good containment check, but it couples the test to whatever happens to sit at the workspace root, and it never asserts the namespace expectation for the default (non-shared) mode — i.e. that a second tenant's directory is not listed. Consider (a) creating a sibling {workspace}/other-user/secret.md in the test and asserting it is absent from ls("."), which pins the isolation question raised on the ls hunk either way, and (b) replacing the hardcoded allowed-segment set with a startsWith(workspace.getFileName())-style containment check on the resolved path, so a future shared route (e.g. knowledge-v2/) does not fail the suite for the wrong reason.

@codecov

codecov Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

aiyili added a commit to aiyili/agentscope-java that referenced this pull request Sep 22, 2026
Codecov 对 PR agentscope-ai#3254 报 1 行 partial:defaultBackendPath 三元式的
"/"→"" 臂已有 grep("/") 测试,": path"("."/null 直通)臂没有触发。
在 rootListingAndGrepStayInsideTheWorkspace 中补充:经框架写入
notes/second.md 后 grep(".") 命中——同时钉住 "." 路径保持既有
命名空间扫描语义不变。
@aiyili

aiyili commented Sep 22, 2026

Copy link
Copy Markdown
Contributor Author

Added the missing branch: the "."-path passthrough arm of the grep ternary is now covered in rootListingAndGrepStayInsideTheWorkspace (write notes/second.md through the framework, then grep(".") finds it — also pinning that "." keeps its namespaced-scan semantics). Module suite 1057/1057 green.

@aiyili

aiyili commented Sep 22, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the sharp review — the namespace-bypass point is exactly right, reworked in c04290c:

  1. Anchor switched from "" to "." — namespace-aware, mirroring LocalFilesystem.glob's existing normalization: namespaced default backends now anchor at {workspace}/{userId} (tenant isolation preserved — the cross-tenant escape is gone), shared-mode backends at their own root.
  2. One shared normalizer — new rootAnchor(path) helper maps {null, "/", "."} to ".", used by both ls and grep, with a single javadoc keeping the reasoning in one place. ls(".") and grep(".")/grep(null)/grep("/") now walk the same tree.
  3. Tests rewritten per the suggestions — the default-mode test now creates a sibling tenant ({workspace}/other-user/secret.md) and asserts it never appears in the root listing (pins tenant isolation either way), asserts the caller's own tree stays visible, and checks all three root spellings grep the same tree; the hardcoded whitelist is gone. The shared-mode test adds an outside-the-workspace marker file that must never appear.
  4. Follow-up issue filed for the absolute-path passthrough: [Bug] Remote-spec UNRESTRICTED default backend passes arbitrary absolute paths through (read_file("/etc/passwd") reaches the host) #3258 (remote-spec default backend should likely be SANDBOXED/ROOTED, with the default-behavior impact left for maintainers).

Module suite 1057/1057 green.

@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 follow-up push (8e181706 → c04290c1). Switching the root anchor from "" to "." fixes the flaw raised last time: a blank key makes applyNamespacePrefix early-return, which traded the OS-root escape for a cross-tenant one. The rewritten tests are the right shape — asserting other-user/ does not leak into the root listing is exactly the property that matters here, and dropping the hard-coded shared-route whitelist in favor of behavioral assertions is an improvement. Not approving, because the "." anchor is a LocalFilesystem convention being applied at a backend-agnostic seam, and glob now disagrees with ls/grep.

Correctness — verified against the resolver: resolvePath(rc, ".") → applyNamespacePrefix prepends the namespace ("." is neither blank nor absolute per isAbsolutePathString), so a namespaced backend anchors at {workspace}/{userId} and a namespace-free one at its own cwd. The containment claim holds for the LocalFilesystem default backend, and the description's "shared mode anchors at the backend's own root" is accurate.

Compatibility (main concern) — rootAnchor is applied to defaultBackend, which is typed AbstractFilesystem and documented as taking a path starting with /. Two real callers install a non-local default: RoutedSandboxFilesystem:49 (primary is an AbstractSandboxFilesystem), whose ls/grep are shell-generated (for f in <path>/*, grep -r … <path>), so "." is expanded against the command cwd and entries come back as ./name instead of /name. That is a user-visible change in listing shape for sandbox-routed agents, and no test here covers a non-local backend. If that path is unreachable in practice, a comment saying so is enough; otherwise the normalization belongs in LocalFilesystem, or gated by backend type.

Consistency — glob's root branch still forwards the raw "/"/null and relies on LocalFilesystem.glob normalizing internally, and route backends keep receiving "/". So there is no longer one definition of "composite root" across the three scanning operations — the same class of drift that produced #3253.

Tests — good on namespaced/shared local modes. Missing: a non-LocalFilesystem default backend, and an equivalence assertion that "/", "." and null produce identical listings (containment is checked, cross-spelling equality is not).

Nits — the : path fallback in rootAnchor is unreachable from both call sites (both already tested null/"/"/"." before calling it), so the Codecov partial that motivated the follow-up commit will remain partial; and the PR description still documents the superseded "" anchor ("Pass a blank path instead of \"/\"", resolvePath blank→cwd), which will mislead anyone bisecting this file.

Findings

  • [Warning] CompositeFilesystem.java:528 — "." is a LocalFilesystem convention applied at a backend-agnostic seam; sandbox default backends shell-expand it to ./name and the AbstractFilesystem javadoc mandates /-rooted paths.
  • [Warning] CompositeFilesystem.java:201 — glob still forwards raw "/"/null; the three root-scanning operations now have two different normalization owners.
  • [Info] CompositeFilesystem.java:520-528 — unreachable ternary fallback; a constant (or calling rootAnchor before the root branch) would be clearer and actually resolves the coverage partial.

Automated review by github-manager-bot

Additional notes (not anchored to a changed line)

  • [INFO] agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/CompositeFilesystem.java:520 — The : path fallback arm looks unreachable from both call sites — ls calls rootAnchor only inside "/".equals(path) || ".".equals(path) and grep only inside path == null || "/".equals(path) || ".".equals(path), so it always returns ".". That also means the Codecov partial that motivated the follow-up test will stay partial: grep(".") takes the true arm, not the fallback. If the fallback is not meant to be reachable, a constant (ROOT_ANCHOR = ".", or a no-arg helper) is clearer and fully covered; if it is, rootAnchor should be called before the root branch rather than inside it. (multi-line range invalid, anchoring single line)

* namespace-free one (shared mode) at its own root — mirroring the normalization {@code
* LocalFilesystem.glob} already applies (#3253).
*/
private static String rootAnchor(String path) {

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.

"." is only a root anchor for LocalFilesystem. The composite is backend-agnostic, and two of its callers install a non-local default backend:

  • RoutedSandboxFilesystem:49 → new CompositeFilesystem(primary, routes) with primary an AbstractSandboxFilesystem; BaseSandboxFilesystem.ls builds for f in <path>/* and grep builds grep -r … <path>, so "." is expanded by the shell against the command cwd (entries come back as ./name, not /name), while "/" enumerated the sandbox root.
  • RemoteFilesystemSpec:250/HarnessAgent:2485 also pass through whatever the caller resolved.

AbstractFilesystem.ls documents @param path absolute path to the directory to list (must start with '/') (same wording on read/delete/exists), so this normalization leaks a LocalFilesystem-specific convention across a backend-agnostic seam. Safer shapes: normalize inside LocalFilesystem (where resolvePath semantics actually justify "."), or gate the substitution on the default backend being local, or teach the sandbox backend that "." means its own root and cover it with a test. Which of those matches the intent here?

if ("/".equals(path) || ".".equals(path)) {
List<FileInfo> results = new ArrayList<>();
LsResult defaultResult = defaultBackend.ls(runtimeContext, "/");
LsResult defaultResult = defaultBackend.ls(runtimeContext, rootAnchor(path));

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.

ls and grep now rewrite the root spelling before calling the default backend; glob (lines ~345/349) still forwards the raw path ("/" or null) and depends on LocalFilesystem.glob normalizing it internally, and route backends keep receiving "/". So after this change there is no single answer to "what does the composite call root": ls/grep say ".", glob says "/", and the routes say "/". That is the same kind of per-method drift that produced #3253.

Could glob go through the same helper, or (per the other comment) could the normalization move into the backends so the composite always forwards "/"? Either way, a short note in the class javadoc stating the root spelling the composite guarantees to its backends would keep the next operation from re-introducing this.

return route.backend().exists(runtimeContext, route.backendPath());
}

/**

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 : path fallback arm looks unreachable from both call sites — ls calls rootAnchor only inside "/".equals(path) || ".".equals(path) and grep only inside path == null || "/".equals(path) || ".".equals(path), so it always returns ".". That also means the Codecov partial that motivated the follow-up test will stay partial: grep(".") takes the true arm, not the fallback. If the fallback is not meant to be reachable, a constant (ROOT_ANCHOR = ".", or a no-arg helper) is clearer and fully covered; if it is, rootAnchor should be called before the root branch rather than inside it.

@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict with main — and the stacked base has landed

#3247 (sharedLocalWorkspace on the filesystem specs) was merged into main as 320822d4, so this branch is now 11 commits behind and its copy of #3247's commits conflicts with the merged version. It cannot be merged in its current state.

Since the stacked base is in main, the cleanest path is a rebase that drops the carried-over commits and leaves only the three commits that belong to #3253:

git fetch upstream
git rebase --onto upstream/main 169eed83 HEAD
git push --force-with-lease

(plain git rebase upstream/main works too, but replays #3247's two commits on top and you would resolve the same conflict twice.)

CI on this PR is currently green (build (ubuntu-latest), build (windows-latest), codecov/patch, license/cla all passing), so the only blocker is the conflict. Re-review on request after the rebase — @mention me and I will pick it up on the next sweep.


Automated notification by github-manager-bot

@aiyili
aiyili force-pushed the fix/root-containment branch from c04290c to b5d4977 Compare September 26, 2026 04:46

@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 after the new commits since my last pass (head now b5d4977e). The containment fix is correct and well-tested: routing default-backend ls/grep root enumerations through rootAnchor (. instead of //null) closes both the OS-root leak under UNRESTRICTED resolvers and the blank-key namespace bypass, and mirrors the normalization LocalFilesystem.glob already applies (#3253). CLA signed. Two minor informational notes inline; no blockers.

Stacked-PR note: this PR is stacked on #3247 — it should not be merged before #3247 lands (or is rebased onto main independently).


Automated review by github-manager-bot

* LocalFilesystem.glob} already applies (#3253).
*/
private static String rootAnchor(String path) {
return (path == null || "/".equals(path) || ".".equals(path)) ? "." : path;

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] rootAnchor defensively handles null, but both call-site guards differ: ls only enters this branch for "/"/".", while grep also passes null. Behaviour is correct today; consider aligning the ls guard with grep (or a short comment) so the null case stays reachable if ls ever routes null paths.

// ====================

@Test
void rootListingAndGrepAnchorAtTheCallersNamespace() throws Exception {

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] Good multi-tenant isolation coverage (sibling-tenant leak + .. escape assertions, shared-mode escape check). One addition worth considering: an assertion that ls("/") and ls(".") return identical entry sets for a namespaced backend, locking in the anchor-equivalence guarantee that the fix relies on.

@aiyili

aiyili commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

Thanks — both Info items addressed in edc4493:

  1. Guards aligned — ls's root branch now also routes null through rootAnchor like grep. Worth noting this turned out to be more than defensive alignment: at the previous head, ls(null) fell through to the default branch and LocalFilesystem.resolvePath(null) short-circuited to the backend's raw cwd — the same namespace bypass as "", just via the null key. Aligning closes that variant too.
  2. Anchor-equivalence assertion added — ls("/") and ls(null) must return entry sets identical to ls("."), pinning the guarantee the fix relies on.

Module suite 12/12 on the touched classes green.

One clarification on the stacked-PR note: it's stale — #3247 merged on 2026-09-24, and this branch was rebased onto main as a single commit (b5d4977) right after; the head you reviewed (b5d4977) is that rebased commit, so the PR is a clean 2-commit change on current main with no #3247 content in the diff. Ready to merge independently.

@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

The follow-up commit adds null to ls's root guard and tests that ls(null) returns the same entry set as ls(".") and ls("/"). It partially resolves the prior null-guard and test-coverage notes, so this round is a comment, not a block: the commit is a strict improvement and I am not requesting changes. Two follow-ups are flagged inline — one Warning (blank/whitespace paths still bypass the anchor) and one Info (a configured "/" route keeps ls(null) and grep(null) non-equivalent). CLA is signed (license/cla=pending was not observed for this PR) and GitHub reports the head as MERGEABLE.

Previous round's notes

  • ls(null) did not take the same namespace-aware root path as grep(null) — partially resolved (CompositeFilesystem.java:201-204 sends un-routed null through rootAnchor, but ls still routes before this guard when a "/" route exists).
  • No direct regression assertion pinned ls(null) to the other root spellings — partially resolved (RemoteFilesystemSpecTest.java:213-220 compares null and "/" with ".", but does not cover blank paths or a "/" route).
  • PR #3254 was stacked on #3247 — resolved (view.json says it was rebased; compare.json shows b5d4977e parented by local main HEAD 6a056809, and RemoteFilesystemSpec.sharedLocalWorkspace is present on main).

Findings

  • [Warning] agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/CompositeFilesystem.java:201 — non-blocking: empty and whitespace paths bypass the namespace anchor in ls, grep, and sibling glob, leaking the raw workspace/sibling tenant entries for a namespaced UNRESTRICTED backend.
  • [Info] agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/CompositeFilesystem.java:201 — A permitted "/" route makes ls(null) select that route while grep(null) takes root aggregation.

Verified good

  • CompositeFilesystem.java:201-204,530-532 sends ordinary default-backend null, "/", and "." root calls to the literal "." namespace anchor rather than an absolute root.
  • CompositeFilesystem.java:282-285 uses the same anchor for grep; apart from the configured-root-route case, "./", absolute/relative subpaths, .. paths, and Windows-separator paths all bypass both root guards consistently.
  • RemoteFilesystemSpecTest.java:213-220 executes the new ls(null) branch and compares its sorted entry paths with ls(".") and ls("/"); reverting the new null predicate would fail this fixture.
  • CompositeFilesystem.java:328-397 is the only other enumeration surface (glob); there is no find, walk, tree, stat, or readDir entry point in this class. Root null/"/" globbing remains normalized by the default LocalFilesystem; the blank-path gap is reported above.

Stacked-PR note

The #3247 merge-order warning no longer applies: the supplied PR metadata says this branch was rebased after #3247 merged, compare.json places the PR base directly on 6a056809, and that is the checked-out main commit.


Automated review by github-manager-bot

if ("/".equals(path) || ".".equals(path)) {
// Guard aligned with grep (and rootAnchor): a null path must reach the same
// namespaced anchor, not the backend's raw cwd via the blank-key shortcut (#3253).
if (path == null || "/".equals(path) || ".".equals(path)) {

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 root predicate still excludes "" and whitespace. Those values fall through to the raw default backend in ls and grep, and glob has the same bypass. LocalFilesystem.applyNamespacePrefix leaves blank keys unchanged and resolvePath maps them to cwd, exposing sibling tenant directories in the namespaced UNRESTRICTED backend. FilesystemTool and WorkspacePathNormalizer preserve blank strings. Treat blank paths as the same root anchor (or reject them consistently) in all three enumeration methods, and test empty and whitespace paths alongside null.

if ("/".equals(path) || ".".equals(path)) {
// Guard aligned with grep (and rootAnchor): a null path must reach the same
// namespaced anchor, not the backend's raw cwd via the blank-key shortcut (#3253).
if (path == null || "/".equals(path) || ".".equals(path)) {

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.

ls and grep are still not strictly symmetric when a caller configures a "/" route: ls(null) calls routeForPath(null) before this guard and selects that route, whereas grep(null) skips routing and aggregates the default and root routes. HarnessAgent.Builder.filesystemRoute accepts such a prefix. If null is intended as a root spelling, skip route resolution for it in ls as grep does, then add a root-route regression test.

@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 head 6e569be1 (one commit since my edc4493c review). The commit does what the follow-up asked: isRootSpelling now covers blank/whitespace, null no longer participates in route resolution for ls/glob, the aggregate branches forward the contract spelling "/", and LocalFilesystem gained isRootPath so a root-spelled scan cannot reach the OS root or drop the per-user namespace. The new tests — including the sibling-tenant leak assertion — are the right shape. I am not approving this round: the "/" vs "." asymmetry through routeForPath is still real when a "/" route is configured, and forwarding "/" widens the blast radius to default backends that were not updated. CI (build ubuntu-latest/windows-latest) was still pending when this review was posted.

Findings

  • [Warning] CompositeFilesystem.java:210 — default backends other than LocalFilesystem may treat "/" as an absolute/container root; only LocalFilesystem anchors it here.
  • [Warning] CompositeFilesystem.java:190 — with a configured "/" route, ls("/") takes the routed branch while ls("."), ls(null) and ls("") take the aggregate branch, so the four root spellings are not equivalent.
  • [Info] LocalFilesystem.java:239 — enumeration surfaces normalize blank/null; mutation surfaces do not. Document the contract.

Suggestions

Check isRootSpelling(path) before routeForPath(path) in ls/grep/glob, and extend rootScans_forwardContractSpellingToNonLocalDefaultBackend / nullRootScan_aggregatesDefaultAndRootRoute_symmetricWithGrep to cover a non-local default backend and the "/" spelling with a root route present.


Automated review by github-manager-bot

// strip the per-user namespace from the anchor and expose sibling tenants.
if (isRootSpelling(path)) {
List<FileInfo> results = new ArrayList<>();
LsResult defaultResult = defaultBackend.ls(runtimeContext, "/");

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] Forwarding the contract spelling "/" instead of the internal "." anchor is right for the seam, but only LocalFilesystem was taught to treat "/" as "my own root" in this commit. OverlayFilesystem, BakedContextFilesystem, AbstractSandboxFilesystem and RemoteFilesystem can all be installed as defaultBackend (the CompositeFilesystemTest comment calls out RoutedSandboxFilesystem doing exactly that), and for them "/" is an absolute path — a sandbox default backend now enumerates the container root, which is the same class of leak #3253 reported. Please audit the other AbstractFilesystem implementations, or keep passing the anchor the previous default backend understood, and add a contract test that every default backend roots "/" inside its own workspace.

// below, exactly like grep(null) (review follow-up, #3253).
if (path != null) {
RouteResult route = routeForPath(path);

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] Route resolution still precedes the root check, so the four root spellings are not equivalent when a "/" route is configured. stripLeadingSlash("/") is "", which matches the canonicalized "/" prefix in routeForPath and takes the routed branch (only that backend's entries), while "." matches nothing and null/blank now skip routing entirely, so all three take the aggregated branch. nullRootScan_aggregatesDefaultAndRootRoute_symmetricWithGrep pins this: ls(null) aggregates default + root route, but ls("/") on the same composite returns only the route. Moving isRootSpelling(path) above the if (path != null) block (and asserting "/" and "." in that test alongside null/"") makes the equivalence real; otherwise the javadoc claim that all root spellings mean "this filesystem's own root" does not hold.

@Override
public LsResult ls(RuntimeContext runtimeContext, String path) {
Path dirPath = resolvePath(runtimeContext, path);
Path dirPath = resolvePath(runtimeContext, isRootPath(path) ? "." : path);

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] Root anchoring is applied to the enumeration surfaces (ls/grep/glob) but read/write/edit/delete/exists still hand "/" and "" straight to resolvePath, so ls("") and read("") disagree about what a blank path means. Defensible, but worth one sentence in AbstractFilesystem stating that blank/null are root spellings only for enumeration, so the next backend does not have to guess.

@aiyili

aiyili commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

Both warnings addressed in 71941a4, plus the Info:

  1. Root check moved before routing (ls/grep/glob): isRootSpelling(path) now precedes routeForPath(path), so a configured "/" route can no longer capture ls("/") while "."/null/"" take the aggregate — all four spellings take the same aggregated view. nullRootScan_aggregatesDefaultAndRootRoute_symmetricWithGrep now asserts entry-set equality across /, ., "", " " against null on a composite with a "/" route, and rootScans_forwardContractSpellingToNonLocalDefaultBackend asserts the routed backend never receives an ls for any root spelling.

  2. Non-local default backend audit (per the suggestion): all implementations that can sit as a composite default backend were checked against the contract spelling / —

    • LocalFilesystem: anchored via isRootPath (this PR);
    • RemoteFilesystem: / is its virtual store root (key-space, not OS filesystem — no host leak possible); one real bug found and fixed en route: ls("") NPE'd on the endsWith check — blank/null now normalize to /, matching normalizePath on grep/glob;
    • OverlayFilesystem / BakedContextFilesystem / RoutedSandboxFilesystem: pure delegation, semantics inherit their delegates;
    • sandbox BaseSandboxFilesystem.ls builds if [ ! -e <path> ] — for / on a POSIX sandbox that is the container root: reachable only when a sandbox filesystem is installed as a default backend, which no spec does today (RoutedSandboxFilesystem installs composites per route and SandboxBackedFilesystem is standalone), noted here for the record rather than silently widened.
      The contract test (rootScans_forwardContractSpellingToNonLocalDefaultBackend) now pins the mock-backend contract and the routed-backend exclusion.
  3. Info documented: AbstractFilesystem.ls javadoc now states the root-spelling contract for enumeration surfaces (null/blank///. anchor inside the workspace or store namespace, never the OS root; CompositeFilesystem forwards /), and that mutation surfaces make no such promise for blank/null.

Module suite matches the upstream baseline (2462 tests, 0 failures, only the two known Windows symlink-privilege environment errors).

@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

This PR normalizes CompositeFilesystem enumeration root spellings and anchors LocalFilesystem root scans through the caller namespace. The new head resolves the previous route-order asymmetry and documents the enumeration-only scope, but it does not make the canonical "/" safe for sandbox default backends. Request changes: routed sandbox grep can now recursively scan the container root, and root-equivalent path forms still bypass the local namespace.

Previous round's findings

  • Default backends other than LocalFilesystem may treat "/" as an absolute root — unresolved (RoutedSandboxFilesystem delegates its default backend to BaseSandboxFilesystem, which directly shells "/").
  • A configured "/" route made root spellings take divergent paths — resolved (the root predicate now runs before route resolution in ls, grep, and glob).
  • The enumeration-only contract needed documentation — resolved (AbstractFilesystem now distinguishes enumeration from mutation surfaces).

Findings

  • [Warning] agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/CompositeFilesystem.java:299 — Canonicalizing grep(".") to "/" makes routed sandbox defaults recursively search the container root.
  • [Warning] agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/CompositeFilesystem.java:553 — Root-equivalent paths such as "/." and "//" bypass the textual root predicate and reach the OS root.
  • [Warning] agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/remote/RemoteFilesystem.java:234 — Direct RemoteFilesystem listings still do not honor the newly documented "." and whitespace root spellings.

Checks

  • CLA: signed (license/cla = success on head 71941a4e).
  • CI at review time: Check License, Check Module Sync, build (ubuntu-latest), codecov/patch pass; build (windows-latest) still pending.

Verified good

  • Root checks precede route resolution in all three CompositeFilesystem enumeration methods.
  • LocalFilesystem maps null, blank, and "/" to "." before ls, grep, and glob resolution, preserving its namespace prefix.
  • The new composite test verifies that root spellings bypass a configured "/" route and aggregate its entry with the default view.
  • The namespaced local test asserts that a sibling tenant is absent from root listings, grep results, and glob results.
  • The shared-workspace test checks that a marker outside the workspace is not returned by a root listing.

Automated review by github-manager-bot

Additional notes (not anchored to a changed line)

  • [WARNING] agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/remote/RemoteFilesystem.java:234 — The new AbstractFilesystem contract says "." and blank spellings mean the backend root, but direct RemoteFilesystem.ls(".") still queries "./" and whitespace queries a whitespace prefix, rather than the store root. The composite tests hide this because they forward "/" to the mock/default backend. Normalize null, blank, "/", and "." to "/" in the remote implementation and add direct remote ls coverage. (line outside diff)

List<GrepMatch> allMatches = new ArrayList<>();
GrepResult defaultResult = defaultBackend.grep(runtimeContext, pattern, path, glob);
GrepResult defaultResult =
defaultBackend.grep(runtimeContext, pattern, path == null ? null : "/", glob);

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.

Canonicalizing non-null root spellings to "/" is unsafe for the production RoutedSandboxFilesystem default backend. It delegates to BaseSandboxFilesystem, which shells the supplied grep path directly, so grep(..., ".") changes from the sandbox working directory to recursive grep -r ... /, exposing and scanning the container root. The same backend cannot satisfy the new contract for root ls/glob either. Make sandbox backends normalize the contract root to their workspace before this forwarding, and add an integration test through RoutedSandboxFilesystem.

* meaning of its own root — namespaced local backends anchor {@code "/"} at {@code
* {workspace}/{userId}} via {@code LocalFilesystem#isRootPath}.
*/
private static boolean isRootSpelling(String path) {

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 recognizes only four raw strings. Valid paths such as "/.", "//", and "/tmp/.." do not match, so an UNRESTRICTED namespaced LocalFilesystem receives an absolute path and resolves it to the OS root, bypassing the namespace for ls, grep, and glob. Normalize paths before the root/route decision (and apply the same rule in LocalFilesystem.isRootPath), then cover these root-equivalent forms in the containment tests.

@aiyili

aiyili commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

All three warnings addressed in aa49b43:

  1. Root-equivalent forms (/., //, /tmp/..): new shared AbstractFilesystem.denotesRootPath(path) canonicalizes duplicate separators and resolves ./.. segments textually; both CompositeFilesystem.isRootSpelling and LocalFilesystem.isRootPath delegate to it, so no absolute variant reaches an UNRESTRICTED resolver as a non-root path. Composite tests now assert /, ., null, "", " ", /., //, /./, /tmp/.. all aggregate over the default backend (contract spelling /), with a configured "/" route never receiving them.

  2. Routed sandbox container-root grep: BaseSandboxFilesystem ls/grep/glob now anchor root spellings at the sandbox working directory (.) via a rootAnchor helper — the composite forwards the contract spelling /, and the sandbox backend owns its root meaning. Tests: canned command-shape assertions for ls/grep/glob across all root spellings (including /., //, /tmp/..), plus an integration test through RoutedSandboxFilesystem asserting grep("/") and grep(".") both shell out with -e 'needle' '.' (the sandbox cwd), not /.

  3. Direct remote ls: RemoteFilesystem.normalizePath now maps null/blank///. to the store root, and ls uses it (also fixing a latent NPE on ls(null) and a ./ prefix query on ls(".")). New RemoteFilesystemRootSpellingTest seeds an InMemoryStore and asserts /, ., null, "", " " all return the identical store-root listing (root-file.md + uploads/).

Module suite matches the upstream baseline (2462 tests, 0 failures, only the two known Windows symlink-privilege environment errors).

@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

The new head aa49b433 closes all three points from the previous round: grep(".")/ls no longer recurse the container root (BaseSandboxFilesystem.rootAnchor), root-equivalent spellings are handled by one shared canonical check (AbstractFilesystem.denotesRootPath), and RemoteFilesystem now honours null/blank///. consistently across ls/grep/glob, with direct tests for each backend.

That still leaves one blocking regression: routing ls through normalizePath removed the trailing / the rest of the method depends on, so listing a non-root directory now drops its files and can surface sibling prefixes. Keeping the request for changes on that one point — the fix is a couple of lines plus one test case.

Findings

  • [Critical] remote/RemoteFilesystem.java:160 — non-root ls() loses its trailing-separator prefix: direct children are emitted as a self-referencing directory entry instead of files, and startsWith/listByPrefix now over-match sibling prefixes.
  • [Info] remote/RemoteFilesystem.java:725 — normalizePath is shared with the mutation surfaces, so "." is accepted there too; either scope the root spelling to enumeration or document it.

Verified good

  • denotesRootPath collapses duplicate separators and ./.. textually, so /., // and /tmp/.. reach the root branch instead of the OS root; LocalFilesystem and CompositeFilesystem now share the single implementation.
  • BaseSandboxFilesystem anchors ls/grep/glob at . (the sandbox working directory) for every root spelling, which is what the routed-sandbox default backend needed.
  • glob already used the length() + 1 form, confirming the ls asymmetry above is unintended rather than a contract change.
  • Test coverage is real and behavioural: CompositeFilesystemTest asserts times(9) contract-spelling forwarding including the canonical forms, RemoteFilesystemRootSpellingTest pins the store-root spellings, and BaseSandboxFilesystemTest asserts the emitted shell commands anchor at '.'.

Checks

  • CLA: signed (license/cla = success on aa49b433).
  • CI on the current head: Check License, Check Module Sync, build (ubuntu-latest), build (windows-latest), codecov/patch — all passing.

Automated review by github-manager-bot

String normalizedPath = path.endsWith("/") ? path : path + "/";
// Root spellings ("." and blank included) normalize to the store root, matching
// grep/glob; this also null-proofs the downstream prefix handling (#3253 review).
String normalizedPath = normalizePath(path);

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.

[Critical] Switching ls to normalizePath(path) drops the trailing separator the rest of this method still depends on, so a non-root directory listing loses its files.

The removed line built path + "/" unconditionally for non-root paths; normalizePath does the opposite (normalized.substring(0, length - 1) strips a trailing /, and none is added). With a store key /memory/notes.md and ls("/memory"):

  • relative = key.substring(normalizedPath.length()) is now "/notes.md", not "notes.md";
  • relative.contains("/") is therefore true, so the file is never emitted as a file — it becomes subdirs.add("/memory" + "" + "/"), i.e. the directory re-lists itself as its own child and the entry is lost;
  • item.key().startsWith(normalizedPath) in the fallback (and index.listByPrefix in the fast path) also lost its separator guard, so /memory-backup/x.md now matches a ls("/memory") request and surfaces as a bogus child.

glob in this same class already handles it the other way (key.substring(normalizedPath.length() + 1), with "/".equals(normalizedPath) special-cased) — ls needs the same treatment. Suggested fix, keeping the root case intact:

String normalizedPath = normalizePath(path);
String prefix = "/".equals(normalizedPath) ? "/" : normalizedPath + "/";

then use prefix for hasPrefix / listByPrefix / startsWith / substring, or reuse matchesPathPrefix(key, normalizedPath) like grep/glob do.

This is not covered by CI: RemoteFilesystemRootSpellingTest only exercises root spellings, and the existing non-root ls assertions go through a LocalFilesystem route. A RemoteFilesystem.ls("/memory") case asserting the child file is returned (plus a sibling-prefix key that must not appear) would pin both halves.

if (path == null || path.isBlank()) {
// Enumeration root spellings per the AbstractFilesystem contract: null, blank, "/"
// and "." all mean the store root (#3253 review).
if (path == null || path.isBlank() || "/".equals(path) || ".".equals(path)) {

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] normalizePath is shared by the mutation surfaces too (exists, delete, move), so adding "." here also changes how those interpret it — exists(rc, ".") now asks the index about / and returns true where it previously returned false. Harmless in practice (delete/move still call validatePath first and the /-prefix match hits nothing because keys never start with //), but it does contradict the enumeration-only framing this PR documents for root spellings. Either scope the root spelling to ls/grep/glob with a dedicated helper, or state in the javadoc that "." is also accepted on the mutation surfaces.

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.

Correction on my own point above: I re-traced exists/delete/move and the "." change is not an actual behaviour change there — before this commit "." normalised to "/.", now to "/", and neither form matches any key, so all three surfaces still no-op. Please read this as a documentation nit only (the root-spelling set is worth stating explicitly if mutation surfaces share the helper), not as a correctness concern. The ls finding above stands.

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.

Scrapping my own point: I re-checked the mutation callers and the premise is wrong. With "." now normalizing to "/", exists(rc, ".") still returns false (the store lookup becomes get(ns, "/") and the child scan becomes startsWith("//"), neither of which any /-prefixed key matches), and delete/move behaved the same before ("/."). So the shared normalizePath does not change mutation behaviour - please ignore the [Info] above; only the ls() prefix finding at line 160 stands.


Automated review by github-manager-bot

@aiyili

aiyili commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

Fixed in 3a84af8:

  • Critical: ls now derives its prefix after normalization — prefix = "/" for the root case, normalizedPath + "/" otherwise — and the fast path (hasPrefix/listByPrefix/substring) plus the fallback (startsWith/substring) all use that prefix. Non-root listings keep direct-child semantics: ls("/memory") returns /memory/notes.md and /memory/sub/, no self-referencing entry, and a sibling-prefix key /memory-backup/x.md never surfaces. Pinned by the new nonRootDirectoryListingKeepsTrailingSeparatorSemantics test (both /memory and memory spellings).
  • Info: normalizePath is back to its original form — mutation surfaces are untouched. The root-spelling handling for ls is local to the enumeration path and uses the shared denotesRootPath (so /, ., /., //, /tmp/.. all anchor at the store root there).

Module suite matches the upstream baseline (2462 tests, 0 failures, only the two known Windows symlink-privilege environment errors).

@aiyili

aiyili commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the re-trace — and a status note: the current head (3a84af8, pushed as the fix for the ls finding) already supersedes this hunk. normalizePath is back to its original two-line form (null/blank → /), so the mutation surfaces (exists/delete/move) no longer share any root-spelling handling at all — the documentation nit is moot for the helper. The enumeration root spellings (including ".") now live only in ls, via the shared AbstractFilesystem.denotesRootPath, and the enumeration-vs-mutation distinction is stated in the AbstractFilesystem.ls javadoc ("Mutation surfaces ... make no such promise for blank/null").

So with 3a84af8: the ls trailing-separator Critical is fixed (pinned by nonRootDirectoryListingKeepsTrailingSeparatorSemantics), and the helper-split also removes the ambiguity this correction was about. Nothing further needed from my side — happy to rebase or adjust if anything else comes up.

@aiyili

aiyili commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

Acknowledged — the Info is fully withdrawn, which matches the current head anyway: 3a84af8 reverted normalizePath to its original form, so the helper no longer carries any root-spelling handling at all (that lives only in ls via denotesRootPath). And the ls() prefix finding was fixed in the same commit, pinned by nonRootDirectoryListingKeepsTrailingSeparatorSemantics. Nothing outstanding from my side.

@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

The new commit fixes the trailing-separator regression in RemoteFilesystem.ls: non-root directories now build a child prefix (normalizedPath + "/") so siblings like /memory-backup no longer leak into ls("/memory"), and root spellings are anchored via denotesRootPath. The previous review left no recorded findings, so there are no outstanding items to resolve. However, the same commit narrowed normalizePath to reject "." for mutation surfaces, and RemoteFilesystem.grep/glob were not updated to match ls; direct calls with . violate the enumeration root-spelling contract. Overall verdict: comment (non-blocking) — align grep/glob root handling with ls before merging.

Previous round's findings

  • No prior findings were recorded by the bot at commit aa49b433.

Findings

  • [Warning] agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/remote/RemoteFilesystem.java:727 — normalizePath no longer anchors . for enumeration, so direct grep/glob calls with . search under /. and miss matches; grep/glob should use the same denotesRootPath guard as ls.

Verified good

  • RemoteFilesystem.ls now uses AbstractFilesystem.denotesRootPath and a trailing-separator prefix; the new nonRootDirectoryListingKeepsTrailingSeparatorSemantics test pins the sibling-prefix leak.
  • CompositeFilesystem checks root spellings before routing and forwards the contract spelling / to the default backend; the mock test verifies all root spellings bypass a configured / route.
  • LocalFilesystem delegates root detection to denotesRootPath and anchors root spellings via resolvePath(rc, "."), keeping the per-user namespace in UNRESTRICTED mode.
  • BaseSandboxFilesystem.rootAnchor maps every root spelling to ., so shell ls, grep -r, and find target the sandbox cwd instead of the container root.
  • AbstractFilesystem.denotesRootPath correctly collapses separators and resolves ./.. segments, catching /., //, and /tmp/.. as root spellings.

Automated review by github-manager-bot

Additional notes (not anchored to a changed line)

  • [WARNING] agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/remote/RemoteFilesystem.java:727 — normalizePath no longer maps "." to "/", but grep and glob still call it directly for enumeration. A direct RemoteFilesystem.grep(..., ".", ...) or glob(..., ".") therefore searches under the meaningless prefix "/." and misses every match, violating the AbstractFilesystem root-spelling contract for enumeration surfaces. Keep normalizePath mutation-only (null/blank → "/") and change grep/glob to use the same root guard as ls: denotesRootPath(path) ? "/" : normalizePath(path). (line outside diff)

@aiyili

aiyili commented Sep 27, 2026

Copy link
Copy Markdown
Contributor Author

Aligned in 9441d95:

  • New normalizeEnumerationPath(path) — denotesRootPath(path) ? "/" : normalizePath(path) — now used by ls, grep and glob alike (ls's inline guard was folded into it). normalizePath stays mutation-only per the documentation suggestion.
  • RemoteFilesystemRootSpellingTest gained grepAndGlobRootSpellingsSearchTheStoreRoot: direct grep and glob with /, . and null must each find both seeded files at the store root — . previously searched the meaningless /. prefix and missed everything.

Module suite matches the upstream baseline (0 failures, only the two known Windows symlink-privilege environment errors).

@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 delta 3a84af84..9441d955: the remote grep/glob root-spelling anchor is correctly consolidated into normalizeEnumerationPath and applied to both enumeration surfaces, with a solid regression test covering "/" / "." / null for grep and glob. This resolves my last [Warning] — the Critical (non-root ls trailing-separator semantics) and everything before it stayed fixed, and mutation surfaces correctly keep normalizePath per the documented contract.

LGTM. CI (build windows/ubuntu) was still in progress at review time — fine to merge once it goes green.


Automated review by github-manager-bot

@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR conflicts with main (mergeable=CONFLICTING, mergeStateStatus=DIRTY) and cannot be merged as-is. Please rebase or merge main into fix/root-containment and resolve the conflicts:

git fetch origin
git checkout fix/root-containment
git rebase origin/main
# resolve conflicts, then:
git push --force-with-lease

Code review itself is already covered on this PR — this is a one-time conflict reminder. Feel free to @mention me for a re-review once the branch is clean.


Automated notification by github-manager-bot

@aiyili
aiyili force-pushed the fix/root-containment branch from 9441d95 to a792722 Compare September 30, 2026 23:08
@aiyili

aiyili commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main as a single commit (a792722) — the conflict was with the merge of #3226 (the sandbox edit fix), whose BaseSandboxFilesystem/Test changes are now folded in alongside the root-anchor semantics. Conflict markers verified resolved at the API compare level (behind_by: 0, mergeable: true); targeted and full harness suites pass locally (0 failures, only the two known Windows symlink-privilege environment errors).

@aiyili

aiyili commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

The rebase CI failure (run 36789527021) is unrelated to this PR's changes — evidence:

Could someone with admin rights rerun the failed jobs (rerun-failed-jobs on run 36789527021)? All the filesystem-targeted suites (CompositeFilesystemTest, RemoteFilesystemRootSpellingTest, BaseSandboxFilesystemTest, RemoteFilesystemSpecTest, LocalFilesystemModeTest, LocalFilesystemSpecSharedWorkspaceTest) passed locally on the rebased commit, and the full suite matches the upstream baseline (0 failures, only the two known Windows symlink-privilege environment errors).

@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 a7927229 (the previous approval was on 9441d955; the branch now carries the whole change as a single commit). The direction is right: hoisting the root check above routeForPath and canonicalizing to the contract spelling "/" closes the ls/glob OS-root escape from #3253, and pushing denotesRootPath down into LocalFilesystem / RemoteFilesystem / BaseSandboxFilesystem is what makes the contract hold per backend instead of only inside the composite. The added coverage (rootScans_forwardContractSpellingToNonLocalDefaultBackend, unrestricted_rootSpellingsAnchorAtNamespacedRootNotOsRoot, RemoteFilesystemRootSpellingTest, the sandbox rootAnchor cases) pins the exact failure modes rather than the happy path — good.

Four non-blocking points, all inline:

  • [Warning] denotesRootPath only canonicalizes absolute root spellings plus "."; "./", ".." and "sub/.." still fall through to a backend raw, where a namespaced ROOTED LocalFilesystem resolves user-2/.. back to the workspace root — the same sibling-tenant listing the new UNRESTRICTED test guards against.
  • [Warning] The helper classifies but does not normalize, so "/alice/../bob" is forwarded unmodified and re-roots outside the namespace anchor. Pre-existing, but the new javadoc advertises that class of escape as closed; the wording and the behaviour should agree.
  • [Info] grep is the one surface where null is forwarded instead of canonicalized; containment there now relies on every future AbstractFilesystem implementation honouring the null convention by hand.
  • [Info] With the root check hoisted, a route registered at "/" is unreachable for ls/grep/glob but still honoured by read/write/edit/delete/exists; rejecting or logging a "/" prefix in the constructor would remove the silent divergence.

Not approving this round: build (ubuntu-latest) is failing and build (windows-latest) was cancelled on this head (mergeable_state=unstable), so the checks need to be green first. CLA is signed. Nothing here needs a redesign — the follow-ups can be a separate PR if you prefer to keep this one focused.


Automated review by github-manager-bot

if (p.equals(".")) {
return true;
}
if (!p.startsWith("/")) {

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.

Relative forms still slip past the root branch. "." is special-cased above, but the early return here rejects every other relative spelling, so "./" is not a root spelling while "." is, and ".." / "sub/.." are rejected as well. Those values then reach a backend raw: on a namespaced LocalFilesystem in ROOTED mode applyNamespacePrefix yields "user-2/..", and cwd.resolve("user-2/..").normalize() == the workspace root — i.e. the sibling-tenant listing the new unrestricted_rootSpellingsAnchorAtNamespacedRootNotOsRoot test explicitly asserts against. The resolver behaviour predates this PR, so this is not a regression, but the new helper is the natural place to close it: either resolve ./.. for relative input too (treat a relative path the same way after prefixing a virtual /), or reject relative enumeration paths. Otherwise the "root-equivalent forms cannot slip past" claim in the javadoc only holds for absolute spellings.

// Non-root path that didn't match any route: delegate to default backend only.
// Route scanning only makes sense for root-level recursive globs.
if (path != null && !"/".equals(path) && !".".equals(path)) {
if (!isRootSpelling(path)) {

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.

denotesRootPath classifies, it does not normalize. For a non-root absolute path that contains .. (e.g. ls("/alice/../bob")) this fall-through forwards the caller's raw string to the default backend. LocalFilesystem.applyNamespacePrefix returns absolute paths unsuffixed by the namespace, and resolveRooted then re-roots "alice/../bob" under cwd, so the result is cwd/bob — the enumeration lands in a sibling tenant's directory by popping the anchor that the namespace was supposed to provide. Again pre-existing rather than introduced here, but the helper javadoc now advertises exactly this class of escape as closed, so either (a) soften the wording to root spellings only, or (b) normalize/strip .. segments before delegating on the enumeration surfaces. A follow-up PR is fine; the two should not disagree.

List<GrepMatch> allMatches = new ArrayList<>();
GrepResult defaultResult = defaultBackend.grep(runtimeContext, pattern, path, glob);
GrepResult defaultResult =
defaultBackend.grep(runtimeContext, pattern, path == null ? null : "/", glob);

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.

grep keeps null as the only spelling the composite does not canonicalize. ls/glob send the contract spelling "/" to the default backend for every root form, while here null is forwarded verbatim (and "/", ".", "" become "/"). That is deliberate and documented, and every in-tree backend handles it (LocalFilesystem/BaseSandboxFilesystem anchor null via denotesRootPath, RemoteFilesystem via normalizeEnumerationPath), so no escape today — but containment for grep then depends on a convention that each new AbstractFilesystem implementation must remember to honour, whereas the canonicalized / path is checked by the existing tests. Consider canonicalizing null to "/" here as well (grep's own path != null branch already shows "/" to backends), or adding one interface-level test that pins null working-directory handling for every implementation.

// route resolution so a configured "/" route cannot capture ls("/") and make the
// spellings diverge (review follow-up, #3253). Non-root paths route as usual; null
// matches no route and falls through to the aggregate below.
if (!isRootSpelling(path)) {

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.

Hoisting the root check makes a configured "/" route unreachable on the enumeration surfaces only. routeForPath("/") does match a "/" prefix (both sides strip the leading slash, so "".equals("")), and that is precisely why ls("/") used to diverge from ls(".")/ls(null); the fix and the new Map.of("/", routedBackend) test are correct. The leftover wrinkle is asymmetry: read/write/edit/delete/exists still honour that "/" route while ls/grep/glob now ignore it, so a composite built with a "/" route behaves as two different filesystems depending on the call. Since such a route is now meaningless for enumeration, rejecting (IllegalArgumentException) or at least logging a "/" prefix in the constructor would make the divergence impossible to configure by accident.

@aiyili

aiyili commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

Disposition of the four non-blocking points:

CI: the ubuntu failure on the previous head was the #3371 middleware test (Failed to close extension context) — unrelated to this PR (details + evidence in my earlier comment); it needs an admin rerun to go green. All filesystem-targeted suites and the full suite (0 failures vs upstream baseline) pass locally on this commit.

@aiyili

aiyili commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

The rerun hit another unrelated flake — this time BotLoopGuardTest.idlePeersAreEvictedAfterWindowPlusCooldown (expected: <0> but was: <1>), a timing-sensitive eviction assertion in the channel/common extension, on the Windows runner. Again outside this PR's scope (it touches only agent/filesystem), and the same test class is not part of this PR's diff.

Everything this PR touches passed on this very run:

  • CompositeFilesystemTest 6/6, LocalFilesystemModeTest 23/23, RemoteFilesystemRootSpellingTest 3/3, RemoteFilesystemSpecTest 8/8 (log lines 6164-6298), plus the sandbox and spec suites.

Two different flakes in two runs (middleware lifecycle, then a channel timing assertion) — the CI environment looks generally flaky right now rather than anything head-specific. Another rerun-failed-jobs on run 36797861955 should do it; happy to help if anything else is needed.

@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 of the new commit f6d60ea2 on top of the previously reviewed a7927229. Both non-blocking items from the last round were taken, and the denotesRootPath javadoc narrowing is accurate: relative .//.. forms return false at AbstractFilesystem.java:65-66, /tmp/../etc returns false, while /tmp/.. is still detected and stays in the example list — so the doc now states exactly what the method does and defers the genuinely-unhandled escape class to #3378. Warn-not-throw is also the right contract here: before this PR a / route did capture root-spelling ls/grep/glob, so throwing would break configurations that exist today.

One thing keeps this at COMMENT: the new warn message is wrong about the two surfaces it names besides ls. grep and glob do not ignore a root route — their root-spelling aggregate branches call entry.backend().grep(..., "/", ...) / entry.backend().glob(..., "/") for every route and prependRoute("/", ...) is the identity, so a root-route backend's content is returned unprefixed. See the inline comment on CompositeFilesystem.java:92. String-only fix.

CI note (not a code problem)

build (windows-latest) is red on this head and build (ubuntu-latest) was cancelled. The Windows failure is BotLoopGuardTest.idlePeersAreEvictedAfterWindowPlusCooldown in agentscope-extensions-channel-common (expected: <0> but was: <1>) — a wall-clock test with 60 ms / 180 ms sleeps against a 160 ms idle threshold, in a module this PR does not touch, so it reads as timing flake under runner load rather than something introduced here. The previous head a7927229 failed on a different unrelated test (HarnessMiddlewareActivePointsTest). A maintainer-authorized re-run is the right next step for the checks; the diff itself does not need changes for it.

Findings

  • [Warning] CompositeFilesystem.java:92 — warn claims root routes are ignored by ls/grep/glob root scans; verified true for ls only. grep (line 342) and glob (line 424) scan every route backend and return its paths unprefixed.
  • [Info] CompositeFilesystem.java:95 — routes.keySet() is streamed twice (anyMatch, then filter(...).toList()); binding the filtered list once is cheaper to read and makes the log argument self-evident. Trivial, fold into the wording fix above.

Suggestions

Nothing structural. Once the warn wording matches the code, this commit is good as far as the review is concerned. If you want the divergence closed for real rather than diagnosed, the follow-up shape is to normalize route keys at construction — reject or drop a root-equivalent prefix (the constructor already throws for a null defaultBackend) — but that is a behaviour change beyond this PR's scope and belongs in #3378 territory.

Carried-over status: denotesRootPath javadoc scope — resolved. Root-route diagnostics — added, wording needs one correction.


Automated review by github-manager-bot — incremental on f6d60ea2.

if (routes != null
&& routes.keySet().stream().anyMatch(AbstractFilesystem::denotesRootPath)) {
LOG.warn(
"A route registered at the root ({}) is ignored by ls/grep/glob root scans"

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 warn text misdescribes the behaviour it exists to explain, for two of the three surfaces it names.

Verified against this head revision:

  • ls on a root spelling is checked before routing (line 203) and the aggregate loop only appends a synthetic directory entry for a / route (line 233) — it never consults that backend. So ignored by ls holds.
  • grep on a root spelling takes the aggregate branch at line 328 and then, for every route, calls entry.backend().grep(runtimeContext, pattern, "/", glob) (line 342), remapping matches through prependRoute(entry.prefix(), ...). For a / prefix prependRoute is the identity, so the root-route backend's hits are returned, indistinguishable from default-backend content. So ignored by grep does not hold.
  • glob does the same at line 424 (entry.backend().glob(runtimeContext, routePattern, "/")). So ignored by glob does not hold.

Why it matters: this warn exists precisely to stop a root route being configured silently. An operator who reads only honoured by mutation surfaces may keep tenant or workspace data behind a root route believing enumeration can never surface it, when grep("/", ...) and glob("**/*", "/") both scan it and return its paths unprefixed. A diagnostic that understates visibility is worse than no diagnostic.

Fix (string-only, non-blocking) — describe capture versus aggregation, e.g.:

LOG.warn(
        "A route registered at the root ({}) is never captured outright by"
                + " ls/grep/glob on root spellings - those return the aggregated"
                + " view across all backends (grep/glob still scan this backend,"
                + " with unprefixed paths) - and is routed to outright by"
                + " read/write/edit/delete/exists; register subtree prefixes"
                + " (e.g. /memories/) instead",
        rootKeys);

The same overstatement is in the block comment on lines 85-89 (unreachable on the enumeration surfaces) — correct it together. While there: routes.keySet() is streamed twice (anyMatch then filter); binding List<String> rootKeys = routes.keySet().stream().filter(AbstractFilesystem::denotesRootPath).toList() once and testing !rootKeys.isEmpty() is the same read and makes the log argument obvious.

@aiyili

aiyili commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

The #3378 fix is now on this branch (4de8f3a, stacked on the rebased commit): normalizeEnumerationSegments resolves ./.. segments for the non-root enumeration fall-through — ls("/alice/../bob") forwards /bob instead of the raw crafted path, closing the namespace-anchor pop-out — while relative ../ forms keep firing the backend traversal guard (SecurityException), matching the reject semantics already tested on this branch. No interface change; the interface-level null contract test from the issue will land as a follow-up if preferred.

@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 of the new commit 4de8f3a9 (previous reviews were on 9441d955 → a7927229 → f6d60ea2). Normalizing ., .. and duplicate separators on the way to the default backend — instead of only classifying them — is the right shape for #3378, and keeping the relative case literal so the backend's SecurityException guard still fires is a good call. normalizeEnumerationSegments is also a clean companion to denotesRootPath, and the javadoc scope note added there matches what the code now actually promises.

Three gaps keep this short of "the escape class is closed", all of them placement rather than design:

  • [Warning] CompositeFilesystem.java:390 — glob is not normalized, so the class the commit targets is still open on one of the three enumeration surfaces.
  • [Warning] CompositeFilesystem.java:209 (same in grep/glob) — a path that matches a route is delegated before any normalization, so /memories/../bob reaches the route backend as /../bob unmodified.
  • [Warning] AbstractFilesystem.java:97 — the rewrite is unconditional, which is lossy for backends that treat the path string literally (POSIX \ in a file name, RemoteFilesystem store keys).
  • [Warning] AbstractFilesystem.java:93 — the new helper has no test anywhere in the module.
  • [Info] CompositeFilesystem.java:91 — carried over from the last round and still unaddressed: the warn text says a root route is ignored by ls/grep/glob; it is true only for ls.

Suggestions

The single change that fixes the first two: normalize once at the top of each surface, before isRootSpelling/routeForPath, instead of at the default-backend fall-through.

public LsResult ls(RuntimeContext runtimeContext, String path) {
    String canonical = AbstractFilesystem.normalizeEnumerationSegments(path);
    // ... existing body, with `canonical` replacing `path` in
    // isRootSpelling(...), routeForPath(...) and the defaultBackend delegation
}

Route matching stays safe because the helper preserves relativity and only rewrites when a ./../duplicate-separator segment is present; "/memories/.." already canonically denotes "/", which is the aggregate-root case this PR handles.

For the lossiness, short-circuit when there is nothing to resolve so the caller's string reaches the backend byte-for-byte:

if (p.indexOf('\\') < 0 && !p.contains("./") && !p.contains("../")
        && !p.contains("//") && !p.endsWith("/")) {
    return path;
}

CI note

build (windows-latest) is failing on this head (maven-surefire test failures in agentscope-extensions-aistio, a module this PR does not touch — consistent with the timing-sensitive flakes seen on a7927229 and f6d60ea2), and build (ubuntu-latest) was cancelled. Not a code problem, but the checks need to be green before this can move. CLA is signed.

Nothing here needs a redesign — normalizing earlier plus a handful of table-driven cases would close it.


Automated review by github-manager-bot — incremental on 4de8f3a9.

// Route scanning only makes sense for root-level recursive globs.
if (path != null && !"/".equals(path) && !".".equals(path)) {
if (!isRootSpelling(path)) {
return defaultBackend.glob(runtimeContext, pattern, path);

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] glob is the one enumeration surface this commit does not normalize. ls (line 248) and grep (line 362) now delegate normalizeEnumerationSegments(path), but this fall-through still forwards the caller's raw string, so glob(rc, "**", "/alice/../bob") reaches a namespaced default backend exactly as it did before #3378 was opened — the same payload, the same anchor pop.

The javadoc on denotesRootPath treats ls/grep/glob as one class, and the commit message claims the enumeration surfaces are normalized, so today the claim is true for two of three. Adding the call here closes the class, or — better — hoisting normalization to the top of each surface (see the comment on line 209) makes the asymmetry impossible to reintroduce.

for (FileInfo fi : result.entries()) {
remapped.add(remapFileInfo(fi, route.routePrefix()));
if (route.routePrefix() != null) {
LsResult result = route.backend().ls(runtimeContext, route.backendPath());

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] Normalizing at the default-backend fall-through leaves the routed branch un-normalized, and that branch is where the namespace anchor actually exists to be popped. routeForPath strips the prefix before any segment resolution, so ls(rc, "/memories/../bob") produces backendPath == "/../bob" (line 148) and hands it to the route backend verbatim — .. at the head of an absolute path, the exact form normalizeEnumerationSegments was written to collapse. Same in grep (line 297) and glob (line 373).

Could normalization move above isRootSpelling(path) / routeForPath(path) at the top of each surface, so routing decisions and delegation both see the canonical string? That single change covers this branch, the glob gap above, and the default-backend delegation, and it keeps route matching sound: a prefix that is not root-equivalent only re-anchors when a .. actually cancels the segment, which is the behavior the caller gets from the filesystem today.

if (path == null) {
return null;
}
String p = path.replace('\\', '/');

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 \ → / fold is unconditional, and this method returns the string the backend receives, not a verdict. Two consequences worth a guard clause:

Skipping the rewrite when there is nothing to resolve keeps both cases byte-for-byte:

if (!p.contains("./") && !p.contains("../") && !p.contains("//")
        && !p.endsWith("/") && p.indexOf('\\') < 0) {
    return path;
}

denotesRootPath can keep folding unconditionally because it only classifies; a function whose return value is delegated needs to be conservative.

* input stays relative — a leading or unresolvable {@code ..} is kept literal so the
* backend's traversal guard (SecurityException) still fires.
*/
static String normalizeEnumerationSegments(String path) {

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] normalizeEnumerationSegments is a security-relevant public method on the interface every backend implements, and 4de8f3a9 adds it with no test: grepping the harness test tree at this head returns zero references to it, and the composite-level tests only feed it root spellings. That is why the glob and routed-prefix gaps above read as unverified rather than verified-and-accepted.

The table is short — "/alice/../bob" -> "/bob", "/../bob" -> "/bob", "a/../../b" -> "../b" (literal, so the traversal guard still fires), "./" -> ".", "" -> ".", "C:\\a\\..\\b" -> "b"-style Windows spelling, null -> null — plus two integration cases: ls(rc, "/memories/../bob") must not reach outside the route, and glob(rc, "**", "/alice/../bob") must return the same tree as "/bob".

@aiyili

aiyili commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

All four warnings addressed in d172dfb, using your suggested shape (normalize once at the top of each surface):

  1. Hoisted above isRootSpelling/routeForPath in ls/grep/glob — routing decisions, root aggregation, and every delegation (routed branch, default branch) now see the canonical string. That closes the glob gap, the routed-prefix gap (/memories/../bob no longer reaches the route backend as /../bob), and the default fall-through in one move.
  2. Byte-for-byte passthrough when nothing needs resolving (no ./, ../, //, trailing / or .., no backslash) — clean strings and literal RemoteFilesystem store keys are untouched; denotesRootPath keeps its unconditional fold since it only classifies.
  3. Table-driven tests (NormalizeEnumerationSegmentsTest) — your exact table plus the passthrough cases (/memories/2026-05-13.md byte-identical; POSIX backslash documented as normalized), the relative-literal cases, and a composite integration case: ls("/memories/../bob") cannot reach outside the route and the route store stays untouched.
  4. grep null — canonical == null keeps the documented working-directory forwarding; the interface-level null contract test for every implementation remains in [Bug] Enumeration surfaces: relative and ..-bearing paths bypass the namespace anchor (sibling-tenant access) #3378's scope as agreed.
  5. I2 carry-over noted — the warn text now says "root scans" (ls/grep/glob) rather than listing surfaces one by one; grep's null-forwarding is the documented exception.

Module suite matches the upstream baseline (0 failures, only the two known Windows symlink-privilege environment errors).

@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

Delta re-review of 4de8f3a9..d172dfbb (1 commit, 3 files) — the follow-up round to my previous review. All four findings from that round are resolved, and resolved the way they were proposed: normalization is hoisted to the top of ls/grep/glob so the routing decision and the delegation see one canonical string, clean strings now pass through byte-for-byte (which is what protects a RemoteFilesystem literal store key from being rewritten), relative .. stays literal so the backend guard still fires, and there is a table-driven test plus a route-escape integration test that asserts the route store is untouched. The new routedPrefixWithTraversal_cannotEscapeTheRoute case is the important one: /memories/../bob canonicalizes outside the route, and the test asserts it neither reaches the route backend nor creates anything outside the workspace.

Two follow-ups keep this from being an approve, both about the new fast path rather than the design:

  • AbstractFilesystem.java:97 — the passthrough predicate misses a trailing lone . segment, so "/memories/." is now returned unchanged where the slow path used to strip it to "/memories". That is a behaviour change introduced by this commit, and it is the same store-key-miss class the guard exists to prevent. One added clause (&& !path.endsWith(".")) closes it; "/a/.hidden" keeps passing through untouched either way.
  • CompositeFilesystem.java:203 — ls is the only one of the three surfaces that does not actually normalize once: the root test at line 228 still uses the raw path, and line 251 re-normalizes it instead of using canonical. Today both are safe — denotesRootPath does its own .. resolution — but the "normalize once at the top" invariant the comment claims holds for grep/glob and not for ls, and with the fast-path gap above the route decision and the value handed to the backend are then different strings for the same call.

CI on this head: Check License, Check Module Sync, build (ubuntu-latest), build (windows-latest), codecov/patch all green; license/cla signed; MERGEABLE/CLEAN. Neither follow-up is a blocker on containment grounds, so this is a COMMENT rather than a request-changes — fix the guard and align ls with grep/glob and this is done from my side.

Findings

  • [Warning] AbstractFilesystem.java:97-108 — fast-path predicate misses trailing /., regressing normalization of that spelling (store-key miss).
  • [Warning] CompositeFilesystem.java:203 — ls still mixes path and canonical at lines 228 and 251, unlike grep/glob.
  • [Info] NormalizeEnumerationSegmentsTest.java:110-114 — two table rows (/memories/. and /a/.hidden) would pin the fast/slow path equivalence.

Automated review by github-manager-bot

Comment on lines +97 to +101
// Byte-for-byte passthrough when there is nothing to resolve: POSIX file names may
// legally contain a backslash, and RemoteFilesystem treats the path as a literal
// store key — rewriting an already-clean string would change which key is read
// (#3378 review).
if (!path.contains("\\")

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 byte-for-byte guard is the right idea (it is exactly what stops a clean literal store key from being rewritten), but its predicate misses a trailing lone . segment, so the fast path now stops stripping a form the slow path used to normalize.

"/memories/.":

  • contains("\\") false, contains("./") false (the . is last, there is no "./" substring), contains("../") false, contains("//") false, endsWith("/") false, endsWith("..") false → returned unchanged as /memories/..
  • Before this commit it went through the loop: segments [memories, .], the . is skipped → /memories.

That is a behaviour change introduced by this very commit, and it is the failure mode the guard exists to prevent in the opposite direction: RemoteFilesystem treats the path as a literal store key, so ls("/memories/.") now asks the store for key /memories/. and misses instead of resolving to /memories. Trailing-dot spellings are not exotic here — model-emitted paths like notes/. and /x/. show up in the same class as the // and ./ forms already handled.

Suggested fix — one more clause, no new logic:

&& !path.endsWith("/")
&& !path.endsWith(".")   // covers both "/x/." and a bare "."; ".." is already covered

A bare "." still resolves correctly via the slow path (parts empty, not absolute → "."), and "/"-rooted "/." lands in denotesRootPath, so nothing else depends on the current behaviour. "/a/.hidden" keeps passing through untouched either way, because ".hidden" is a real name — worth keeping that as a table row so the two cases cannot be confused later.

RouteResult route = routeForPath(path);
// Normalize once at the top: routing decisions and every delegation see the canonical
// string, so a crafted ".." cannot pop the namespace anchor on any branch (#3378).
String canonical = AbstractFilesystem.normalizeEnumerationSegments(path);

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.

ls is the one surface of the three that does not actually normalize once. canonical is computed here and used for the route decision two lines below, but the two other uses inside the same method were left on the raw argument:

  • line 228: if (isRootSpelling(path)) — still raw. It happens to be safe today only because denotesRootPath does its own textual .. resolution, i.e. the correctness of this branch depends on a second, independent normalizer rather than on the canonical value this commit just introduced.
  • line 251: defaultBackend.ls(runtimeContext, AbstractFilesystem.normalizeEnumerationSegments(path)) — re-normalizes the raw argument instead of using canonical, so the same string is normalized twice per call on an enumeration hot path, and the two sites can drift if the guard above is ever tightened (they already disagree for the /x/. case in my other comment: canonical would be /memories/. today, and line 251 computes the same, but line 208's route decision and line 228's root test are then made from different strings than the value the backend receives).

grep (line 375) and glob (line 371/393) are already consistent — they route on canonical and delegate canonical. Doing the same in ls (isRootSpelling(canonical) at 228, defaultBackend.ls(runtimeContext, canonical) at 251) makes the "normalize once at the top" claim in the comment true for all three surfaces, which is the point of the change.

Comment on lines +110 to +114
LsResult routed = composite.ls(RT, "/memories");
assertTrue(routed.isSuccess() && !routed.entries().isEmpty());
Path bobFile = workspace.resolve("bob");
assertFalse(Files.exists(bobFile), "nothing may be created outside the workspace");
}

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 table — it pins the forms that mattered (/alice/../bob, //a//b, C:\a\..\b, relative .. staying literal so the backend guard still fires) and the assertSame byte-fidelity row is the right way to lock in the store-key fix.

Two rows would have caught the gap in my AbstractFilesystem comment and keep the fast path and slow path provably equivalent:

{"/memories/.", "/memories"}, // trailing lone dot must still be stripped
{"/a/.hidden", "/a/.hidden"}, // a real dotfile name is not a "." segment

The distinction between those two rows is precisely what contains("./") cannot express, so having both in the table documents why the guard needs an endsWith(".") clause rather than a contains one.

@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

Delta re-review of 4de8f3a9..d172dfbb (1 commit, 3 files, +145/-14) — the follow-up round to my previous review on this PR. All four findings from that round are genuinely resolved, and resolved the way they were proposed: normalizeEnumerationSegments is hoisted to the top of ls/grep/glob, the routing decision now runs on the canonical string, a clean path is returned byte-for-byte (which is what protects a RemoteFilesystem literal store key from being rewritten), relative .. stays literal so the backend's own traversal guard still fires, and there is a table-driven test plus a route-escape integration test. routedPrefixWithTraversal_cannotEscapeTheRoute is the one I'd have written: it asserts both that /memories/../bob cannot reach the route backend and that the route store is never touched and that nothing appears outside the workspace.

Two follow-ups keep this at COMMENT rather than APPROVE, and the first one is a regression introduced by the new fast path itself:

  • AbstractFilesystem.java:97 — the passthrough predicate misses a trailing lone . segment. "/memories/." has no \, no "../", no "//", and does not end in / or .., so it is now returned unchanged where the resolver it short-circuits stripped it to "/memories". Proven by compiling the shipped method and diffing it against the pre-commit resolver over 511 generated spellings: 5 divergences, all that one shape ("/.", "a/.", "/a/b/."), and 0 after adding && !path.endsWith("."). Not a traversal hole (.. is always caught, since a .. segment either has a / after it or terminates the string) — but through ls with a /memories/ route it makes the backend ask for key "/." instead of "/", i.e. the same literal-key miss as #3378 from the clean side. endsWith(".") cannot over-trigger: "/a/.hidden" does not end in a dot, and I confirmed that against the same corpus.
  • CompositeFilesystem.java:208 — the normalize-once claim holds for the routing check but not for the whole method: the root-aggregation branch at line 228 still tests raw path, and line 251 re-normalizes instead of reusing canonical (grep has the same split at 319; glob is the consistent one). Observable on "a/..", which canonicalises to ".": the route branch is skipped (canonical is root), the aggregate branch is skipped too (denotesRootPath only resolves .. for absolute paths), so it falls through to defaultBackend.ls(ctx, "."). ls("a/..") therefore enumerates the default backend alone while ls("/"), ls("//") and ls("/tmp/..") enumerate default plus every route — the #3253 divergence, entered from a relative spelling instead of a route. Visibility inconsistency, not an escape: the delegation is still normalized.

Findings

  • [Warning] AbstractFilesystem.java:97-108 — fast-path predicate misses trailing /., regressing normalization of that spelling into a store-key miss.
  • [Warning] CompositeFilesystem.java:203-208 (and 228/251, 319) — canonical used for routing but raw path for the root test, so "a/.." bypasses the aggregate branch.
  • [Info] NormalizeEnumerationSegmentsTest.java:110-114 — two table rows (/memories/. and /a/.hidden) would pin fast/slow equivalence.

Gate state at d172dfbb: license/cla signed, Check License / Check Module Sync / build (ubuntu-latest) / build (windows-latest) / codecov/patch all green, MERGEABLE/CLEAN, reviewDecision=APPROVED. Nothing here blocks the maintainer on containment or CI grounds; the fast-path clause is the one I'd want in before merge, since it is a one-line fix to a behaviour change this commit introduced.


Automated review by github-manager-bot

Comment on lines +97 to +101
// Byte-for-byte passthrough when there is nothing to resolve: POSIX file names may
// legally contain a backslash, and RemoteFilesystem treats the path as a literal
// store key — rewriting an already-clean string would change which key is read
// (#3378 review).
if (!path.contains("\\")

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 byte-for-byte guard is the right mechanism — this is what stops a clean literal RemoteFilesystem store key from being rewritten — but its predicate misses one shape: a trailing single-dot segment. "/a/b/." has no \, no "./" (the . is last, so the pair never occurs), no "../", no "//", does not end with /, does not end with .. → it now returns unchanged, where the resolver it short-circuits produced "/a/b".

I checked this by compiling the shipped method and diffing it against the pre-d172dfb resolver over every spelling built from ., .., // and mixed separators (511 cases):

INPUT              OLD(slow only)     NEW(fast path)     DIFFER
"/memories/."      "/memories"        "/memories/."      YES
"notes/."          "notes"            "notes/."          YES
"/a/b/."           "/a/b"             "/a/b/."           YES
"/."               "/"                "/."               YES   (still root-equivalent)

All 5 divergences are that one shape. It is not a traversal hole — .. is always caught, because any .. segment is either followed by / ("../") or terminates the string (endsWith("..")) — so this is a correctness regression, not a containment one. But it lands squarely on the invariant this PR exists to hold. Through CompositeFilesystem.ls with a /memories/ route, "/memories/." now reaches routeForPath un-normalized: the prefix matches and the suffix is ".", so the backend is asked for "/." instead of "/" — a literal key miss on a remote store for a path that used to list the route root. That is the same class of failure as #3378, arriving from the clean side instead of the crafted side.

One clause closes it:

&& !path.endsWith("/")
&& !path.endsWith(".")   // "/a/b/." and bare "."; "/a/.hidden" is untouched either way

endsWith(".") cannot over-trigger: a legitimate dotfile name ("/a/.hidden") does not end in ., and I re-ran the same 511-case corpus with the clause added — divergences drop to 0, so the fast path becomes provably equivalent to the slow resolver rather than merely equivalent in the cases the table happens to list.

Comment on lines +203 to +208
String canonical = AbstractFilesystem.normalizeEnumerationSegments(path);
// All root spellings are equivalent and take the aggregated root — checked BEFORE
// route resolution so a configured "/" route cannot capture ls("/") and make the
// spellings diverge (review follow-up, #3253). Non-root paths route as usual; null
// matches no route and falls through to the aggregate below.
if (!isRootSpelling(canonical)) {

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.

ls is the only one of the three surfaces whose normalize-once claim in the comment above is not actually true for the whole method: the routing check here uses canonical, but the root-aggregation check still tests the raw argument — if (isRootSpelling(path)) at line 228 — and the final delegation re-normalizes instead of reusing canonical (normalizeEnumerationSegments(path) at line 251). grep has the same split (path at 319, canonical at 322/375); glob is the consistent one (374 and 393 both canonical).

The mixed source is observable on a relative spelling that resolves to the anchor. normalizeEnumerationSegments("a/..") returns "." (the .. pops the real a segment, parts ends empty and non-absolute), so:

  • the route branch here is skipped — isRootSpelling(canonical) is true;
  • the aggregate branch at 228 is also skipped — denotesRootPath("a/..") is false, because it only resolves .. for paths that start with /;
  • execution falls through to defaultBackend.ls(ctx, ".").

Net: ls("a/..") enumerates the default backend alone, while ls("/"), ls("//"), ls("/tmp/..") — every spelling that reaches this file's root test already normalized — enumerate the aggregate of default plus every route. Two callers asking for the same location get different visibility. It is the same #3253 divergence, just entered from a relative path instead of from a "/" route, and it is not an escape (the delegation is still normalized, nothing leaves the anchor). Worth a reply on this PR because it is a follow-up to the same comment I raised about the route check — the point was one canonical string per call, and inside ls there are still two competing ones.

Both spots become canonical and the invariant matches the comment.

Comment on lines +110 to +114
LsResult routed = composite.ls(RT, "/memories");
assertTrue(routed.isSuccess() && !routed.entries().isEmpty());
Path bobFile = workspace.resolve("bob");
assertFalse(Files.exists(bobFile), "nothing may be created outside the workspace");
}

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 table is good and the assertSame byte-fidelity row is exactly the right way to pin the store-key contract — plus relativeTraversalStaysLiteralSoTheGuardFires and routedPrefixWithTraversal_cannotEscapeTheRoute cover the containment side properly.

Two rows would have caught the gap in my first comment and keep the fast path provably equivalent to the slow resolver rather than equivalent-in-the-listed-cases:

{"/memories/.", "/memories"}, // trailing lone dot must still be stripped
{"/a/.hidden", "/a/.hidden"}, // a real dotfile name is not a "." segment

The distinction between those two rows is precisely what contains("./") cannot express — the first ends in a dot segment, the second only contains a dot — so having both present documents why the guard needs an endsWith(".") clause rather than a contains clause.

@oss-maintainer

oss-maintainer commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

Correction to my first review comment on d172dfbb

Two reviews were posted on this commit; the second (5387957854) is the accurate one. Nothing is being deleted — this states plainly what was wrong in the first (5387909379).

The affected-surface list was wrong. The first review stated that ls was the only one of the three surfaces that does not actually normalize once, and that grep (line 375) and glob (line 371/393) were already consistent. Both halves of that are wrong:

  • the root-aggregation branch tests the raw argument in both ls (line 228) and grep (line 319);
  • the line-375 citation pointed at code inside glob, not grep.

Only glob (374, 393) uses canonical for both its route test and its root test. So the "a/.." case — normalizeEnumerationSegments("a/..") returns ".", the route branch is skipped because canonical is root-equivalent, the aggregate branch is skipped because denotesRootPath only resolves .. for absolute paths, and execution falls through to the default backend with "." — applies to two readers, not one. Neither case is an escape; both are visibility inconsistencies, and the fix is the same (isRootSpelling(canonical) in both places).

The count, for the record, since it is the number the proposed fix rests on: compiling the shipped predicate against the pre-commit resolver and diffing every spelling built from ., .., //, x. and mixed separators gives 5 divergences out of 511 cases, all of them the trailing-lone-. shape ("/.", "a/.", "b/."), and 0 after adding && !path.endsWith("."). "/a/.hidden" fails every guard clause including endsWith("."), so genuine dotfile names still pass through untouched — the clause cannot over-trigger.

That is the whole correction. The primary finding stands as written in either pass: the passthrough predicate misses a trailing . segment, so "/memories/." is returned unchanged where the resolver it short-circuits produced "/memories" — a literal store-key miss through routeForPath, arriving from the clean side rather than the crafted one, and the one thing I would want fixed before merge. The two suggested table rows ({"/memories/.", "/memories"}, {"/a/.hidden", "/a/.hidden"}) still stand as the way to pin that equivalence.

Findings right, scope wrong. Apologies for the two-pass noise on a commit you pushed in good faith.


Automated review by github-manager-bot

@jujn jujn added the P1 紧急不重要 label Nov 4, 2026
@aiyili
aiyili force-pushed the fix/root-containment branch from d172dfb to 170b138 Compare November 11, 2026 14:05
@aiyili

aiyili commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

All three points of the 10-02 review are addressed in 170b1383 (plus a rebase onto current main, which resolves the merge conflict — the branch is 4 clean commits on dee7a210 now):

1. Trailing lone-dot segment (AbstractFilesystem) — exactly the regression you found, including the 511-case diff: the guard's endsWith("..") is now endsWith("."), which subsumes .. and catches /memories/. (no ./ pair occurs when the dot is last). A real dotfile name /a/.hidden still passes through byte-identical. The guard comment now spells out why contains("./") cannot express this distinction.

2. normalize-once made true for all three surfaces (CompositeFilesystem) — ls and grep now test isRootSpelling(canonical) (line 228/319 previously raw) and ls's final delegation reuses canonical instead of re-normalizing the raw argument. Beyond the drift risk you flagged, this closes an observable inconsistency: ls("a/..") — canonical resolves to "." — previously skipped route resolution (correctly) but then failed the raw-argument root check and fell through to default-backend delegation, silently dropping route entries that ls(".") shows. With the single-source check it now takes the aggregated root like every other root spelling. grep("a/..") had the same split.

3. Test rows — added {"/memories/.", "/memories"} and {"/a/.hidden", "/a/.hidden"} to the table, with a comment stating these two rows are precisely what a contains("./") guard cannot express.

Validation: harness module full suite 1639/1639 green locally on the rebased head (the 37 skips are the pre-existing shell-integration tests gated on real hardware). Spotless applied; the rebase kept upstream's sessionStorage() additions intact (the only textual conflicts were additive on both sides).

@aiyili
aiyili force-pushed the fix/root-containment branch from 170b138 to 7657cf9 Compare November 11, 2026 14:12
CompositeFilesystem 对 ls 的根分支与 grep 的 "/" 向 default backend 传
绝对路径,UNRESTRICTED 解析器原样放行,操作锚定 OS 根——默认配置下
list_files(".") 枚举盘根(agentscope-ai#3253)。

- rootAnchor/normalizeEnumerationPath/denotesRootPath:全部根拼写
  (含 "/."、"//"、"/tmp/.." 等根等价形式)统一锚定 backend 自身根,
  命名空间后端保持 {workspace}/{userId} 租户隔离
- ls/grep/glob 的根拼写检查先于路由解析,配置了 "/" 路由时四种拼写
  等价;routed sandbox 的 grep 不再递归容器根(BaseSandboxFilesystem
  rootAnchor 锚定沙箱工作目录)
- RemoteFilesystem ls/grep/glob 统一枚举根锚点,ls 保留尾分隔符前缀
  语义(非根目录列表不丢文件、不泄漏兄弟前缀)
- AbstractFilesystem.ls javadoc 写明枚举面根拼写契约

测试:租户隔离/根等价/沙箱锚定/remote 直连等全部覆盖。

Fixes agentscope-ai#3253
- AbstractFilesystem 新增 normalizeEnumerationSegments():按段折叠
  ./..;绝对输入 "alice/../bob" → "/bob",相对输入保持相对(越界的
  ".." 保留字面,backend 的遍历守卫照常抛 SecurityException)
- CompositeFilesystem ls/grep/glob 的非根 fall-through 转发规范化
  后的路径:namespaced UNRESTRICTED backend 的绝对路径直通不再能被
  /alice/../bob 弹出命名空间锚点
- 与并行引入的相对 ../ 拒绝语义(SecurityException)并存互补

Fixes agentscope-ai#3378
- normalizeEnumerationSegments 加字节保真短路:无 ./ ../ // 尾/ 尾..
  及反斜杠时原样返回——干净字符串与 RemoteFilesystem 字面 store key
  不再被重写
- ls/grep/glob 三处把规范化提升到方法顶部(isRootSpelling/routeForPath
  之前):路由分支("/memories/../bob" 不再以 "/../bob" 直达路由
  backend)、glob 缺口、default 分支一次覆盖;根拼写聚合判定用规范化
  后的字符串
- normalizeEnumerationSegmentsTest:表驱动(绝对/相对/Windows 拼写/
  null)+字节保真+相对越界保留字面(守卫照常抛)+经路由 composite 的
  集成用例(/memories/../bob 不可越路由,route store 零触碰)
- normalizeEnumerationSegments 快路径守卫:endsWith(".") 替代 endsWith(".."),
  覆盖 '/memories/.' 这类无 './' 配对但需剥离尾部点段的拼写;真实点文件名
  ('/a/.hidden') 不受影响仍字节保真直通
- ls/grep 的根判定改用 canonical,与路由决策同源:相对拼写解析到锚点
  ('a/..' -> '.') 时不再漏掉路由聚合分支
- ls 尾部委派复用 canonical,规范化每调用恰好一次,两处位点不再漂移
- 测试表补 '/memories/.' -> '/memories' 与 '/a/.hidden' 原样两行,
  钉住 contains('./') 表达不了的区分

harness 模块全套件 1639/1639 绿
@aiyili
aiyili force-pushed the fix/root-containment branch from 7657cf9 to 1ada3fb Compare November 27, 2026 01:44
@aiyili

aiyili commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main as 1ada3fb3; the old head is kept on backup/pr-3254-before-rebase. The only conflict was the import block of CompositeFilesystemTest (both sides added imports). git range-diff against the previous head shows the four patches unchanged apart from context lines.

agentscope-harness suite on current main on Windows: 2288 tests, 0 failures. On Linux the same suite has two failing cases, BaseSandboxFilesystemTest.edit_fileNotFound and MarketplaceStagerOrphanGcTest.unreadableEntryDoesNotFailStage; both fail identically on unmodified main in the same environment (a container running as root), so they are not from this change.

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.

[Bug] CompositeFilesystem root ls/grep escape the workspace under the UNRESTRICTED default backend (list_files(".") enumerates the drive root)

3 participants