Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/webcodex-core/src/runner_protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1278,6 +1278,8 @@ pub enum RunnerConfigErrorField {
SkillsRoots,
#[serde(rename = "instructions.files")]
InstructionsFiles,
#[serde(rename = "policy.managed_worktree_root")]
ManagedWorktreeRoot,
#[serde(rename = "shell.max_persistent_shells")]
ShellMaxPersistentShells,
#[serde(rename = "shell.persistent_shell_idle_timeout_secs")]
Expand Down
83 changes: 83 additions & 0 deletions crates/webcodex-runner/src/main_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2008,6 +2008,89 @@ fn concurrent_managed_worktree_bootstraps_choose_distinct_runner_paths() {
assert_eq!(load_runner_project_summaries_from_dir(&registry).len(), 3);
}

#[test]
fn managed_worktree_uses_configured_central_root_without_changing_identity() {
let tmp = tempfile::tempdir().unwrap();
let other_root = tempfile::tempdir().unwrap();
let source = tmp.path().join("source");
let central = tmp.path().join("central");
let registry = tmp.path().join("project-registry");
seed_managed_worktree_repo(&source);
std::fs::create_dir(&central).unwrap();
let central = central.canonicalize().unwrap();
register_managed_source_project(&registry, &source);
let mut policy = project_policy(tmp.path());
policy.allowed_roots = vec![
other_root.path().canonicalize().unwrap(),
tmp.path().canonicalize().unwrap(),
];
policy.managed_worktree_root = Some(central.clone());
let request = managed_worktree_request(
&source,
serde_json::Value::Null,
"77777777-7777-4777-8777-777777777777",
None,
);

let result = project_ok(handle_prepare_managed_worktree(
&policy, &registry, &request,
));
let path = PathBuf::from(result["path"].as_str().unwrap());
assert_eq!(path.parent(), Some(central.as_path()));
assert_eq!(result["outcome"], "managed_worktree_created");
assert_eq!(result["managed"], true);
}

#[test]
fn managed_worktree_resume_revalidates_current_root_without_retargeting_old_path() {
let tmp = tempfile::tempdir().unwrap();
let source = tmp.path().join("source");
let central = tmp.path().join("central");
let replacement = tmp.path().join("replacement");
let registry = tmp.path().join("project-registry");
seed_managed_worktree_repo(&source);
std::fs::create_dir(&central).unwrap();
std::fs::create_dir(&replacement).unwrap();
register_managed_source_project(&registry, &source);

let mut initial_policy = project_policy(tmp.path());
initial_policy.managed_worktree_root = Some(central.canonicalize().unwrap());
let request = managed_worktree_request(
&source,
serde_json::Value::Null,
"88888888-8888-4888-8888-888888888888",
None,
);
let created = project_ok(handle_prepare_managed_worktree(
&initial_policy,
&registry,
&request,
));
let old_path = created["path"].clone();

let mut reloaded_policy = project_policy(tmp.path());
reloaded_policy.managed_worktree_root = Some(replacement.canonicalize().unwrap());
let resume = managed_worktree_request(
&source,
serde_json::Value::Null,
"99999999-9999-4999-8999-999999999999",
created["agent_project_id"].as_str(),
);
let resumed = project_ok(handle_prepare_managed_worktree(
&reloaded_policy,
&registry,
&resume,
));
assert_eq!(resumed["outcome"], "managed_worktree_recovered");
assert_eq!(resumed["path"], old_path);
assert_eq!(
Path::new(resumed["path"].as_str().unwrap())
.parent()
.unwrap(),
central.canonicalize().unwrap()
);
}

#[test]
fn managed_worktree_git_source_without_registered_project_does_not_infer_lineage() {
let tmp = tempfile::tempdir().unwrap();
Expand Down
115 changes: 115 additions & 0 deletions crates/webcodex-runner/src/main_tests/config_reload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,121 @@ fn instruction_files_do_not_expand_project_allowed_roots() {
assert_eq!(config.instructions.files, vec![instruction_file]);
}

#[test]
fn managed_worktree_root_is_hot_reloadable_and_rejects_invalid_values() {
let (tmp, path, runtime) = reload_fixture();
// An explicit temp root is portable: "/" is not the Temp directory's
// drive on Windows and must not authorize the configured worktree root.
let allowed_root = format!(
"policy.allowed_roots = [{:?}]",
tmp.path().canonicalize().unwrap().to_string_lossy()
);
let central = tmp.path().join("central-worktrees");
std::fs::create_dir(&central).unwrap();
let central = central.canonicalize().unwrap();
let valid = reload_toml(
"oe",
None,
60,
1024,
"sh",
"native",
false,
"claude",
"project_search_generation_1",
)
.replace("policy.allowed_roots = [\"/\"]", &allowed_root)
.replace(
"policy.max_output_bytes = 1024",
&format!(
"policy.max_output_bytes = 1024\npolicy.managed_worktree_root = {:?}",
central.to_string_lossy()
),
);
std::fs::write(&path, valid).unwrap();
let checked = runtime.check_config();
assert_eq!(checked.valid, Some(true));
assert!(!checked.restart_required);
assert_eq!(runtime.reload().generation, 2);
assert_eq!(
runtime.snapshot().policy.managed_worktree_root,
Some(central.clone())
);

std::fs::write(
&path,
reload_toml(
"oe",
None,
60,
1024,
"sh",
"native",
false,
"claude",
"project_search_generation_2",
)
.replace("policy.allowed_roots = [\"/\"]", &allowed_root)
.replace(
"policy.max_output_bytes = 1024",
&format!(
"policy.max_output_bytes = 1024\npolicy.managed_worktree_root = {:?}",
tmp.path().join("missing").to_string_lossy()
),
),
)
.unwrap();
let rejected = runtime.check_config();
assert_eq!(rejected.valid, Some(false));
assert_eq!(
rejected.error_field,
Some(runner_protocol::RunnerConfigErrorField::ManagedWorktreeRoot)
);
assert_eq!(
rejected.error_reason,
Some(runner_protocol::RunnerConfigErrorReason::InvalidPath)
);
assert_eq!(
runtime.snapshot().policy.managed_worktree_root,
Some(central)
);

#[cfg(unix)]
{
use std::os::unix::fs::symlink;
let target = tmp.path().join("real-central");
let redirected = tmp.path().join("redirected-central");
std::fs::create_dir(&target).unwrap();
symlink(&target, &redirected).unwrap();
let candidate = reload_toml(
"oe",
None,
60,
1024,
"sh",
"native",
false,
"claude",
"project_search_generation_3",
)
.replace("policy.allowed_roots = [\"/\"]", &allowed_root)
.replace(
"policy.max_output_bytes = 1024",
&format!(
"policy.max_output_bytes = 1024\npolicy.managed_worktree_root = {:?}",
redirected.to_string_lossy()
),
);
std::fs::write(&path, candidate).unwrap();
let checked = runtime.check_config();
assert_eq!(checked.valid, Some(false));
assert_eq!(
checked.error_field,
Some(runner_protocol::RunnerConfigErrorField::ManagedWorktreeRoot)
);
}
}

#[test]
fn invalid_instruction_paths_are_structured_config_diagnostics() {
let (_tmp, path, runtime) = reload_fixture();
Expand Down
54 changes: 53 additions & 1 deletion crates/webcodex-runner/src/webcodex_runner/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,51 @@ pub(crate) struct InstructionsConfig {
pub(crate) files: Vec<PathBuf>,
}

fn validate_managed_worktree_root_config(policy: &RunnerPolicy) -> Result<(), String> {
let Some(path) = policy.managed_worktree_root.as_ref() else {
return Ok(());
};
if !path.is_absolute() || webcodex_runner_config::paths::project_path_has_parent_traversal(path)
{
return Err(
"policy.managed_worktree_root must be an absolute path without parent traversal"
.to_string(),
);
}
let metadata = std::fs::symlink_metadata(path).map_err(|error| {
format!("policy.managed_worktree_root must be an existing directory: {error}")
})?;
if metadata.file_type().is_symlink() || !metadata.is_dir() {
return Err(
"policy.managed_worktree_root must be an existing non-redirected directory".to_string(),
);
}
let canonical = std::fs::canonicalize(path).map_err(|error| {
format!("policy.managed_worktree_root cannot be canonicalized: {error}")
})?;
if !webcodex_runner_config::paths::paths_equal(path, &canonical) {
return Err(
"policy.managed_worktree_root must not contain redirected path components".to_string(),
);
}
let roots =
webcodex_runner_config::paths::canonicalize_usable_allowed_roots(&policy.allowed_roots);
if !roots
.iter()
.any(|root| webcodex_runner_config::paths::path_is_within(&canonical, root))
{
return Err(
"policy.managed_worktree_root must be inside effective allowed_roots".to_string(),
);
}
Ok(())
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub(crate) struct SkillsConfig {
#[serde(default)]
pub(crate) roots: Vec<PathBuf>,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct RunnerConfig {
pub(crate) server_url: String,
Expand Down Expand Up @@ -375,6 +414,11 @@ pub(crate) struct RunnerPolicy {
pub(crate) allow_cwd_anywhere: bool,
#[serde(default)]
pub(crate) allowed_roots: Vec<PathBuf>,
/// Optional operator-selected central namespace for new managed
/// worktrees. It is validated against the effective roots at config load
/// and revalidated against the live filesystem before each operation.
#[serde(default)]
pub(crate) managed_worktree_root: Option<PathBuf>,
#[serde(default = "default_max_timeout_secs")]
pub(crate) max_timeout_secs: u64,
/// Per-stream Runner capture/presentation policy for stdout and stderr.
Expand All @@ -389,6 +433,7 @@ impl Default for RunnerPolicy {
allow_raw_shell: true,
allow_cwd_anywhere: false,
allowed_roots: Vec::new(),
managed_worktree_root: None,
max_timeout_secs: DEFAULT_MAX_TIMEOUT_SECS,
max_output_bytes: DEFAULT_MAX_OUTPUT_BYTES,
}
Expand Down Expand Up @@ -1072,6 +1117,12 @@ fn reload_error_diagnostic(
Some(RunnerConfigErrorReason::InvalidPath),
);
}
if error.starts_with("policy.managed_worktree_root") {
return (
Some(RunnerConfigErrorField::ManagedWorktreeRoot),
Some(RunnerConfigErrorReason::InvalidPath),
);
}
OUT_OF_RANGE_FIELDS
.iter()
.find_map(|(prefix, field)| {
Expand Down Expand Up @@ -1649,6 +1700,7 @@ pub(crate) fn load_config_with_server_url(
let effective =
effective_allowed_roots(&cfg.policy.allowed_roots, cfg.policy.allow_cwd_anywhere)?;
cfg.policy.allowed_roots = effective;
validate_managed_worktree_root_config(&cfg.policy)?;
if cfg.project_registry_dir.is_none() {
cfg.project_registry_dir = Some(default_project_registry_dir()?);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ fn fixture() -> (tempfile::TempDir, PathBuf, PathBuf, RunnerPolicy) {
allow_raw_shell: true,
allow_cwd_anywhere: false,
allowed_roots: vec![project.clone()],
managed_worktree_root: None,
max_timeout_secs: 30,
max_output_bytes: 16 * 1024,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ fn fixture() -> (tempfile::TempDir, PathBuf, PathBuf, RunnerPolicy) {
allow_raw_shell: true,
allow_cwd_anywhere: false,
allowed_roots: vec![project.clone()],
managed_worktree_root: None,
max_timeout_secs: 30,
max_output_bytes: 16 * 1024,
};
Expand Down
Loading
Loading