mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:50:52 +00:00
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:
@@ -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('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">");
|
||||
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())
|
||||
|
||||
+23
@@ -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&test</path></entry><entry access="read"><path>D:\build&test\.git</path></entry><entry access="read"><path>D:\build&test\.agents</path></entry><entry access="read"><path>D:\build&test\.codex</path></entry><entry access="read"><path>D:\build&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&test"]
|
||||
Directly under each listed path, .git, .agents, .codex and .aws have read-only entries.
|
||||
Separate write grants: :tmpdir
|
||||
</filesystem>
|
||||
</environment_context>
|
||||
Reference in New Issue
Block a user