You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[Bug]: In sandbox mode, shell writes to AGENTS.md / skills/ / MEMORY.md override host definitions and persist across calls #3388
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
Build a HarnessAgent with DockerFilesystemSpec (python:3.12-slim, LocalSnapshotSpec, IsolationScope.USER); host workspace contains AGENTS.md with HOST-PERSONA.
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.
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).
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.
Category: bug | Status: Confirmed (engine-verified against main @ 915507134453)
All three claims in the report check out in the current code:
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 sedinside 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.
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.
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).
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-276without 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.
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)
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)
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 /.
Change readWithOverride (:818-824) to:
privateStringreadWithOverride(RuntimeContextrc, StringrelativePath) {
if (isHostAuthoritative(relativePath)) {
Pathhost = workspace.resolve(relativePath).normalize();
if (host.startsWith(workspace) && Files.isRegularFile(host)) {
returnreadFileQuietly(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"";
}
StringfsContent = 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).
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.
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)
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.
Add nullable field + accessors (default null = legacy):
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).
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).
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)
fileDigests maps normalized relative path → SHA-256 hex of the file bytes (insertion-ordered, unmodifiable).
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.
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").
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
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).
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)).
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.
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.
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.
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.
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)
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.
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)
With setHostAuthoritativeDir(hostDir): host-only catalog, sandbox-only skills excluded, host-missing → empty, resourcesFor still delegates to the filesystem; unset → legacy
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):
start_unchangedHost_skipsRehydration — count doHydrateWorkspace invocations via a subclass counter; second start() with untouched sandbox → no re-hydrate (fast path preserved).
start_tamperedAgentsMd_restoresHostCopy — tamper AGENTS.md after first start → start() → file bytes equal host; stored hash unchanged.
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.
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).
start_hostAuthoritativeFalse_skipsVerification — entry flag false → legacy skip (no extra exec; tamper survives — asserts the opt-out is honest).
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):
Host workspace: AGENTS.md = HOST-PERSONA; skills/host-skill/SKILL.md (host skill); state dir per test.
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.
Call 2: new session s2, same userId → resume count == 1 (same isolation slot).
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.
Assert host workspace files are unmodified.
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)
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.
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
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
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.
Activity
xuchaoguo1983 commentedon Oct 2, 2026
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 theexecuteshell 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.oss-maintainer commentedon Oct 2, 2026
Issue Evaluation
Category:
bug| Status: Confirmed (engine-verified againstmain@915507134453)All three claims in the report check out in the current code:
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 isSandboxBackedFilesystem(wired inHarnessAgent.java:2463-2468,:2498-2499) and itsreadrunssedinside 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 viaWorkspaceContextMiddleware.buildWorkspaceSection(:219-256). Layer-4WorkspaceSkillRepository(filesystem, "skills", ...)(HarnessAgentBuilderSupport.java:912-916) globsSKILL.mdthe same way, so the skill catalog is affected too.AbstractBaseSandbox.applyWorkspaceProjectionIfChanged(AbstractBaseSandbox.java:267-287) compares the host payload hash (WorkspaceProjectionApplier.java:64-87) against the last-applied hash stored inSandboxState(SandboxState.java:43) — never against what is actually in the sandbox. A tampered copy therefore survives until the host file changes, andstop()snapshots it (AbstractBaseSandbox.java:132-141), so it persists across sessions in the same isolation slot.ShellExecuteTool.execute(ShellExecuteTool.java:50-79) has no path/command guard;DockerSandbox.doExecrunsdocker exec -w <workspaceRoot> sh -c <cmd>(DockerSandbox.java:150-158).Impact: prompt-integrity / persistence vector in
agentscope-harnesssandbox 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 toMEMORY.mdbypassingmemory_save, for that isolation slot. Host files themselves are not modified; withIsolationScope.USERother users are unaffected, but underAGENT/GLOBALscope the tampering is shared. Severity: high. No existing fix onmain; 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.
AGENTS.md,KNOWLEDGE.md,MEMORY.md,skills/, …) resolve content from the host workspace only (no sandbox override), keeping the sandbox writable for everything else.execper sandbox start, fail-safe to re-hydrate).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.WorkspaceProjectionApplierTest+ a regression test that mirrors the repro (shell-writeAGENTS.mdandskills/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 callsStatus: 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/GLOBALisolation)Module:
agentscope-harness(sandbox filesystem mode:SandboxFilesystemSpecincl.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
execper sandbox start); (c) an explicithostAuthoritativeDefinitions(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.readWithOverridereads through the configuredAbstractFilesystemfirst 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)readAgentsMd:251-253,readKnowledgeMd:256-258,readMemoryMd:261-263,readManagedWorkspaceFileUtf8:269-282(returnsreadWithOverrideat: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(orRoutedSandboxFilesystemwrapping it) becomes the agent filesystem; passed intoWorkspaceManagerat:2498-2499.filesystem/sandbox/BaseSandboxFilesystem.java:132-192(text read =sed -nviaexecute,:159-172),filesystem/sandbox/SandboxBackedFilesystem.java:100-120(execute→ live sandbox).tool/ShellExecuteTool.java:44-90(no command/path guard; only an advisory description) →SandboxBackedFilesystem.execute→DockerSandbox.doExecrunsdocker 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.mdshadows the host persona on every subsequent read.Skills use the same mechanism with the highest repository priority:
WorkspaceSkillRepository(filesystem, "skills", "workspace-namespaced")is composed atagentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.java:909-916and wired atHarnessAgent.java:2786-2789.SKILL.mdvia sandboxglob+read:skill/WorkspaceSkillRepository.java:149-186.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-172globs/readssubagents/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
sandbox/WorkspaceProjectionApplier.java:50-88(digest over sorted(relativePath, content)pairs,:64-87; record at:155).sandbox/AbstractBaseSandbox.java:267-287(applyWorkspaceProjectionIfChanged): ifpayload.hash()equalsstate.getWorkspaceProjectionHash()the method returns at:273-276without looking at the sandbox; hydration happens only on host-content change (:277-281); the hash stored is the applied hash (:282).sandbox/SandboxState.java:43(field),:70-76(accessors).start()(AbstractBaseSandbox.java:116), after the 4-branch restore (:69-124).Consequence: a tampered
/workspace/AGENTS.md(orskills/**) 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.workspaceProjectionHash) and snapshot id are persisted per isolation slot:sandbox/SandboxManager.java:100-130(resume; the currentWorkspaceSpecis re-attached at:112-115, the projection hash is not reset),:214-252(persistState); driven bymiddleware/SandboxLifecycleMiddleware.java:100-154(acquire +start()) and:162-190(release + persist).IsolationScope.USERkeys onuserId(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)
echo INJ-PERSONA > AGENTS.md; mkdir -p skills/x; printf … > skills/x/SKILL.mdShellExecuteTool.execute→DockerSandbox.doExec(ShellExecuteTool.java:50-79,DockerSandbox.java:145-158)AbstractBaseSandbox.java:131-141,SandboxManager.java:214-252SandboxManager.java:100-121,SandboxIsolationKey.java:78-82AbstractBaseSandbox.java:273-276AGENTS.mdread sandbox-first →INJ-PERSONAWorkspaceManager.java:818-824viaWorkspaceContextMiddleware.java:220skills/→ injectedxappearsWorkspaceSkillRepository.java:149-186,HarnessSkillMiddleware.java:352-3841.5 Why existing knobs don't address it
workspaceProjectionEnabled/workspaceProjectionRootscontrol what is projected, not read authority or tamper handling (filesystem/spec/SandboxFilesystemSpec.java:41-48,:97-108,:127-141).BindMountEntry.readOnlyexists (sandbox/layout/BindMountEntry.java:35-55) but the default projection is a writable tar-hydrate (sandbox/layout/WorkspaceProjectionEntry.java:30-57;WorkspaceSpecApplier.java:130-132skips projection entries), and cloud backends ignore bind mounts./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:
WorkspaceManager,WorkspaceSkillRepository)WorkspaceProjectionApplier,AbstractBaseSandbox)SandboxFilesystemSpec.hostAuthoritativeDefinitions(false)restores exact legacy behaviortrueSemantics of host-authoritative mode (flag
true): for the configured definition roots (=workspaceProjectionRoots, defaultAGENTS.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.javaAdd a field + setter, default empty (zero behavior change when unset):
Add a public static prefix matcher (shared with wiring/tests):
isUnderRoot(String relativePath, String root)— exact match orstartsWith(root + "/")after normalizing\→/, stripping leading./and trailing/.Change
readWithOverride(:818-824) to: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""viareadFileQuietly(fail-closed to "no definition", same as today's missing-host behavior).Make
listKnowledgeFiles(:296-…, fs-union at:300-309) host-only whenknowledgeis authoritative: skip thefilesystem.globhalf and keep the host walk, so injectedknowledge/**files neither appear in the prompt's knowledge list nor inreadKnowledgeMdresolution.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(readstools.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 anyreadManagedWorkspaceFileUtf8path under roots.Step 2 — Host-authoritative directory in
WorkspaceSkillRepository(Part A, skills)File:
agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/WorkspaceSkillRepository.javaDo not wrap the repository in a decorator class.
MarketplaceStager.stageAllspecial-casesbound.repo() instanceof WorkspaceSkillRepository→StageResult.WorkspaceNative(skill/runtime/MarketplaceStager.java:222-226); a wrapper would change<files-root>from/workspace/skills/<name>to a.skills-cachestaging path and require resources. Extend the class itself instead — the flag-configured instance keeps its type, source string, and write path.Add nullable field + accessors (default
null= legacy):In
getAllSkills(RuntimeContext)(:149-186): whenhostAuthoritativeDir != null, listSKILL.mdfiles by walking the host directory (same metadata-dir skip rule ashasMetadataAncestor,:503-515), buildAgentSkillviaSkillUtil.createFrom(content, null, this.source)— i.e. host content only; sandbox-only skills (e.g. shell-injectedskills/x/SKILL.md) are excluded. Host dir missing/empty → empty list.getSkill,getAllSkillNames,skillExistsinherit the behavior (they delegate togetAllSkills).Leave the write path and lazy resources untouched:
save/delete/writeSkillFile/resourcesForstill go to the sandbox filesystem, andresourcesForkeeps 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).Wiring (set at construction, not post hoc):
HarnessAgentBuilderSupport.composeSkillRepositories(:909-916): whenb.sandboxFilesystemSpec != null,isHostAuthoritativeDefinitions()and the roots list contains exactlyskills, callrepo.setHostAuthoritativeDir(wsManager.getSkillsDir()).HarnessAgent.java:2801-2821(skill_manage replacement): when the non-writable layer-4 repo is replaced by the writableWorkspaceSkillRepository(filesystem, smConfig.mainDir(), …), copy the config over whensmConfig.mainDir()equals an authoritative root exactly ("skills";SkillManageConfig.DEFAULT_MAIN_DIR,tool/SkillManageConfig.java:32-35).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
skillsroot are no longer part of the prompt catalog whilehostAuthoritativeDefinitionsis on;SkillCuratorlikewise only sees host skills. Apps that rely on sandbox skill self-learning set the flag tofalse.Step 3 — Per-file digests in the projection payload (Part B, payload)
File:
agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/WorkspaceProjectionApplier.javaExtend the internal record (
:155) with a per-file manifest:fileDigestsmaps normalized relative path → SHA-256 hex of the file bytes (insertion-ordered, unmodifiable).build(...): while already reading each file (:68-83), also compute the per-file SHA-256. Do not change the aggregatehashderivation (:64,:73-75,:86) — it is persisted inSandboxStateand must stay stable across upgrade to avoid spurious re-hydration (§5).Blast radius is small:
ProjectionPayloadis constructed only here; consumers areAbstractBaseSandbox:267-287andWorkspaceProjectionApplierTest.Step 4 — Tamper-aware re-projection (Part B, enforcement)
File:
agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/AbstractBaseSandbox.javaReplace the skip check in
applyWorkspaceProjectionIfChanged(:267-287) with:null→ return.boolean hostChanged = !Objects.equals(payload.hash(), state.getWorkspaceProjectionHash());hostChanged || (projectionIsHostAuthoritative(spec) && !projectedContentMatchesSandbox(payload))fileCount() > 0→ hydrate (:277-281unchanged), thenstate.setWorkspaceProjectionHash(payload.hash())(:282unchanged). Log at debug/info which condition triggered ("host payload changed" vs "sandbox copy diverged — restoring").projectedContentMatchesSandbox(payload)(new private method):Build one shell command per chunk (chunk size 64 paths; ARG_MAX safety):
<workspaceRoot>=state.getWorkspaceSpec().getRoot(); paths are payload keys, quoted withfilesystem/util/FilesystemUtils.shellQuote(:101); run viadoExec(null, cmd, PROJECTION_VERIFY_TIMEOUT_SECONDS)with a new constant (30).Parse
sha256sumlines (<hex> <path>), normalize paths, compare the resulting map by exact key set and values topayload.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)walksspec.getEntries()for theWorkspaceProjectionEntryrecursively (mirror the walk inWorkspaceProjectionApplier.collectProjectionEntries) and returns its new flag; defaults totruewhen 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
agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/layout/WorkspaceProjectionEntry.java(:30-57): addprivate boolean hostAuthoritative = true;+ getter/setter (serialized with the state; Jackson fills the default for old JSON).agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/spec/SandboxFilesystemSpec.java:private boolean hostAuthoritativeDefinitions = true;with fluenthostAuthoritativeDefinitions(boolean)+isHostAuthoritativeDefinitions()(next to:97-108);isWorkspaceProjectionEnabled()/getWorkspaceProjectionRoots()(currently none) so the wiring can reuse the roots list;buildWorkspaceSpecWithProjection(:127-141):projection.setHostAuthoritative(hostAuthoritativeDefinitions);— and whenhostAuthoritativeDefinitionsisfalse, keep legacy (setHostAuthoritative(false)).agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java::2459-2497) and beforenew WorkspaceManager(:2498): whensandboxFilesystemSpec != null && isHostAuthoritativeDefinitions(), resolve the effective roots (minus any path covered by an explicitfilesystemRoutesprefix — routes are an explicit app choice and keep their backend) and callwsManager.setHostAuthoritativeRoots(roots);:2505-2515,workspaceFactoryFn) soworkspaceFor(userId, sessionId)behaves identically;HarnessAgentchanges; theinstanceofdispatch sites (:2708-2709,:2887-2898) are untouched.docs/v2/en+docs/v2/zhpages —harness/filesystem.md(projection section,:282-292),harness/workspace.mdsandbox mode (:271-285),harness/skill.mdprojection/authority notes (:355-373); document the new flag and the restore semantics.Step 6 — Rejected alternatives (for review context)
BindMountEntry.readOnly): the default projection is a tar hydrate, not a mount; Docker/cloud backends diverge; task constraint excludes it as the sole mechanism.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.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 betweenLocalFilesystemandBaseSandboxFilesystem. Larger risk than the targeted Steps 1–2 for the same guarantee.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 addMEMORY.mdtoworkspaceProjectionRoots— withhostAuthoritativeDefinitionson it then becomes host-authoritative and restored.subagents/**content is restored by Part B at each start, butAgentSpecLoader/DynamicSubagentsMiddleware/SubagentsMiddlewarekeep 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.resourcesForread 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.
agentscope-harness/src/main/java/io/agentscope/harness/agent/workspace/WorkspaceManager.javahostAuthoritativeRootsfield/setter,isUnderRoothelper,readWithOverridehost-first branch,listKnowledgeFileshost-only branchagentscope-harness/src/main/java/io/agentscope/harness/agent/skill/WorkspaceSkillRepository.javahostAuthoritativeDirfield/accessors, host listing branch ingetAllSkills(RuntimeContext)agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/WorkspaceProjectionApplier.javaProjectionPayload/build(aggregate hash unchanged)agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/AbstractBaseSandbox.javaapplyWorkspaceProjectionIfChanged,projectedContentMatchesSandbox, entry-flag walk, verify constantsagentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/layout/WorkspaceProjectionEntry.javahostAuthoritativefield (defaulttrue) + accessorsagentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/spec/SandboxFilesystemSpec.javahostAuthoritativeDefinitions(boolean)(defaulttrue), info accessors, set flag on entryagentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.javacomposeSkillRepositoriesagentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.javaWorkspaceManagers; carry skill config on the skill_manage replacementdocs/v2/en/docs/harness/{filesystem,workspace,skill}.md+docs/v2/zh/…counterpartsNew test files (module
agentscope-harness):src/test/java/io/agentscope/harness/agent/sandbox/AbstractBaseSandboxProjectionTest.java(+ test doubleLocalDirSandboxin the same package orsandbox/support)src/test/java/io/agentscope/harness/agent/workspace/WorkspaceManagerHostAuthoritativeReadsTest.javasrc/test/java/io/agentscope/harness/agent/sandbox/SandboxDefinitionTamperRegressionTest.javasrc/test/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandboxDefinitionTamperIT.javaNo changes to
agentscope-coreoragentscope-extensions: every sandbox spec (DockerFilesystemSpec,KubernetesFilesystemSpec,E2bFilesystemSpec,AgentRunFilesystemSpec,DaytonaFilesystemSpec) inherits the new option fromSandboxFilesystemSpec.Estimated diff: ~350–450 net LOC in main + docs, plus tests.
4. Test Plan
4.1 Existing tests to extend
agentscope-harness/src/test/java/io/agentscope/harness/agent/sandbox/WorkspaceProjectionApplierTest.javafileDigests()has one SHA-256 entry per projected file with correct values forAGENTS.md/skills/java/SKILL.md; add a golden-value test pinning the aggregatehash()for a fixed input tree (guards the "hash derivation unchanged" backward-compat promise)agentscope-harness/src/test/java/io/agentscope/harness/agent/skill/WorkspaceSkillRepositoryTest.javasetHostAuthoritativeDir(hostDir): host-only catalog, sandbox-only skills excluded, host-missing → empty,resourcesForstill delegates to the filesystem; unset → legacyagentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/WorkspaceContextMiddlewareSandboxPromptTest.javaagentscope-harness/src/test/java/io/agentscope/harness/agent/example/SandboxFilesystemIsolationScopeExampleTest.javaagentscope-harness/src/test/java/io/agentscope/harness/agent/HarnessAgentTest.javaInMemorySandboxFilesystemSpec→wsManagergets the default roots;hostAuthoritativeDefinitions(false)→ roots empty and project entry flag false4.2 New unit tests (run everywhere, no Docker)
AbstractBaseSandboxProjectionTestwith a test doubleLocalDirSandbox extends AbstractBaseSandbox(temp dir as workspace root;doExecviash -cwith cwd = root, mirroringInMemorySandbox.execincl. the Windowscmd /cswitch;doHydrateWorkspaceviaWorkspaceArchiveExtractor.extractTarArchive(destRoot, stream)—sandbox/WorkspaceArchiveExtractor.java:54;doPersistWorkspacetar of the dir; setup/destroy mkdir/rm):start_unchangedHost_skipsRehydration— countdoHydrateWorkspaceinvocations via a subclass counter; secondstart()with untouched sandbox → no re-hydrate (fast path preserved).start_tamperedAgentsMd_restoresHostCopy— tamperAGENTS.mdafter first start →start()→ file bytes equal host; stored hash unchanged.start_deletedProjectedFile_restores—rm skills/java/SKILL.md→ restored.start_injectedExtraSkillFile_doesNotAffectPayloadMatch— extraskills/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.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).start_hostAuthoritativeFalse_skipsVerification— entry flag false → legacy skip (no extra exec; tamper survives — asserts the opt-out is honest).start_hostFileChanged_stillRehydrates— existing behavior guard.WorkspaceManagerHostAuthoritativeReadsTest:readAgentsMdreturns host; unset → sandbox content.""under authority (no fallback), legacy returns sandbox content."", not tampered content.knowledge/authoritative →listKnowledgeFilesexcludes injected sandbox-only files.MEMORY.mdunaffected (sandbox-first preserved)../skills/x,skillsexact,skillsX(prefix must not match on partial segment).4.3 Regression test mirroring the repro (required)
SandboxDefinitionTamperRegressionTest(harness tests, no Docker) — pattern afterSandboxFilesystemIsolationScopeExampleTest(MockitoModelstub,@TempDirworkspace,agentscope.state.homeoverride,@HarnessQuiescence,InMemorySandboxClient/InMemorySandboxFilesystemSpec):AGENTS.md=HOST-PERSONA;skills/host-skill/SKILL.md(host skill); state dir per test.HarnessAgentwithInMemorySandboxFilesystemSpec,IsolationScope.USER, mock model that (turn 1) emits a tool call toexecutewith 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.agent.call(user u1, session s1)→ release persists state.userId→resumecount == 1 (same isolation slot).HOST-PERSONA, does not containINJ-PERSONA;host-skill, does not containx/INJ-SKILL..hostAuthoritativeDefinitions(false)→ documents legacy behavior (injected content visible) so the opt-out cannot silently regress.4.4 Docker integration test (optional, gated)
DockerSandboxDefinitionTamperITmirroring the repro end-to-end withDockerFilesystemSpec(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 keepsHOST-PERSONA;cat /workspace/AGENTS.mdinside 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
5. Backward Compatibility
5.1 Behavior changes with default config (flag
true)skillsrootskills/directory onlyskills/and shell-created skills disappear from the prompt catalog; opt out withhostAuthoritativeDefinitions(false)skills/); narrowworkspaceProjectionRootsor opt outsha256sumexec (ceil(N/64) execs) per startMEMORY.md,memory/**, sessions, tasks, tools.json5.2 Unchanged / guaranteed
SandboxFilesystemSpec.hostAuthoritativeDefinitions/isHostAuthoritativeDefinitions/isWorkspaceProjectionEnabled/getWorkspaceProjectionRoots,WorkspaceProjectionEntryflag,WorkspaceManager.setHostAuthoritativeRoots,WorkspaceSkillRepository.setHostAuthoritativeDir). No signature or default changes to existing methods.SandboxState.workspaceProjectionHashkeeps its meaning and derivation; no new required fields; old state JSON deserializes (missinghostAuthoritativeonWorkspaceProjectionEntrydefaults totrue; on resume the persistedWorkspaceSpecis replaced by the current build config anyway —SandboxManager.java:112-115— so the flag follows the app's config).execute, file tools, snapshots, and isolation semantics are unchanged; host workspace files are never written by the fix.5.3 Options and migration
DockerFilesystemSpec/KubernetesFilesystemSpec/E2bFilesystemSpec/AgentRunFilesystemSpec/DaytonaFilesystemSpec(inherited):.hostAuthoritativeDefinitions(false)→ exact legacy semantics (sandbox-first reads, union catalog, hash-only skip, tampering persists). Default:true(secure).workspaceProjectionRoots(...)— a single knob controls both projection and read authority (explicit routes via.filesystem(prefix, fs)still win for their prefixes).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), sethostAuthoritativeDefinitions(false)."docs/v2/enanddocs/v2/zh(filesystem, workspace, skill pages) — required by repo rules (AGENTS.md §5).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
skills/, self-modifying persona apps)workspaceProjectionRootsor opt out (hostAuthoritativeDefinitions(false)); restore only touches payload paths, never deletes extra filessha256sumunavailable in some image (exit 127)md5sumfallback chain.skills-cachestaging treessha256sumescaped output, ARG_MAXFilesystemUtils.shellQuote; chunking at 64; parse tolerance: any anomaly → mismatch → re-hydrate (safe direction)readFileQuietlyAgentSpecLoader(Step 7)LocalDirSandboxusessh -c(Windows CI)InMemorySandbox.exec'scmd /cbranch;@TempDir; no real credentials/servicesRollback: 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:
/approveto proceed with PR generation/revise <feedback>to request changes/rejectto close this proposalThis proposal expires in 72 hours.
Automated evaluation and proposal by github-manager-bot
lzyruc commentedon Oct 4, 2026
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.