Skip to content

[Bug]: In sandbox mode, shell writes to AGENTS.md / skills/ / MEMORY.md override host definitions and persist across calls #3388

Open

Description

@xuchaoguo1983

Describe the bug

In sandbox filesystem mode, workspace definition files (AGENTS.md, skills/, MEMORY.md) are read with "sandbox filesystem first, host workspace as fallback" (WorkspaceManager.readWithOverride). The same sandbox is writable by the model through the execute (shell) tool. As a result, any file the model writes at those paths inside the sandbox replaces the host-provided definition in the system prompt of all later calls for that isolation slot, and it persists through snapshots.

The workspace projection does not restore the host version either: AbstractBaseSandbox.applyWorkspaceProjectionIfChanged compares the host payload hash with the last applied hash stored in the sandbox state, not with the files currently in the sandbox, so a modified file is kept until the host files change.

In remote/local filesystem mode an application can prevent this by denying write_file / edit_file. In sandbox mode there is no equivalent: an application that needs execute (e.g. code interpreter scenarios) cannot keep the agent definition host-authoritative. Combined with prompt injection from untrusted content, a single shell command can persistently change the agent's persona and skills for that user.

The docs describe projection as host -> sandbox one-way sync, so the host version appears to be intended as the source of truth.

To Reproduce

  1. Build a HarnessAgent with DockerFilesystemSpec (python:3.12-slim, LocalSnapshotSpec, IsolationScope.USER); host workspace contains AGENTS.md with HOST-PERSONA.
  2. Call 1 (user u1, session s1): the model calls execute with echo INJ-PERSONA > AGENTS.md; mkdir -p skills/x; printf -- '---\nname: x\ndescription: INJ-SKILL\n---\n' > skills/x/SKILL.md.
  3. Call 2 (user u1, new session s2): inspect the system prompt sent to the model.

Expected behavior

The system prompt keeps HOST-PERSONA and the host skill set; the sandbox copy of host-projected definition files is either read-only, restored on each call, or not used as an override. Alternatively, an option to make projected roots host-authoritative in sandbox mode.

Actual behavior

System prompt of call 2 contains INJ-PERSONA instead of HOST-PERSONA, and the skill list contains the injected skill. The same happens for content appended to MEMORY.md via shell (bypassing memory_save). Other users are not affected (isolation works).

Environment

  • AgentScope-Java Version: 2.0.3 (agentscope-harness; also checked with agentscope-extensions-sandbox-e2b 2.0.3)
  • Java Version: 21
  • OS: macOS (Docker via OrbStack)

Additional context

Related but different: #2654 (persistence semantics of MEMORY.md in sandbox), #3192 (sandbox system prompt paths).

