Add compact filesystem context for workspace-write profiles (#64164)

## Why

The filesystem context sent to the model repeats the same generated
read-only metadata entries under each writable path.

## What changed

Add the opt-in `features.compact_filesystem_context` flag. For matching
workspace-write profiles with multiple writable paths, list workspace
roots and other writable paths separately, then state the shared
read-only rule for `.git`, `.agents`, `.codex`, and `.aws` once.
Keep temporary-directory write grants explicit and use the full listing
for profiles with rules the summary cannot represent.

## Testing

Cover compact rendering and fallback for explicit metadata reads or
Windows paths with different casing. Snapshot shared and per-environment
context across two turns to verify that unchanged permissions carry
forward.

GitOrigin-RevId: 4e9f36a054a96f06c9e5d0b3882148b132233e4f
This commit is contained in:
Charlie Marsh
2026-11-26 15:09:58 +00:00
committed by copyberry
parent 61369c4e95
commit 42c320991e
10 changed files with 416 additions and 2 deletions
+6
View File
@@ -970,6 +970,9 @@
"command_sessions_world_state": {
"type": "boolean"
},
"compact_filesystem_context": {
"type": "boolean"
},
"compaction_image_budget": {
"type": "boolean"
},
@@ -8360,6 +8363,9 @@
"command_sessions_world_state": {
"type": "boolean"
},
"compact_filesystem_context": {
"type": "boolean"
},
"compaction_image_budget": {
"type": "boolean"
},
@@ -4,11 +4,19 @@ use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxEntry;
use codex_protocol::permissions::FileSystemSpecialPath;
use codex_protocol::permissions::PROTECTED_METADATA_PATH_NAMES;
use codex_utils_path_uri::PathUri;
use std::collections::HashSet;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum FileSystemFormat {
Full,
Compact,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct FileSystemContext {
format: FileSystemFormat,
workspace_roots: Vec<String>,
permission_profile: FileSystemPermissionProfileContext,
}
@@ -33,6 +41,7 @@ impl FileSystemContext {
pub(super) fn from_permission_profile(
permission_profile: &PermissionProfile,
workspace_roots: &[PathUri],
format: FileSystemFormat,
) -> Self {
let permission_profile = permission_profile
.clone()
@@ -51,12 +60,25 @@ impl FileSystemContext {
PermissionProfile::External { .. } => FileSystemPermissionProfileContext::External,
};
Self {
format,
workspace_roots,
permission_profile,
}
}
pub(super) fn render(&self) -> String {
if self.format == FileSystemFormat::Compact
&& let FileSystemPermissionProfileContext::Managed(
ManagedFileSystemContext::Restricted {
entries,
glob_scan_max_depth: None,
},
) = &self.permission_profile
&& let Some(compact) = render_compact_filesystem(&self.workspace_roots, entries)
{
return compact;
}
let mut rendered = "<filesystem>".to_string();
if !self.workspace_roots.is_empty() {
rendered.push_str("<workspace_roots>");
@@ -140,6 +162,105 @@ impl ManagedFileSystemContext {
}
}
/// Describe a workspace-write profile only if every literal write path has exactly
/// the same generated read-only children. Any other rule needs the full listing.
fn render_compact_filesystem(
workspace_roots: &[String],
entries: &[FileSystemSandboxEntry],
) -> Option<String> {
if workspace_roots.is_empty() || entries.len() < 2 * (1 + PROTECTED_METADATA_PATH_NAMES.len()) {
return None;
}
let mut read_root = false;
let mut temp_grants = Vec::new();
let mut writes = Vec::new();
let mut reads = HashSet::new();
for entry in entries {
match (&entry.path, entry.access) {
(
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
FileSystemAccessMode::Read,
) => read_root = true,
(FileSystemPath::Special { value }, FileSystemAccessMode::Write)
if matches!(
value,
FileSystemSpecialPath::SlashTmp | FileSystemSpecialPath::Tmpdir
) =>
{
temp_grants.push(render_special_path(value));
}
(FileSystemPath::Path { path }, FileSystemAccessMode::Write) => writes.push(path),
(FileSystemPath::Path { path }, FileSystemAccessMode::Read) => {
if !entry.skips_missing_path() || !reads.insert(path) {
return None;
}
}
(_, FileSystemAccessMode::Deny)
| (FileSystemPath::Special { .. } | FileSystemPath::GlobPattern { .. }, _) => {
return None;
}
}
}
if !read_root
|| writes.len() < 2
|| reads.len() != writes.len() * PROTECTED_METADATA_PATH_NAMES.len()
|| writes.iter().any(|path| reads.contains(path))
{
return None;
}
let mut remaining_roots: HashSet<_> = workspace_roots.iter().collect();
let mut other_writes = Vec::new();
for path in writes {
for name in PROTECTED_METADATA_PATH_NAMES {
let child = path.join_descendant(name).ok()?;
// PathUri equality ignores Windows case. Preserve the spelling the model sees.
if reads.take(&child)?.encoded_path() != child.encoded_path() {
return None;
}
}
let path = path.inferred_native_path_string();
if !remaining_roots.remove(&path) {
other_writes.push(path);
}
}
if !remaining_roots.is_empty() {
return None;
}
let mut rendered = String::from("<filesystem>\nManaged, restricted. Read access to :root.");
for (label, paths) in [
("Writable workspace roots", workspace_roots),
("Other writable paths", other_writes.as_slice()),
] {
if !paths.is_empty() {
// Quote path boundaries and control characters as JSON inside XML text.
let paths = serde_json::to_string(paths)
.ok()?
.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;");
rendered.push_str(&format!("\n{label}: {paths}"));
}
}
let (last, rest) = PROTECTED_METADATA_PATH_NAMES.split_last()?;
rendered.push_str(&format!(
"\nDirectly under each listed path, {} and {last} have read-only entries.",
rest.join(", ")
));
if !temp_grants.is_empty() {
rendered.push_str(&format!(
"\nSeparate write grants: {}",
temp_grants.join(", ")
));
}
rendered.push_str("\n</filesystem>");
Some(rendered)
}
fn render_file_system_entry(rendered: &mut String, entry: &FileSystemSandboxEntry) {
rendered.push_str("<entry access=\"");
let access = entry.access.to_string();
@@ -6,6 +6,7 @@ use super::WorldStateUpdate;
use super::WorldStateUpdateContent;
use crate::context::ContextualUserFragment;
use crate::context::environment_context::FileSystemContext;
use crate::context::environment_context::FileSystemFormat;
use crate::context::environment_context::NetworkContext;
use crate::context::environment_context::push_xml_escaped_text;
use crate::environment_selection::TurnEnvironmentSnapshot;
@@ -59,6 +60,15 @@ impl EnvironmentsState {
.config
.features
.enabled(Feature::PerEnvironmentContext);
let filesystem_format = if turn_context
.config
.features
.enabled(Feature::CompactFilesystemContext)
{
FileSystemFormat::Compact
} else {
FileSystemFormat::Full
};
let shell_version = if turn_context
.config
.features
@@ -72,7 +82,7 @@ impl EnvironmentsState {
None
};
Self {
environments: environment_states(environments, per_environment),
environments: environment_states(environments, per_environment, filesystem_format),
per_environment,
shell_version,
current_date_is_utc: current_date.is_some()
@@ -93,6 +103,7 @@ impl EnvironmentsState {
FileSystemContext::from_permission_profile(
environment.permission_profile(),
environment.workspace_roots(),
filesystem_format,
)
}),
subagents: None,
@@ -543,6 +554,7 @@ async fn powershell_version(shell_path: &Path) -> Option<String> {
fn environment_states(
snapshot: &TurnEnvironmentSnapshot,
per_environment: bool,
filesystem_format: FileSystemFormat,
) -> BTreeMap<String, EnvironmentState> {
let mut environments = snapshot
.turn_environments()
@@ -564,6 +576,7 @@ fn environment_states(
FileSystemContext::from_permission_profile(
environment.permission_profile(),
environment.workspace_roots(),
filesystem_format,
)
.render()
}),
@@ -121,6 +121,7 @@ fn serialize_environment_context_with_foreign_windows_cwd() {
FileSystemContext::from_permission_profile(
&PermissionProfile::Disabled,
&[PathUri::parse("file:///D:/workspace").expect("Windows workspace root URI")],
FileSystemFormat::Full,
)
.render(),
);
@@ -228,6 +229,7 @@ fn serialize_environment_context_with_full_filesystem_profile() {
PathUri::from_abs_path(&repo),
PathUri::from_abs_path(&other_repo),
],
FileSystemFormat::Compact,
));
let expected = format!(
@@ -248,6 +250,87 @@ fn serialize_environment_context_with_full_filesystem_profile() {
assert_eq!(context.render().expect_text(), expected);
}
#[test]
fn group_default_metadata_reads_across_literal_write_paths() {
let workspace = PathUri::parse("file:///C:/work").unwrap();
let extra = PathUri::parse("file:///D:/build&test").unwrap();
let profile = PermissionProfile::workspace_write_with_path_uris(
&[extra],
NetworkSandboxPolicy::Restricted,
/*exclude_tmpdir_env_var*/ false,
/*exclude_slash_tmp*/ true,
);
let mut context = environment_state(
[environment("local", workspace.clone(), "powershell")],
/*current_date*/ None,
/*timezone*/ None,
/*network*/ None,
/*subagents*/ None,
);
let [full, compact] = [FileSystemFormat::Full, FileSystemFormat::Compact].map(|format| {
context.filesystem = Some(FileSystemContext::from_permission_profile(
&profile,
std::slice::from_ref(&workspace),
format,
));
context.render().expect_text()
});
insta::assert_snapshot!(format!("Control\n{full}\n\nTreatment\n{compact}"));
}
#[test]
fn keep_nonuniform_metadata_reads_explicit() {
let workspace = PathUri::parse("file:///C:/work").unwrap();
let extra = PathUri::parse("file:///D:/build").unwrap();
let mut policy = FileSystemSandboxPolicy::workspace_write_with_path_uris(
std::slice::from_ref(&extra),
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ true,
);
let git = extra.join_descendant(".git").unwrap().into();
let entry = policy
.entries
.iter_mut()
.find(|entry| entry.path == git)
.unwrap();
// Windows paths compare case-insensitively. A shared rule would lose this spelling.
entry.path = extra.join_descendant(".GIT").unwrap().into();
let profile =
PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted);
let rendered = FileSystemContext::from_permission_profile(
&profile,
&[workspace],
FileSystemFormat::Compact,
)
.render();
assert!(rendered.contains(r#"<entry access="read"><path>C:\work\.git</path></entry>"#));
assert!(rendered.contains(r#"<entry access="read"><path>D:\build\.GIT</path></entry>"#));
}
#[test]
fn keep_an_explicit_metadata_read_even_when_the_paths_match() {
let roots = [
PathUri::parse("file:///repo").unwrap(),
PathUri::parse("file:///cache").unwrap(),
];
let mut policy = FileSystemSandboxPolicy::workspace_write_with_path_uris(
&roots, /*exclude_tmpdir_env_var*/ false, /*exclude_slash_tmp*/ false,
);
let git = roots[1].join_descendant(".git").unwrap();
policy.entries.push(FileSystemSandboxEntry::new(
git.into(),
FileSystemAccessMode::Read,
));
let profile =
PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted);
let render =
|format| FileSystemContext::from_permission_profile(&profile, &roots, format).render();
assert_eq!(
render(FileSystemFormat::Compact),
render(FileSystemFormat::Full)
);
}
#[test]
fn serialize_read_only_environment_context() {
let context = environment_state(
@@ -70,6 +70,7 @@ fn snapshots() -> Result<()> {
filesystem: Some(FileSystemContext::from_permission_profile(
&PermissionProfile::Disabled,
&[],
FileSystemFormat::Full,
)),
..environments.clone()
};
@@ -85,6 +86,7 @@ fn snapshots() -> Result<()> {
network: NetworkSandboxPolicy::Restricted,
},
&[],
FileSystemFormat::Full,
)),
..environments
};
@@ -98,6 +100,7 @@ fn snapshots() -> Result<()> {
filesystem: Some(FileSystemContext::from_permission_profile(
&PermissionProfile::Disabled,
&[],
FileSystemFormat::Full,
)),
..Default::default()
};
@@ -485,7 +488,11 @@ fn failure_context_limits_total_detail_bytes_at_utf8_boundaries() {
})
.collect(),
};
let states = environment_states(&snapshot, /*per_environment*/ false);
let states = environment_states(
&snapshot,
/*per_environment*/ false,
FileSystemFormat::Full,
);
let details: Vec<_> = states
.values()
.map(|state| state.error.as_deref())
@@ -0,0 +1,23 @@
---
source: core/src/context/world_state/environment_render_tests.rs
expression: "format!(\"Control\\n{full}\\n\\nTreatment\\n{compact}\")"
---
Control
<environment_context>
<cwd>C:\work</cwd>
<shell>powershell</shell>
<filesystem><workspace_roots><root>C:\work</root></workspace_roots><permission_profile type="managed"><file_system type="restricted"><entry access="read"><special>:root</special></entry><entry access="write"><path>C:\work</path></entry><entry access="write"><special>:tmpdir</special></entry><entry access="read"><path>C:\work\.git</path></entry><entry access="read"><path>C:\work\.agents</path></entry><entry access="read"><path>C:\work\.codex</path></entry><entry access="read"><path>C:\work\.aws</path></entry><entry access="write"><path>D:\build&amp;test</path></entry><entry access="read"><path>D:\build&amp;test\.git</path></entry><entry access="read"><path>D:\build&amp;test\.agents</path></entry><entry access="read"><path>D:\build&amp;test\.codex</path></entry><entry access="read"><path>D:\build&amp;test\.aws</path></entry></file_system></permission_profile></filesystem>
</environment_context>
Treatment
<environment_context>
<cwd>C:\work</cwd>
<shell>powershell</shell>
<filesystem>
Managed, restricted. Read access to :root.
Writable workspace roots: ["C:\\work"]
Other writable paths: ["D:\\build&amp;test"]
Directly under each listed path, .git, .agents, .codex and .aws have read-only entries.
Separate write grants: :tmpdir
</filesystem>
</environment_context>
+78
View File
@@ -3843,6 +3843,84 @@ async fn model_catalog_refresh_preserves_tools_and_history() -> Result<()> {
Ok(())
}
#[test_case::test_case(false, "compact_filesystem"; "shared")]
#[test_case::test_case(true, "compact_filesystem_per_environment"; "per_environment")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn compact_filesystem_context(per_environment: bool, snapshot_name: &str) -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let mock = mount_sse_sequence(
&server,
vec![
sse(vec![ev_completed("first")]),
sse(vec![ev_completed("second")]),
],
)
.await;
let test = test_codex()
.with_config(move |config| {
configure_scenario_catalog(config);
config.workspace_roots = vec![config.cwd.clone()];
config
.features
.enable(Feature::CompactFilesystemContext)
.expect("enable compact filesystem context");
config
.features
.set_enabled(Feature::PerEnvironmentContext, per_environment)
.expect("configure per-environment context");
})
.build_with_auto_env(&server)
.await?;
let cwd = executor_path_uri(&test.config.cwd)?;
let roots = [cwd.clone(), cwd.join("cache")?];
let profile = PermissionProfile::workspace_write_with_path_uris(
&roots,
NetworkSandboxPolicy::Restricted,
/*exclude_tmpdir_env_var*/ false,
/*exclude_slash_tmp*/ true,
);
test.submit_turn_with_permission_profile("Where can I write?", profile)
.await?;
test.submit_text_turn("What about the cache?").await?;
// The snapshot formatter handles XML paths. Normalize the compact JSON lists before clipping.
let [workspace, cache] =
roots.map(|path| json!(path.inferred_native_path_string()).to_string());
let mut bodies = mock
.requests()
.iter()
.map(core_test_support::responses::ResponsesRequest::body_json)
.collect::<Vec<_>>();
for body in &mut bodies {
for item in body["input"].as_array_mut().expect("request input") {
for part in item["content"].as_array_mut().into_iter().flatten() {
if let Some(text) = part["text"].as_str()
&& text.starts_with("<environment_context>")
{
part["text"] = text
.replace(&workspace, r#""<CWD>""#)
.replace(&cache, r#""<CWD>/cache""#)
.replace(r#"<environment id="remote""#, r#"<environment id="local""#)
.into();
}
}
}
}
let entries = bodies.iter().map(SnapshotEntry::body).collect::<Vec<_>>();
insta::assert_snapshot!(
snapshot_name,
context_snapshot::format_context_snapshot(
"The workspace and cache share read-only children. Unchanged permissions carry over to the next turn.",
&entries,
&ContextSnapshotOptions::default()
.rewrite_known_segments()
.preserve_environment_context(),
)
);
Ok(())
}
#[test_case::test_case(PermissionPathScenario::OmittedPaths; "omitted_paths")]
#[test_case::test_case(PermissionPathScenario::DeniedReads; "denied_reads")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
@@ -0,0 +1,35 @@
---
source: core/tests/suite/scenarios.rs
expression: "context_snapshot::format_context_snapshot(\"The workspace and cache share read-only children. Unchanged permissions carry over to the next turn.\",\n&entries,\n&ContextSnapshotOptions::default().rewrite_known_segments().preserve_environment_context(),)"
---
Scenario: The workspace and cache share read-only children. Unchanged permissions carry over to the next turn.
## Window 1
-- request 1 (request) --
00:message/developer:
<MODEL_INSTRUCTIONS>
01:message/developer[2]:
[01] <PERMISSIONS_INSTRUCTIONS>
[02] <tools>
Deferred tool namespaces:
- multi_agent_v1: Tools for spawning and managing sub-agents.
</tools>
02:message/user:
<environment_context>
<cwd><CWD></cwd>
<shell><HOST_SHELL></shell>
<current_date><CURRENT_DATE></current_date>
<timezone><HOST_TIMEZONE></timezone>
<filesystem>
Managed, restricted. Read access to :root.
Writable workspace roots: ["<CWD>"]
Other writable paths: ["<CWD>/cache"]
Directly under each listed path, .git, .agents, .codex and .aws have read-only entries.
Separate write grants: :tmpdir
</filesystem>
</environment_context>
03:message/user:
Where can I write?
-- request 2 (request) --
04:message/user:
What about the cache?
@@ -0,0 +1,40 @@
---
source: core/tests/suite/scenarios.rs
expression: "context_snapshot::format_context_snapshot(\"The workspace and cache share read-only children. Unchanged permissions carry over to the next turn.\",\n&entries,\n&ContextSnapshotOptions::default().rewrite_known_segments().preserve_environment_context(),)"
---
Scenario: The workspace and cache share read-only children. Unchanged permissions carry over to the next turn.
## Window 1
-- request 1 (request) --
00:message/developer:
<MODEL_INSTRUCTIONS>
01:message/developer[2]:
[01] <PERMISSIONS_INSTRUCTIONS>
[02] <tools>
Deferred tool namespaces:
- multi_agent_v1: Tools for spawning and managing sub-agents.
</tools>
02:message/user:
<environment_context>
<environments>
<environment id="local">
<cwd><CWD></cwd>
<shell><HOST_SHELL></shell>
<network access="restricted" />
<filesystem>
Managed, restricted. Read access to :root.
Writable workspace roots: ["<CWD>"]
Other writable paths: ["<CWD>/cache"]
Directly under each listed path, .git, .agents, .codex and .aws have read-only entries.
Separate write grants: :tmpdir
</filesystem>
</environment>
</environments>
<current_date><CURRENT_DATE></current_date>
<timezone><HOST_TIMEZONE></timezone>
</environment_context>
03:message/user:
Where can I write?
-- request 2 (request) --
04:message/user:
What about the cache?
+8
View File
@@ -226,6 +226,8 @@ pub enum Feature {
DeferredExecutor,
/// Describe each selected environment's filesystem and permissions separately.
PerEnvironmentContext,
/// Describe uniform workspace-write permissions without repeating paths or nested XML.
CompactFilesystemContext,
/// Use the current working directory for turn diff display paths.
CwdRelativeTurnDiffs,
/// Enable runtime metrics snapshots via a manual reader.
@@ -1364,6 +1366,12 @@ pub const FEATURES: &[FeatureSpec] = &[
stage: Stage::UnderDevelopment,
default_enabled: false,
},
FeatureSpec {
id: Feature::CompactFilesystemContext,
key: "compact_filesystem_context",
stage: Stage::UnderDevelopment,
default_enabled: false,
},
FeatureSpec {
id: Feature::CwdRelativeTurnDiffs,
key: "cwd_relative_turn_diffs",