Batch filesystem metadata checks for instruction and skill discovery (#63266)

## Why

Discovering project instructions and repository skill directories can
require several metadata checks per ancestor directory. Batching those
checks reduces remote executor round trips and sandbox helper launches.

## What changed

Add bounded metadata batches that return a result or error for each
path in input order. Remote executors advertise support for
`fs/getMetadataBatch`, and sandboxed filesystems can process a batch in
one helper invocation.

Check project root markers alongside the first working-directory
instruction candidate, then batch the next candidate across unresolved
directories in filename priority order. Batch checks for
`.agents/skills` directories between the project root and the working
directory. Fall back to individual checks when batching is unsupported.

## Testing

Extend tests to assert batch counts for shallow and nested `AGENTS.md`
discovery and verify that metadata batches preserve result order and
per-path errors.

GitOrigin-RevId: 6cb04202a905d783454908348d008def95b9a5d6
This commit is contained in:
dozaki-openai
2026-11-23 05:39:53 +00:00
committed by copyberry
parent 794584993e
commit 5f645d732c
17 changed files with 537 additions and 45 deletions
+1
View File
@@ -470,6 +470,7 @@ callers must convert them to `file:` URIs before sending requests:
reads also back `ExecutorFileSystem::read_file_stream`)
- `fs/writeFile`
- `fs/createDirectory`
- `fs/getMetadataBatch` (requires `fsMetadataBatch`, returns metadata or an error for each input path in the same order)
- `fs/getMetadata`
- `fs/canonicalize`
- `fs/readDirectory`
+17
View File
@@ -77,6 +77,7 @@ use crate::protocol::FS_CANONICALIZE_METHOD;
use crate::protocol::FS_CLOSE_METHOD;
use crate::protocol::FS_COPY_METHOD;
use crate::protocol::FS_CREATE_DIRECTORY_METHOD;
use crate::protocol::FS_GET_METADATA_BATCH_METHOD;
use crate::protocol::FS_GET_METADATA_METHOD;
use crate::protocol::FS_OPEN_METHOD;
use crate::protocol::FS_READ_BLOCK_METHOD;
@@ -94,6 +95,8 @@ use crate::protocol::FsCopyParams;
use crate::protocol::FsCopyResponse;
use crate::protocol::FsCreateDirectoryParams;
use crate::protocol::FsCreateDirectoryResponse;
use crate::protocol::FsGetMetadataBatchParams;
use crate::protocol::FsGetMetadataBatchResponse;
use crate::protocol::FsGetMetadataParams;
use crate::protocol::FsGetMetadataResponse;
use crate::protocol::FsOpenMode;
@@ -1086,6 +1089,20 @@ impl ExecServerClient {
.await?)
}
pub(crate) fn supports_metadata_batch(&self) -> bool {
self.inner
.environment_info
.get()
.is_some_and(|info| info.capabilities.fs_metadata_batch)
}
pub(crate) async fn fs_get_metadata_batch(
&self,
params: FsGetMetadataBatchParams,
) -> Result<FsGetMetadataBatchResponse, ExecServerError> {
self.call(FS_GET_METADATA_BATCH_METHOD, &params).await
}
pub async fn fs_get_metadata(
&self,
params: FsGetMetadataParams,
+64 -1
View File
@@ -24,6 +24,7 @@ use crate::protocol::CAPABILITY_ROOTS_DISCOVER_METHOD;
use crate::protocol::FS_CANONICALIZE_METHOD;
use crate::protocol::FS_COPY_METHOD;
use crate::protocol::FS_CREATE_DIRECTORY_METHOD;
use crate::protocol::FS_GET_METADATA_BATCH_METHOD;
use crate::protocol::FS_GET_METADATA_METHOD;
use crate::protocol::FS_OPEN_METHOD;
use crate::protocol::FS_READ_DIRECTORY_METHOD;
@@ -37,6 +38,8 @@ use crate::protocol::FsCopyParams;
use crate::protocol::FsCopyResponse;
use crate::protocol::FsCreateDirectoryParams;
use crate::protocol::FsCreateDirectoryResponse;
use crate::protocol::FsGetMetadataBatchParams;
use crate::protocol::FsGetMetadataBatchResponse;
use crate::protocol::FsGetMetadataParams;
use crate::protocol::FsGetMetadataResponse;
use crate::protocol::FsOpenMode;
@@ -77,6 +80,8 @@ pub(crate) enum FsHelperRequest {
CreateDirectory(FsCreateDirectoryParams),
#[serde(rename = "fs/getMetadata")]
GetMetadata(FsGetMetadataParams),
#[serde(rename = "fs/getMetadataBatch")]
GetMetadataBatch(FsGetMetadataBatchParams),
#[serde(rename = "fs/canonicalize")]
Canonicalize(FsCanonicalizeParams),
#[serde(rename = "fs/readDirectory")]
@@ -115,7 +120,7 @@ pub(crate) struct FsHelperOpenResponse {
pub(crate) file_handle: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "operation", content = "response")]
pub(crate) enum FsHelperPayload {
#[serde(rename = "capabilities/loadDiscoveries")]
@@ -132,6 +137,8 @@ pub(crate) enum FsHelperPayload {
CreateDirectory(FsCreateDirectoryResponse),
#[serde(rename = "fs/getMetadata")]
GetMetadata(FsGetMetadataResponse),
#[serde(rename = "fs/getMetadataBatch")]
GetMetadataBatch(FsGetMetadataBatchResponse),
#[serde(rename = "fs/canonicalize")]
Canonicalize(FsCanonicalizeResponse),
#[serde(rename = "fs/readDirectory")]
@@ -154,6 +161,7 @@ impl FsHelperPayload {
Self::WriteFile(_) => FS_WRITE_FILE_METHOD,
Self::CreateDirectory(_) => FS_CREATE_DIRECTORY_METHOD,
Self::GetMetadata(_) => FS_GET_METADATA_METHOD,
Self::GetMetadataBatch(_) => FS_GET_METADATA_BATCH_METHOD,
Self::Canonicalize(_) => FS_CANONICALIZE_METHOD,
Self::ReadDirectory(_) => FS_READ_DIRECTORY_METHOD,
Self::Walk(_) => FS_WALK_METHOD,
@@ -222,6 +230,18 @@ impl FsHelperPayload {
}
}
pub(crate) fn expect_get_metadata_batch(
self,
) -> Result<FsGetMetadataBatchResponse, JSONRPCErrorError> {
match self {
Self::GetMetadataBatch(response) => Ok(response),
other => Err(unexpected_response(
FS_GET_METADATA_BATCH_METHOD,
other.operation(),
)),
}
}
pub(crate) fn expect_canonicalize(self) -> Result<FsCanonicalizeResponse, JSONRPCErrorError> {
match self {
Self::Canonicalize(response) => Ok(response),
@@ -366,6 +386,21 @@ pub(crate) async fn run_direct_request(
modified_at_ms: metadata.modified_at_ms,
}))
}
FsHelperRequest::GetMetadataBatch(params) => {
let results = codex_file_system::resolve_metadata_batch(
&file_system,
&params.paths,
GetMetadataOptions {
follow_symlinks: params.follow_symlinks.unwrap_or(true),
},
/*sandbox*/ None,
)
.await
.map_err(map_fs_error)?;
Ok(FsHelperPayload::GetMetadataBatch(encode_metadata_batch(
results,
)))
}
FsHelperRequest::Canonicalize(params) => {
let path = file_system
.canonicalize(&params.path, /*sandbox*/ None)
@@ -430,6 +465,34 @@ pub(crate) async fn run_direct_request(
}
}
pub(crate) fn encode_metadata_batch(
results: Vec<io::Result<crate::FileMetadata>>,
) -> FsGetMetadataBatchResponse {
FsGetMetadataBatchResponse {
results: results
.into_iter()
.map(|result| result.map_err(map_fs_error))
.collect(),
}
}
pub(crate) fn decode_metadata_batch(
response: FsGetMetadataBatchResponse,
expected: usize,
) -> io::Result<Vec<io::Result<crate::FileMetadata>>> {
if response.results.len() != expected {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"invalid metadata batch response",
));
}
Ok(response
.results
.into_iter()
.map(|result| result.map_err(crate::sandboxed_file_system::map_sandbox_error))
.collect())
}
pub(crate) fn map_fs_error(err: io::Error) -> JSONRPCErrorError {
match err.kind() {
io::ErrorKind::NotFound => not_found(err.to_string()),
@@ -344,6 +344,18 @@ impl ExecutorFileSystem for LocalFileSystem {
Box::pin(LocalFileSystem::get_metadata(self, path, options, sandbox))
}
fn get_metadata_batch<'a>(
&'a self,
paths: &'a [PathUri],
options: GetMetadataOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<io::Result<FileMetadata>>> {
Box::pin(async move {
let (fs, sandbox) = self.file_system_for_reads(sandbox)?;
fs.get_metadata_batch(paths, options, sandbox).await
})
}
fn read_directory<'a>(
&'a self,
path: &'a PathUri,
@@ -7,6 +7,7 @@ use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use bytes::Bytes;
use codex_file_system::FILE_WRITE_CHUNK_SIZE;
use codex_file_system::metadata_batch_fits;
use codex_protocol::models::ManagedFileSystemPermissions;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemPath;
@@ -43,6 +44,7 @@ use crate::protocol::FsCanonicalizeParams;
use crate::protocol::FsCloseParams;
use crate::protocol::FsCopyParams;
use crate::protocol::FsCreateDirectoryParams;
use crate::protocol::FsGetMetadataBatchParams;
use crate::protocol::FsGetMetadataParams;
use crate::protocol::FsOpenMode;
use crate::protocol::FsOpenParams;
@@ -499,6 +501,38 @@ impl ExecutorFileSystem for RemoteFileSystem {
Box::pin(RemoteFileSystem::get_metadata(self, path, options, sandbox))
}
fn get_metadata_batch<'a>(
&'a self,
paths: &'a [PathUri],
options: GetMetadataOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<io::Result<FileMetadata>>> {
Box::pin(async move {
let Some((first_path, rest)) = paths.split_first() else {
return Ok(Vec::new());
};
let client = self.client.get().await.map_err(map_remote_error)?;
let convention = first_path.infer_path_convention();
if !client.supports_metadata_batch()
|| !metadata_batch_fits(paths)
|| rest
.iter()
.any(|path| path.infer_path_convention() != convention)
{
return Err(io::ErrorKind::Unsupported.into());
}
let response = client
.fs_get_metadata_batch(FsGetMetadataBatchParams {
paths: paths.to_vec(),
follow_symlinks: (!options.follow_symlinks).then_some(false),
sandbox: read_sandbox(&client, first_path, sandbox).await?.cloned(),
})
.await
.map_err(map_remote_error)?;
crate::fs_helper::decode_metadata_batch(response, paths.len())
})
}
fn read_directory<'a>(
&'a self,
path: &'a PathUri,
@@ -1,6 +1,7 @@
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use codex_exec_server_protocol::JSONRPCErrorError;
use codex_file_system::metadata_batch_fits;
use codex_utils_path_uri::PathUri;
use tokio::io;
use tokio_util::io::ReaderStream;
@@ -32,6 +33,7 @@ use crate::fs_sandbox::FileSystemSandboxRunner;
use crate::protocol::FsCanonicalizeParams;
use crate::protocol::FsCopyParams;
use crate::protocol::FsCreateDirectoryParams;
use crate::protocol::FsGetMetadataBatchParams;
use crate::protocol::FsGetMetadataParams;
use crate::protocol::FsOpenMode;
use crate::protocol::FsReadDirectoryParams;
@@ -412,6 +414,36 @@ impl ExecutorFileSystem for SandboxedFileSystem {
))
}
fn get_metadata_batch<'a>(
&'a self,
paths: &'a [PathUri],
options: GetMetadataOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<io::Result<FileMetadata>>> {
Box::pin(async move {
if paths.is_empty() {
return Ok(Vec::new());
}
if !metadata_batch_fits(paths) {
return Err(io::ErrorKind::Unsupported.into());
}
let sandbox = require_platform_sandbox(sandbox)?;
let response = self
.run_sandboxed(
sandbox,
FsHelperRequest::GetMetadataBatch(FsGetMetadataBatchParams {
paths: paths.to_vec(),
follow_symlinks: (!options.follow_symlinks).then_some(false),
sandbox: None,
}),
)
.await?
.expect_get_metadata_batch()
.map_err(map_sandbox_error)?;
crate::fs_helper::decode_metadata_batch(response, paths.len())
})
}
fn read_directory<'a>(
&'a self,
path: &'a PathUri,
@@ -477,7 +509,7 @@ fn require_platform_sandbox(
})
}
fn map_sandbox_error(error: JSONRPCErrorError) -> io::Error {
pub(crate) fn map_sandbox_error(error: JSONRPCErrorError) -> io::Error {
match error.code {
-32004 => io::Error::new(io::ErrorKind::NotFound, error.message),
-32600 => io::Error::new(io::ErrorKind::InvalidInput, error.message),
@@ -26,6 +26,8 @@ use crate::protocol::FsCopyParams;
use crate::protocol::FsCopyResponse;
use crate::protocol::FsCreateDirectoryParams;
use crate::protocol::FsCreateDirectoryResponse;
use crate::protocol::FsGetMetadataBatchParams;
use crate::protocol::FsGetMetadataBatchResponse;
use crate::protocol::FsGetMetadataParams;
use crate::protocol::FsGetMetadataResponse;
use crate::protocol::FsOpenParams;
@@ -235,6 +237,38 @@ impl FileSystemHandler {
Ok(FsCreateDirectoryResponse {})
}
pub(crate) async fn get_metadata_batch(
&self,
params: FsGetMetadataBatchParams,
) -> Result<FsGetMetadataBatchResponse, JSONRPCErrorError> {
if !codex_file_system::metadata_batch_fits(&params.paths) {
return Err(invalid_request(
"metadata batch exceeds size limit".to_string(),
));
}
let options = GetMetadataOptions {
follow_symlinks: params.follow_symlinks.unwrap_or(true),
};
let results = match self
.file_system
.get_metadata_batch(&params.paths, options, params.sandbox.as_ref())
.await
{
Err(error) if error.kind() == io::ErrorKind::Unsupported => {
codex_file_system::resolve_metadata_batch(
&self.file_system,
&params.paths,
options,
params.sandbox.as_ref(),
)
.await
}
result => result,
}
.map_err(map_fs_error)?;
Ok(crate::fs_helper::encode_metadata_batch(results))
}
pub(crate) async fn get_metadata(
&self,
params: FsGetMetadataParams,
@@ -39,6 +39,8 @@ use crate::protocol::FsCopyParams;
use crate::protocol::FsCopyResponse;
use crate::protocol::FsCreateDirectoryParams;
use crate::protocol::FsCreateDirectoryResponse;
use crate::protocol::FsGetMetadataBatchParams;
use crate::protocol::FsGetMetadataBatchResponse;
use crate::protocol::FsGetMetadataParams;
use crate::protocol::FsGetMetadataResponse;
use crate::protocol::FsOpenParams;
@@ -419,6 +421,14 @@ impl ExecServerHandler {
.map_err(|error| crate::rpc::internal_error(error.to_string()))?
}
pub(crate) async fn fs_get_metadata_batch(
&self,
params: FsGetMetadataBatchParams,
) -> Result<FsGetMetadataBatchResponse, JSONRPCErrorError> {
self.require_initialized_for("filesystem")?;
self.file_system.get_metadata_batch(params).await
}
pub(crate) async fn fs_get_metadata(
&self,
params: FsGetMetadataParams,
@@ -21,6 +21,7 @@ use crate::protocol::FS_CANONICALIZE_METHOD;
use crate::protocol::FS_CLOSE_METHOD;
use crate::protocol::FS_COPY_METHOD;
use crate::protocol::FS_CREATE_DIRECTORY_METHOD;
use crate::protocol::FS_GET_METADATA_BATCH_METHOD;
use crate::protocol::FS_GET_METADATA_METHOD;
use crate::protocol::FS_OPEN_METHOD;
use crate::protocol::FS_READ_BLOCK_METHOD;
@@ -31,6 +32,7 @@ use crate::protocol::FS_WALK_METHOD;
use crate::protocol::FS_WRITE_BLOCK_METHOD;
use crate::protocol::FS_WRITE_FILE_METHOD;
use crate::protocol::FsCloseParams;
use crate::protocol::FsGetMetadataBatchParams;
use crate::protocol::FsReadBlockParams;
use crate::protocol::FsWriteBlockParams;
use crate::protocol::HTTP_REQUEST_METHOD;
@@ -193,6 +195,12 @@ pub(crate) fn build_router() -> RpcRouter<ExecServerHandler> {
handler.fs_watch_missing(params).await
},
);
router.request(
FS_GET_METADATA_BATCH_METHOD,
|handler: Arc<ExecServerHandler>, params: FsGetMetadataBatchParams| async move {
handler.fs_get_metadata_batch(params).await
},
);
router.request(
FS_GET_METADATA_METHOD,
|handler: Arc<ExecServerHandler>, params: WireFsGetMetadataParams| async move {
@@ -131,6 +131,49 @@ async fn file_system_get_metadata_reports_files_and_directories(
);
assert!(directory_metadata.modified_at_ms > 0);
let nested = directory_path.join("note.txt");
std::fs::write(&nested, "nested")?;
let paths = [
PathUri::from_host_native_path(&nested)?,
PathUri::from_host_native_path(tmp.path().join("missing"))?,
PathUri::from_host_native_path(&directory_path)?,
];
let batch = file_system
.get_metadata_batch(&paths, Default::default(), /*sandbox*/ None)
.await;
if matches!(implementation, FileSystemImplementation::Local) {
assert_eq!(
batch
.expect_err("unrestricted local metadata keeps the original short-circuit path")
.kind(),
std::io::ErrorKind::Unsupported
);
return Ok(());
}
let results = batch?;
assert_eq!(results.len(), paths.len());
assert!(results[0].as_ref().expect("file metadata").is_file);
assert_eq!(
results[1].as_ref().expect_err("missing metadata").kind(),
std::io::ErrorKind::NotFound
);
assert!(
results[2]
.as_ref()
.expect("directory metadata")
.is_directory
);
#[cfg(unix)]
{
std::fs::remove_file(&nested)?;
std::os::unix::fs::symlink("note.txt", &nested)?;
let results = file_system
.get_metadata_batch(&paths, Default::default(), /*sandbox*/ None)
.await?;
assert!(results[0].is_err(), "individual path errors are preserved");
assert!(results[2].as_ref().expect("later result").is_directory);
}
Ok(())
}