Activity

  1. xuchaoguo1983 commented on Oct 2, 2026

    @xuchaoguo1983
    Author

    Related: #3317 (workspace definition paths cannot be made read-only to the model; file tools have no per-path rules). This issue is the sandbox-mode variant of that gap: there the protection can be approximated by denying write_file / edit_file, but in sandbox mode the execute shell bypasses file tools entirely, and the workspace projection does not restore modified files because it only compares the host payload hash. A fix for either issue alone would not cover the other.

  2. oss-maintainer commented on Oct 2, 2026

    @oss-maintainer
    Collaborator

    Issue Evaluation

    Category: bug | Status: Confirmed (engine-verified against main @ 915507134453)

    All three claims in the report check out in the current code:

    1. Sandbox-first reads. WorkspaceManager.readWithOverride (agentscope-harness/.../workspace/WorkspaceManager.java:818-824) reads through the configured filesystem first and only falls back to the host when that returns empty. In sandbox mode that filesystem is SandboxBackedFilesystem (wired in HarnessAgent.java:2463-2468, :2498-2499) and its read runs sed inside the container (BaseSandboxFilesystem.java:132-192). AGENTS.md (:252), KNOWLEDGE.md (:257), MEMORY.md (:262) and additional context files (:269-282) all go through this path into the system prompt via WorkspaceContextMiddleware.buildWorkspaceSection (:219-256). Layer-4 WorkspaceSkillRepository(filesystem, "skills", ...) (HarnessAgentBuilderSupport.java:912-916) globs SKILL.md the same way, so the skill catalog is affected too.
    2. Projection does not restore. AbstractBaseSandbox.applyWorkspaceProjectionIfChanged (AbstractBaseSandbox.java:267-287) compares the host payload hash (WorkspaceProjectionApplier.java:64-87) against the last-applied hash stored in SandboxState (SandboxState.java:43) — never against what is actually in the sandbox. A tampered copy therefore survives until the host file changes, and stop() snapshots it (AbstractBaseSandbox.java:132-141), so it persists across sessions in the same isolation slot.
    3. The shell tool can write those paths. ShellExecuteTool.execute (ShellExecuteTool.java:50-79) has no path/command guard; DockerSandbox.doExec runs docker exec -w <workspaceRoot> sh -c <cmd> (DockerSandbox.java:150-158).

    Impact: prompt-integrity / persistence vector in agentscope-harness sandbox mode (DockerFilesystemSpec, K8s, E2B, AgentRun, Daytona). A single shell command — e.g. from prompt injection in untrusted content — can permanently replace the agent persona, inject skills, and append to MEMORY.md bypassing memory_save, for that isolation slot. Host files themselves are not modified; with IsolationScope.USER other users are unaffected, but under AGENT/GLOBAL scope the tampering is shared. Severity: high. No existing fix on main; no open PR references this issue.

    Automated Fix Proposal (v1) — code base 915507134453 (main)

    In short: make host-projected definition roots host-authoritative in sandbox mode, and make projection tamper-aware.

    • Part A — host-authoritative reads: for projected definition roots (AGENTS.md, KNOWLEDGE.md, MEMORY.md, skills/, …) resolve content from the host workspace only (no sandbox override), keeping the sandbox writable for everything else.
    • Part B — tamper-aware re-projection: re-hydrate not only when the host payload hash changed, but also when the sandbox-side copy of the last-applied payload diverges (per-file SHA-256 check, one chunked exec per sandbox start, fail-safe to re-hydrate).
    • Escape hatch: hostAuthoritativeDefinitions(false) restores the exact legacy behavior (self-learning-skills / sandbox-side persona workflows); default flips to the secure behavior with a documented migration note, and docs (docs/v2/en + docs/v2/zh) are updated in the same PR.
    • Tests: extend WorkspaceProjectionApplierTest + a regression test that mirrors the repro (shell-write AGENTS.md and skills/x/SKILL.md, then a new session in the same isolation slot, assert host definitions win).
    Full specification (spec_v1.md, 366 lines)

    Fix Specification — agentscope-java issue #3388

    Issue: [Bug]: In sandbox mode, shell writes to AGENTS.md / skills/ / MEMORY.md override host definitions and persist across calls
    Status: verified — confirmed, root cause reproduced with file/line evidence (verification_result.md)
    Severity: high (prompt-integrity / persistence vector; cross-session, and cross-user under AGENT/GLOBAL isolation)
    Module: agentscope-harness (sandbox filesystem mode: SandboxFilesystemSpec incl. DockerFilesystemSpec, K8s, E2B, AgentRun, Daytona)
    Shape: one PR, no architectural rewrite, no reliance on mount-level read-only

    Fix in one paragraph. In sandbox mode, treat host-projected definition roots as authoritative: (a) agent-context reads for those roots resolve from the host workspace only (no sandbox fallback) while the sandbox stays writable; (b) workspace projection is re-applied not only when the host payload hash changes but also when the sandbox copy of the last-applied payload diverges (per-file SHA-256 verification, one chunked exec per sandbox start); (c) an explicit hostAuthoritativeDefinitions(false) opt-out preserves exact legacy behavior. All additions are backward-compatible API additions; the default flips to the secure behavior (documented in §5 with a migration note).


    1. Root Cause Analysis

    1.1 Defect A — definition reads are "sandbox-first, host fallback"

    WorkspaceManager.readWithOverride reads through the configured AbstractFilesystem first and only falls back to host disk when the filesystem returns empty:

    • agentscope-harness/src/main/java/io/agentscope/harness/agent/workspace/WorkspaceManager.java:818-824 — readWithOverride (fs first at :819-822, host fallback :823)
    • Callers: readAgentsMd :251-253, readKnowledgeMd :256-258, readMemoryMd :261-263, readManagedWorkspaceFileUtf8 :269-282 (returns readWithOverride at :281, also used at :707)

    These feed the system prompt via WorkspaceContextMiddleware:

    • agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/WorkspaceContextMiddleware.java:206-217 (onSystemPrompt) → :219-256 (buildWorkspaceSection): AGENTS.md at :220, MEMORY.md at :223, KNOWLEDGE.md at :224; additional context files at :550-565.

    In sandbox mode the configured filesystem is sandbox-backed:

    • agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java:2463-2468 — SandboxBackedFilesystem (or RoutedSandboxFilesystem wrapping it) becomes the agent filesystem; passed into WorkspaceManager at :2498-2499.
    • Reads execute as shell commands inside the container: filesystem/sandbox/BaseSandboxFilesystem.java:132-192 (text read = sed -n via execute, :159-172), filesystem/sandbox/SandboxBackedFilesystem.java:100-120 (execute → live sandbox).
    • The model can write those same paths through the shell tool: tool/ShellExecuteTool.java:44-90 (no command/path guard; only an advisory description) → SandboxBackedFilesystem.execute → DockerSandbox.doExec runs docker exec -w <workspaceRoot> sh -c <command> (sandbox/impl/docker/DockerSandbox.java:145-158).

    So the "filesystem override" layer is, in sandbox mode, model-writable: a shell echo … > AGENTS.md shadows the host persona on every subsequent read.

    Skills use the same mechanism with the highest repository priority:

    • Layer-4 WorkspaceSkillRepository(filesystem, "skills", "workspace-namespaced") is composed at agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.java:909-916 and wired at HarnessAgent.java:2786-2789.
    • Listing reads SKILL.md via sandbox glob + read: skill/WorkspaceSkillRepository.java:149-186.
    • The catalog merges repositories "in compose order; later entries with the same name win" (middleware/HarnessSkillMiddleware.java:352-384, :380) — so the sandbox layer wins over the host-disk Layer 3 (HarnessAgentBuilderSupport.java:896-907) and sandbox-only skills are added.

    (Subagent declarations have the same shape — subagent/AgentSpecLoader.java:157-172 globs/reads subagents/ through the filesystem — but are out of the required fix scope; see §2.7.)

    1.2 Defect B — projection "skip if unchanged" compares host hash with last applied hash, never with the sandbox

    • Payload is built from host files only: sandbox/WorkspaceProjectionApplier.java:50-88 (digest over sorted (relativePath, content) pairs, :64-87; record at :155).
    • sandbox/AbstractBaseSandbox.java:267-287 (applyWorkspaceProjectionIfChanged): if payload.hash() equals state.getWorkspaceProjectionHash() the method returns at :273-276 without looking at the sandbox; hydration happens only on host-content change (:277-281); the hash stored is the applied hash (:282).
    • The stored hash lives in serialized sandbox state: sandbox/SandboxState.java:43 (field), :70-76 (accessors).
    • Start-order: the check runs at the end of start() (AbstractBaseSandbox.java:116), after the 4-branch restore (:69-124).

    Consequence: a tampered /workspace/AGENTS.md (or skills/**) is retained forever as long as the host file set is unchanged, because the skip condition only compares host↔host-history.

    1.3 Why tamper persists across calls and sessions

    • stop() snapshots the whole sandbox workspace (AbstractBaseSandbox.java:131-141), so the tampered copy is archived.
    • State (including workspaceProjectionHash) and snapshot id are persisted per isolation slot: sandbox/SandboxManager.java:100-130 (resume; the current WorkspaceSpec is re-attached at :112-115, the projection hash is not reset), :214-252 (persistState); driven by middleware/SandboxLifecycleMiddleware.java:100-154 (acquire + start()) and :162-190 (release + persist).
    • IsolationScope.USER keys on userId (sandbox/SandboxIsolationKey.java:78-82), so a new session for the same user resumes the tampered sandbox and re-hydrates nothing.

    1.4 Repro trace (call 1 → call 2)

    Step Code path
    Call 1: model shells echo INJ-PERSONA > AGENTS.md; mkdir -p skills/x; printf … > skills/x/SKILL.md ShellExecuteTool.execute → DockerSandbox.doExec (ShellExecuteTool.java:50-79, DockerSandbox.java:145-158)
    Call 1 end: sandbox stopped, workspace snapshotted, state+hash persisted AbstractBaseSandbox.java:131-141, SandboxManager.java:214-252
    Call 2 (user u1, session s2): state resumed, sandbox restored from snapshot SandboxManager.java:100-121, SandboxIsolationKey.java:78-82
    Projection skipped (host hash == stored hash) → tampered copy survives AbstractBaseSandbox.java:273-276
    AGENTS.md read sandbox-first → INJ-PERSONA WorkspaceManager.java:818-824 via WorkspaceContextMiddleware.java:220
    Skills catalog globs sandbox skills/ → injected x appears WorkspaceSkillRepository.java:149-186, HarnessSkillMiddleware.java:352-384

    1.5 Why existing knobs don't address it

    • workspaceProjectionEnabled / workspaceProjectionRoots control what is projected, not read authority or tamper handling (filesystem/spec/SandboxFilesystemSpec.java:41-48, :97-108, :127-141).
    • BindMountEntry.readOnly exists (sandbox/layout/BindMountEntry.java:35-55) but the default projection is a writable tar-hydrate (sandbox/layout/WorkspaceProjectionEntry.java:30-57; WorkspaceSpecApplier.java:130-132 skips projection entries), and cloud backends ignore bind mounts.
    • The documented contract is host → sandbox one-way: "the framework tars the workspace's static assets and hydrates them into /workspace" (docs/v2/en/docs/harness/filesystem.md:282-292, docs/v2/en/docs/harness/workspace.md:271-285, docs/v2/en/docs/harness/skill.md:355-373). The host is the source of truth; the current skip check just fails to enforce that.

    2. Fix Strategy

    Minimal, reviewable change set built from three cooperating parts plus one option:

    Part Change Default
    A. Read authority Definition roots resolve from host; no sandbox fallback (WorkspaceManager, WorkspaceSkillRepository) ON
    B. Tamper-aware re-projection Verify sandbox-side content of the last-applied payload at every sandbox start; re-hydrate on divergence (WorkspaceProjectionApplier, AbstractBaseSandbox) ON
    C. Opt-out SandboxFilesystemSpec.hostAuthoritativeDefinitions(false) restores exact legacy behavior flag default true

    Semantics of host-authoritative mode (flag true): for the configured definition roots (= workspaceProjectionRoots, default AGENTS.md, skills, subagents, knowledge, .skills-cache), a sandbox-side file can neither override nor extend host definitions in agent context, and the last applied projection payload is restored into the sandbox whenever it diverges. The sandbox remains freely writable (no shell guards) — tamper is neutralized, not prevented.

    Step 1 — Host-first reads in WorkspaceManager (Part A, scalar files)

    File: agentscope-harness/src/main/java/io/agentscope/harness/agent/workspace/WorkspaceManager.java

    1. Add a field + setter, default empty (zero behavior change when unset):

      private volatile List<String> hostAuthoritativeRoots = List.of();
      public void setHostAuthoritativeRoots(List<String> roots) { /* normalize, copy, List.of() when null */ }
    2. Add a public static prefix matcher (shared with wiring/tests): isUnderRoot(String relativePath, String root) — exact match or startsWith(root + "/") after normalizing \ → /, stripping leading ./ and trailing /.

    3. Change readWithOverride (:818-824) to:

      private String readWithOverride(RuntimeContext rc, String relativePath) {
          if (isHostAuthoritative(relativePath)) {
              Path host = workspace.resolve(relativePath).normalize();
              if (host.startsWith(workspace) && Files.isRegularFile(host)) {
                  return readFileQuietly(host);   // host exists (even empty) -> authoritative, no fs fallback
              }
              // Host does not define this path: fall through to the filesystem only when the
              // file is NOT under an authoritative root? No — under authority, host-absence means absence:
              return "";
          }
          String fsContent = readTextThroughFilesystem(rc, relativePath);
          return !fsContent.isEmpty() ? fsContent : readFileQuietly(workspace.resolve(relativePath));
      }

      Decision (documented): under host authority there is no sandbox fallback for a path under an authoritative root. A sandbox-only AGENTS.md / skill file is not a legitimate definition source; falling back would reopen the injection vector whenever the host file is missing. A host file that exists but is unreadable yields "" via readFileQuietly (fail-closed to "no definition", same as today's missing-host behavior).

    4. Make listKnowledgeFiles (:296-…, fs-union at :300-309) host-only when knowledge is authoritative: skip the filesystem.glob half and keep the host walk, so injected knowledge/** files neither appear in the prompt's knowledge list nor in readKnowledgeMd resolution.

    5. Do not touch non-projected runtime paths: MEMORY.md, memory/**, tools.json, agents/**, sessions/** keep fs-first semantics (MemoryConsolidator.java:160, MemoryFlushManager.java:239, ToolsConfigLoader (reads tools.json), etc.). Memory lives in the sandbox by design (docs/…/workspace.md:284); curation bypass via shell is issue [Question] Inconsistent persistence semantics: sessions/*.jsonl (local-first) vs MEMORY.md (sandbox-only) in e2b scenario #2654, not this fix.

    Covers: AGENTS.md, knowledge/KNOWLEDGE.md, knowledge listing, additional context files under roots, and any readManagedWorkspaceFileUtf8 path under roots.

    Step 2 — Host-authoritative directory in WorkspaceSkillRepository (Part A, skills)

    File: agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/WorkspaceSkillRepository.java

    Do not wrap the repository in a decorator class. MarketplaceStager.stageAll special-cases bound.repo() instanceof WorkspaceSkillRepository → StageResult.WorkspaceNative (skill/runtime/MarketplaceStager.java:222-226); a wrapper would change <files-root> from /workspace/skills/<name> to a .skills-cache staging path and require resources. Extend the class itself instead — the flag-configured instance keeps its type, source string, and write path.

    1. Add nullable field + accessors (default null = legacy):

      private volatile Path hostAuthoritativeDir;
      public void setHostAuthoritativeDir(Path dir) { … }
      public Path getHostAuthoritativeDir() { … }
    2. In getAllSkills(RuntimeContext) (:149-186): when hostAuthoritativeDir != null, list SKILL.md files by walking the host directory (same metadata-dir skip rule as hasMetadataAncestor, :503-515), build AgentSkill via SkillUtil.createFrom(content, null, this.source) — i.e. host content only; sandbox-only skills (e.g. shell-injected skills/x/SKILL.md) are excluded. Host dir missing/empty → empty list. getSkill, getAllSkillNames, skillExists inherit the behavior (they delegate to getAllSkills).

    3. Leave the write path and lazy resources untouched: save/delete/writeSkillFile/resourcesFor still go to the sandbox filesystem, and resourcesFor keeps returning sandbox paths (:222-229) so the <files-root> /workspace/skills/<name> rendering and script execution stay valid (content is host-identical because of Part B).

    4. Wiring (set at construction, not post hoc):

      • HarnessAgentBuilderSupport.composeSkillRepositories (:909-916): when b.sandboxFilesystemSpec != null, isHostAuthoritativeDefinitions() and the roots list contains exactly skills, call repo.setHostAuthoritativeDir(wsManager.getSkillsDir()).
      • HarnessAgent.java:2801-2821 (skill_manage replacement): when the non-writable layer-4 repo is replaced by the writable WorkspaceSkillRepository(filesystem, smConfig.mainDir(), …), copy the config over when smConfig.mainDir() equals an authoritative root exactly ("skills"; SkillManageConfig.DEFAULT_MAIN_DIR, tool/SkillManageConfig.java:32-35).
      • Never configure the drafts repo (skills/_drafts) or any repo whose relative dir is below a root: promotion/draft flows (SkillPromoter, SkillManageTool) read drafts from the sandbox and must keep doing so.

    Expected strict-mode consequences (documented, §5): promoted/agent-created skills under the projected skills root are no longer part of the prompt catalog while hostAuthoritativeDefinitions is on; SkillCurator likewise only sees host skills. Apps that rely on sandbox skill self-learning set the flag to false.

    Step 3 — Per-file digests in the projection payload (Part B, payload)

    File: agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/WorkspaceProjectionApplier.java

    1. Extend the internal record (:155) with a per-file manifest:

      public record ProjectionPayload(
              String hash, byte[] tarBytes, int fileCount, Map<String, String> fileDigests) {}

      fileDigests maps normalized relative path → SHA-256 hex of the file bytes (insertion-ordered, unmodifiable).

    2. build(...): while already reading each file (:68-83), also compute the per-file SHA-256. Do not change the aggregate hash derivation (:64, :73-75, :86) — it is persisted in SandboxState and must stay stable across upgrade to avoid spurious re-hydration (§5).

    Blast radius is small: ProjectionPayload is constructed only here; consumers are AbstractBaseSandbox:267-287 and WorkspaceProjectionApplierTest.

    Step 4 — Tamper-aware re-projection (Part B, enforcement)

    File: agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/AbstractBaseSandbox.java

    Replace the skip check in applyWorkspaceProjectionIfChanged (:267-287) with:

    1. Build payload as today; null → return.
    2. boolean hostChanged = !Objects.equals(payload.hash(), state.getWorkspaceProjectionHash());
    3. Needed = hostChanged || (projectionIsHostAuthoritative(spec) && !projectedContentMatchesSandbox(payload))
    4. If needed and fileCount() > 0 → hydrate (:277-281 unchanged), then state.setWorkspaceProjectionHash(payload.hash()) (:282 unchanged). Log at debug/info which condition triggered ("host payload changed" vs "sandbox copy diverged — restoring").
    5. If not needed → keep the existing debug log.

    projectedContentMatchesSandbox(payload) (new private method):

    • Build one shell command per chunk (chunk size 64 paths; ARG_MAX safety):

      cd '<workspaceRoot>' && sha256sum -- '<rel1>' '<rel2>' … 2>/dev/null
      

      <workspaceRoot> = state.getWorkspaceSpec().getRoot(); paths are payload keys, quoted with filesystem/util/FilesystemUtils.shellQuote (:101); run via doExec(null, cmd, PROJECTION_VERIFY_TIMEOUT_SECONDS) with a new constant (30).

    • Parse sha256sum lines (<hex> <path>), normalize paths, compare the resulting map by exact key set and values to payload.fileDigests(). Missing files, extra parse failures, or any non-zero exit → mismatch.

    • If the hash tool is unavailable (exit 127 / "not found") → log once at WARN and return false (fail-safe: re-hydrate every start on that backend until the tool exists). This trades bandwidth for integrity on exotic images; documented in §6.

    • projectionIsHostAuthoritative(spec) walks spec.getEntries() for the WorkspaceProjectionEntry recursively (mirror the walk in WorkspaceProjectionApplier.collectProjectionEntries) and returns its new flag; defaults to true when the field is absent (pre-upgrade serialized state, hand-built specs).

    Note the ordering guarantees this works for the repro: start() runs before the system prompt is built (SandboxLifecycleMiddleware.acquireForCall → beforeAgentExecution), so at call 2 the divergence is detected and the host copy is restored before any definition read.

    Step 5 — Option and plumbing

    1. agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/layout/WorkspaceProjectionEntry.java (:30-57): add private boolean hostAuthoritative = true; + getter/setter (serialized with the state; Jackson fills the default for old JSON).
    2. agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/spec/SandboxFilesystemSpec.java:
      • add private boolean hostAuthoritativeDefinitions = true; with fluent hostAuthoritativeDefinitions(boolean) + isHostAuthoritativeDefinitions() (next to :97-108);
      • add read accessors isWorkspaceProjectionEnabled() / getWorkspaceProjectionRoots() (currently none) so the wiring can reuse the roots list;
      • in buildWorkspaceSpecWithProjection (:127-141): projection.setHostAuthoritative(hostAuthoritativeDefinitions); — and when hostAuthoritativeDefinitions is false, keep legacy (setHostAuthoritative(false)).
    3. agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java:
      • after the sandbox/filesystem composition (:2459-2497) and before new WorkspaceManager (:2498): when sandboxFilesystemSpec != null && isHostAuthoritativeDefinitions(), resolve the effective roots (minus any path covered by an explicit filesystemRoutes prefix — routes are an explicit app choice and keep their backend) and call wsManager.setHostAuthoritativeRoots(roots);
      • apply the same configuration to the per-user factory managers (:2505-2515, workspaceFactoryFn) so workspaceFor(userId, sessionId) behaves identically;
      • nothing else in HarnessAgent changes; the instanceof dispatch sites (:2708-2709, :2887-2898) are untouched.
    4. Docs (required by repo rules for user-visible behavior change): update docs/v2/en + docs/v2/zh pages — harness/filesystem.md (projection section, :282-292), harness/workspace.md sandbox mode (:271-285), harness/skill.md projection/authority notes (:355-373); document the new flag and the restore semantics.

    Step 6 — Rejected alternatives (for review context)

    • Mount-level read-only (BindMountEntry.readOnly): the default projection is a tar hydrate, not a mount; Docker/cloud backends diverge; task constraint excludes it as the sole mechanism.
    • Shell-level path guard in ShellExecuteTool: trivially bypassed (any interpreter can write files: python -c, redirections via scripts) and would break legitimate code-interpreter workflows. Kept as a possible future defense-in-depth signal only.
    • Whole-filesystem read decorator (route reads under authoritative roots to a host-disk AbstractFilesystem): breaks existing type dispatch (WorkspaceManager.java:453-456, HarnessAgent.java:2708-2709, :2887-2898, WorkspaceContextMiddleware.java:375/411/443-444) and requires exact glob/path-shape equivalence between LocalFilesystem and BaseSandboxFilesystem. Larger risk than the targeted Steps 1–2 for the same guarantee.
    • Blocking save()/promotion in sandbox mode: breaks skill self-learning outright instead of scoping it behind the option.

    Step 7 — Explicit non-goals

    • MEMORY.md / memory/** remain sandbox-owned runtime data (shell appends there stay outside memory curation; tracked by [Question] Inconsistent persistence semantics: sessions/*.jsonl (local-first) vs MEMORY.md (sandbox-only) in e2b scenario #2654). Apps that want a curated host memory seed can add MEMORY.md to workspaceProjectionRoots — with hostAuthoritativeDefinitions on it then becomes host-authoritative and restored.
    • subagents/** content is restored by Part B at each start, but AgentSpecLoader/DynamicSubagentsMiddleware/SubagentsMiddleware keep reading through the live filesystem, so an in-call tamper is still visible within the same call. Flagged as follow-up hardening (route through the Step-1 helper or add a host-first scan when authority is on); not required for the issue's acceptance criteria.
    • Within-call windows in general: tamper + immediate lazy resourcesFor read can still see sandbox content within the same call; because Part B restores at the next start and Part A fixes prompt/catalog reads, this is self-influence, not a persistence vector.

    3. Files to Modify

    All paths relative to the repository root.

    # File Change
    1 agentscope-harness/src/main/java/io/agentscope/harness/agent/workspace/WorkspaceManager.java hostAuthoritativeRoots field/setter, isUnderRoot helper, readWithOverride host-first branch, listKnowledgeFiles host-only branch
    2 agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/WorkspaceSkillRepository.java hostAuthoritativeDir field/accessors, host listing branch in getAllSkills(RuntimeContext)
    3 agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/WorkspaceProjectionApplier.java per-file SHA-256 manifest in ProjectionPayload/build (aggregate hash unchanged)
    4 agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/AbstractBaseSandbox.java tamper-aware applyWorkspaceProjectionIfChanged, projectedContentMatchesSandbox, entry-flag walk, verify constants
    5 agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/layout/WorkspaceProjectionEntry.java hostAuthoritative field (default true) + accessors
    6 agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/spec/SandboxFilesystemSpec.java hostAuthoritativeDefinitions(boolean) (default true), info accessors, set flag on entry
    7 agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.java configure layer-4 skill repo in composeSkillRepositories
    8 agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java wiring: authoritative roots on main + per-user WorkspaceManagers; carry skill config on the skill_manage replacement
    9 docs/v2/en/docs/harness/{filesystem,workspace,skill}.md + docs/v2/zh/… counterparts document host-authoritative mode, new flag, restore semantics

    New test files (module agentscope-harness):

    # File Purpose
    10 src/test/java/io/agentscope/harness/agent/sandbox/AbstractBaseSandboxProjectionTest.java (+ test double LocalDirSandbox in the same package or sandbox/support) Part B unit tests
    11 src/test/java/io/agentscope/harness/agent/workspace/WorkspaceManagerHostAuthoritativeReadsTest.java Part A unit tests for files/knowledge
    12 src/test/java/io/agentscope/harness/agent/sandbox/SandboxDefinitionTamperRegressionTest.java End-to-end repro mirror (§4.3)
    13 optional, gated src/test/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandboxDefinitionTamperIT.java Real Docker repro (§4.4)

    No changes to agentscope-core or agentscope-extensions: every sandbox spec (DockerFilesystemSpec, KubernetesFilesystemSpec, E2bFilesystemSpec, AgentRunFilesystemSpec, DaytonaFilesystemSpec) inherits the new option from SandboxFilesystemSpec.

    Estimated diff: ~350–450 net LOC in main + docs, plus tests.


    4. Test Plan

    4.1 Existing tests to extend

    Test Extension
    agentscope-harness/src/test/java/io/agentscope/harness/agent/sandbox/WorkspaceProjectionApplierTest.java Assert fileDigests() has one SHA-256 entry per projected file with correct values for AGENTS.md/skills/java/SKILL.md; add a golden-value test pinning the aggregate hash() for a fixed input tree (guards the "hash derivation unchanged" backward-compat promise)
    agentscope-harness/src/test/java/io/agentscope/harness/agent/skill/WorkspaceSkillRepositoryTest.java With setHostAuthoritativeDir(hostDir): host-only catalog, sandbox-only skills excluded, host-missing → empty, resourcesFor still delegates to the filesystem; unset → legacy
    agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/WorkspaceContextMiddlewareSandboxPromptTest.java Host-authoritative variant: fake sandbox fs returns injected AGENTS.md/knowledge; prompt must render host content (flag on) and sandbox content (flag off)
    agentscope-harness/src/test/java/io/agentscope/harness/agent/example/SandboxFilesystemIsolationScopeExampleTest.java Leave as-is (isolation regression guard; confirms the fix does not alter resume/create counts)
    agentscope-harness/src/test/java/io/agentscope/harness/agent/HarnessAgentTest.java Build-time wiring: InMemorySandboxFilesystemSpec → wsManager gets the default roots; hostAuthoritativeDefinitions(false) → roots empty and project entry flag false

    4.2 New unit tests (run everywhere, no Docker)

    AbstractBaseSandboxProjectionTest with a test double LocalDirSandbox extends AbstractBaseSandbox (temp dir as workspace root; doExec via sh -c with cwd = root, mirroring InMemorySandbox.exec incl. the Windows cmd /c switch; doHydrateWorkspace via WorkspaceArchiveExtractor.extractTarArchive(destRoot, stream) — sandbox/WorkspaceArchiveExtractor.java:54; doPersistWorkspace tar of the dir; setup/destroy mkdir/rm):

    1. start_unchangedHost_skipsRehydration — count doHydrateWorkspace invocations via a subclass counter; second start() with untouched sandbox → no re-hydrate (fast path preserved).
    2. start_tamperedAgentsMd_restoresHostCopy — tamper AGENTS.md after first start → start() → file bytes equal host; stored hash unchanged.
    3. start_deletedProjectedFile_restores — rm skills/java/SKILL.md → restored.
    4. start_injectedExtraSkillFile_doesNotAffectPayloadMatch — extra skills/x/SKILL.md → verification still "matches" for payload paths (documents that extra files are a catalog-layer concern, covered by Part A), while a modified host-defined skill restores.
    5. start_verifyToolMissing_failsSafe — subclass overriding the verify hook/exec to simulate exit 127 → expects re-hydration and a single WARN (use a log capture or an overridable hook).
    6. start_hostAuthoritativeFalse_skipsVerification — entry flag false → legacy skip (no extra exec; tamper survives — asserts the opt-out is honest).
    7. start_hostFileChanged_stillRehydrates — existing behavior guard.

    WorkspaceManagerHostAuthoritativeReadsTest:

    1. Configured root + tampered fs content → readAgentsMd returns host; unset → sandbox content.
    2. Host file absent + sandbox content present → returns "" under authority (no fallback), legacy returns sandbox content.
    3. Host file empty (0 bytes) + tampered sandbox content → "", not tampered content.
    4. knowledge/ authoritative → listKnowledgeFiles excludes injected sandbox-only files.
    5. Non-projected MEMORY.md unaffected (sandbox-first preserved).
    6. Path normalization: ./skills/x, skills exact, skillsX (prefix must not match on partial segment).

    4.3 Regression test mirroring the repro (required)

    SandboxDefinitionTamperRegressionTest (harness tests, no Docker) — pattern after SandboxFilesystemIsolationScopeExampleTest (Mockito Model stub, @TempDir workspace, agentscope.state.home override, @HarnessQuiescence, InMemorySandboxClient/InMemorySandboxFilesystemSpec):

    1. Host workspace: AGENTS.md = HOST-PERSONA; skills/host-skill/SKILL.md (host skill); state dir per test.
    2. Build HarnessAgent with InMemorySandboxFilesystemSpec, IsolationScope.USER, mock model that (turn 1) emits a tool call to execute with the repro command (echo INJ-PERSONA > AGENTS.md; mkdir -p skills/x; printf -- '---\nname: x\ndescription: INJ-SKILL\n---\n' > skills/x/SKILL.md) and (turn 2) a terminal answer. If driving the full tool loop in the mock is impractical, the fallback is to write the same files directly into the live sandbox workspace dir (InMemorySandbox.getWorkspaceDir()), which is byte-equivalent to a shell write — note which variant was used in the test name/javadoc.
    3. Call 1: agent.call(user u1, session s1) → release persists state.
    4. Call 2: new session s2, same userId → resume count == 1 (same isolation slot).
    5. Assertions on the system prompt captured from the mock model's request:
      • contains HOST-PERSONA, does not contain INJ-PERSONA;
      • skill catalog contains host-skill, does not contain x / INJ-SKILL.
    6. Assert host workspace files are unmodified.
    7. Parametrized/sibling case: same flow with .hostAuthoritativeDefinitions(false) → documents legacy behavior (injected content visible) so the opt-out cannot silently regress.

    4.4 Docker integration test (optional, gated)

    DockerSandboxDefinitionTamperIT mirroring the repro end-to-end with DockerFilesystemSpec (python:3.12-slim, LocalSnapshotSpec, IsolationScope.USER), gated like the existing ones (@EnabledIfSystemProperty(named = "docker.it", matches = "true") + daemon-reachability assumption, cf. DockerSandboxFileTransferIntegrationTest:50-60). Assert: call 2 prompt keeps HOST-PERSONA; cat /workspace/AGENTS.md inside the sandbox equals host content (restore actually happened); injected skill file removed from the catalog (it may still exist on disk — assert catalog, not disk, and document that disk retention of extras is a non-goal).

    4.5 Commands

    mvn -T1 -pl agentscope-harness -am test -Dtest=WorkspaceProjectionApplierTest
    mvn -T1 -pl agentscope-harness -am test -Dtest=AbstractBaseSandboxProjectionTest
    mvn -T1 -pl agentscope-harness -am test -Dtest=WorkspaceManagerHostAuthoritativeReadsTest
    mvn -T1 -pl agentscope-harness -am test -Dtest=SandboxDefinitionTamperRegressionTest
    mvn -T1 -pl agentscope-harness -am spotless:check
    mvn -B -T1 clean verify          # full check (public behavior change)
    mvn -T1 -pl agentscope-harness -am test -Ddocker.it=true -Dtest=DockerSandboxDefinitionTamperIT   # optional
    

    5. Backward Compatibility

    5.1 Behavior changes with default config (flag true)

    Surface Before After Impact
    AGENTS.md / KNOWLEDGE.md / knowledge listing / additional context files under roots sandbox copy wins when present host copy authoritative; sandbox has no vote None for healthy states (projection makes them identical); fixes tamper
    Skills catalog for a projected skills root sandbox glob (host skills + sandbox-only additions, sandbox wins on name) host skills/ directory only Potential regression: promoted/agent-created skills under skills/ and shell-created skills disappear from the prompt catalog; opt out with hostAuthoritativeDefinitions(false)
    Sandbox copy of projected files kept until host content changed restored at every sandbox start when it diverges Potential regression for apps that deliberately mutate projected files inside the sandbox (self-modifying persona; build outputs written under skills/); narrow workspaceProjectionRoots or opt out
    Per-start cost 0 extra round trips on unchanged host +1 chunked sha256sum exec (ceil(N/64) execs) per start Small; see §6
    MEMORY.md, memory/**, sessions, tasks, tools.json fs-first unchanged none

    5.2 Unchanged / guaranteed

    • API: additions only (SandboxFilesystemSpec.hostAuthoritativeDefinitions/isHostAuthoritativeDefinitions/isWorkspaceProjectionEnabled/getWorkspaceProjectionRoots, WorkspaceProjectionEntry flag, WorkspaceManager.setHostAuthoritativeRoots, WorkspaceSkillRepository.setHostAuthoritativeDir). No signature or default changes to existing methods.
    • Persisted state: SandboxState.workspaceProjectionHash keeps its meaning and derivation; no new required fields; old state JSON deserializes (missing hostAuthoritative on WorkspaceProjectionEntry defaults to true; on resume the persisted WorkspaceSpec is replaced by the current build config anyway — SandboxManager.java:112-115 — so the flag follows the app's config).
    • Projection hash stability: the aggregate hash derivation is untouched, so upgrading does not invalidate stored hashes and healthy sandboxes are not re-hydrated on the first post-upgrade call.
    • Sandbox remains writable; execute, file tools, snapshots, and isolation semantics are unchanged; host workspace files are never written by the fix.

    5.3 Options and migration

    • New fluent option: DockerFilesystemSpec/KubernetesFilesystemSpec/E2bFilesystemSpec/AgentRunFilesystemSpec/DaytonaFilesystemSpec (inherited): .hostAuthoritativeDefinitions(false) → exact legacy semantics (sandbox-first reads, union catalog, hash-only skip, tampering persists). Default: true (secure).
    • Definition roots are the existing workspaceProjectionRoots(...) — a single knob controls both projection and read authority (explicit routes via .filesystem(prefix, fs) still win for their prefixes).
    • Release note: "In sandbox mode, workspace definition files (AGENTS.md, skills/, subagents/, knowledge/) are now host-authoritative and sandbox copies are restored when modified. To restore the previous behavior (e.g. self-learning skills in the sandbox), set hostAuthoritativeDefinitions(false)."
    • Docs: update docs/v2/en and docs/v2/zh (filesystem, workspace, skill pages) — required by repo rules (AGENTS.md §5).
    • Alternative default considered: ship with default false (opt-in hardening). Rejected because the issue's severity is high, the documented contract already says projection is a host→sandbox one-way sync, and healthy-state behavior is identical; reviewers preferring the conservative sequence can split the PR (Part B first, then Part A + flag) — the steps are independently testable.

    6. Risk Assessment

    Risk Likelihood Impact Mitigation
    Restore clobbers legitimate sandbox-side writes to projected paths (scripts emitting artifacts under skills/, self-modifying persona apps) medium for niche apps medium Documented; scope via workspaceProjectionRoots or opt out (hostAuthoritativeDefinitions(false)); restore only touches payload paths, never deletes extra files
    Sandbox skill self-learning / curator regression (promoted skills invisible in catalog) medium for apps using skill_manage in sandbox mode medium Opt-out flag; drafts repo explicitly excluded from authority; documented consequence; add release note
    sha256sum unavailable in some image (exit 127) low perf: re-hydrate per start until fixed; integrity preserved Fail-safe (verify=skip→hydrate) + single WARN; optional refinement: md5sum fallback chain
    Verification exec overhead: +1..ceil(N/64) round trips + in-container hashing per start certain low for typical definition trees (KBs–MBs, <100 ms); higher with large .skills-cache staging trees Only runs when host hash is unchanged (the common case) and payload non-empty; document; possible future mtime/size pre-check is out of scope
    Command-portability edge cases: filenames with newlines/quotes, sha256sum escaped output, ARG_MAX very low one extra re-hydration Strict quoting via FilesystemUtils.shellQuote; chunking at 64; parse tolerance: any anomaly → mismatch → re-hydrate (safe direction)
    Host disk becomes a per-call read path (network-mounted workspaces add latency) low small latency per call Files are small and OS-cached; same disk is already read by projection payload building every start
    Fail-closed read when host file exists but is unreadable (persona disappears for that call) low degraded prompt, no security hole Documented; matches today's behavior for missing host file; WARN log preserved from readFileQuietly
    TOCTOU inside a call (tamper after restore, before lazy resource reads; subagents loader in-call window) low self-influence within one call; no persistence Part B restores at next start; optional follow-up for AgentSpecLoader (Step 7)
    User-managed/external sandboxes (Priority 1/2) get restore semantics they did not ask for low their hand-edits to projected files revert at start Documented; they can disable projection or the flag on the spec they build
    GLOBAL/AGENT scope: one user's tamper still visible to concurrent in-flight calls until their next start low reduced (no longer persists), not zero Document; restore + host-authoritative reads eliminate the persistent and catalog vectors
    Cross-platform tests: LocalDirSandbox uses sh -c (Windows CI) medium test-only Mirror InMemorySandbox.exec's cmd /c branch; @TempDir; no real credentials/services
    Docs drift (en/zh divergence) medium low Update both trees in the same PR; run docs checks per repo rules

    Rollback: set hostAuthoritativeDefinitions(false) on the sandbox spec (no code change), or revert the PR — no persisted-format migration is involved, so reverting is safe in both directions.

    Next Steps:

    • Reply /approve to proceed with PR generation
    • Reply /revise <feedback> to request changes
    • Reply /reject to close this proposal

    This proposal expires in 72 hours.


    Automated evaluation and proposal by github-manager-bot

  3. added
    bug
    area/harness
    on Oct 2, 2026
  4. lzyruc commented on Oct 4, 2026

    @lzyruc

    I’d like to work on this.

    I’m planning to follow the proposed direction: make projected definition roots host-authoritative for agent-context reads, add tamper-aware re-projection when the sandbox copy diverges, preserve the legacy behavior behind the opt-out, and add an end-to-end regression covering cross-call persistence.

    I’ll keep the change scoped to #3388 and avoid expanding it into the broader per-path shell authorization problem from #3317.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/harnessbug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions