diff --git a/apps/desktop/src-tauri/src/project_inventory.rs b/apps/desktop/src-tauri/src/project_inventory.rs index 9c829d2ef..8b0763a7b 100644 --- a/apps/desktop/src-tauri/src/project_inventory.rs +++ b/apps/desktop/src-tauri/src/project_inventory.rs @@ -35,6 +35,14 @@ fn unavailable() -> DesktopError { ) } +pub(crate) fn revision_changed() -> DesktopError { + DesktopError::new( + "project_revision_changed", + "The project changed since confirmation", + "Review the current project again before removing it.", + ) +} + fn uncertain() -> DesktopError { DesktopError::new("project_unregister_uncertain", "The unregister outcome could not be confirmed", "Refresh the Runner inventory before taking further action. No automatic retry or folder deletion was attempted.") } @@ -67,50 +75,69 @@ pub async fn observe_many( return Err(unavailable()); } } - let value = crate::workspace::post( + let exact = |project: &str| json!({"project":project,"limit":1,"summary_only":false}); + let params = if projects.len() == 1 { + exact(&projects[0]) + } else { + json!({"client_id":target.client_id,"limit":100,"summary_only":false}) + }; + let page = list_for_removal(runtime, params).await?; + let rows = page + .get("projects") + .and_then(Value::as_array) + .ok_or_else(unavailable)?; + let mut observations = Vec::with_capacity(projects.len()); + for project in projects { + let exact_page; + let row = match rows.iter().find(|row| row["id"].as_str() == Some(project)) { + Some(row) => row, + None if projects.len() > 1 && page["truncated"].as_bool() == Some(true) => { + exact_page = list_for_removal(runtime, exact(project)).await?; + exact_page["projects"] + .as_array() + .and_then(|rows| rows.iter().find(|row| row["id"].as_str() == Some(project))) + .ok_or_else(unavailable)? + } + None => return Err(unavailable()), + }; + let revision = row + .get("revision") + .and_then(Value::as_str) + .filter(|s| { + s.len() == 71 + && s.starts_with("sha256:") + && s[7..].bytes().all(|b| b.is_ascii_hexdigit()) + }) + .ok_or_else(unavailable)?; + let path = row + .get("path") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .ok_or_else(unavailable)?; + observations.push(UnregisterObservation { + target: target.clone(), + project: project.clone(), + expected_revision: revision.to_owned(), + path: path.to_owned(), + }); + } + Ok(observations) +} + +async fn list_for_removal(runtime: &StoredRuntime, params: Value) -> DesktopResult { + let mut value = crate::workspace::post( runtime, "/api/tools/call", - json!({"tool":"list_projects","params":{}}), + json!({"tool":"list_projects","params":params}), Duration::from_secs(12), ) .await?; if value.get("success").and_then(Value::as_bool) != Some(true) { return Err(unavailable()); } - let rows = value - .pointer("/output/projects") - .and_then(Value::as_array) - .ok_or_else(unavailable)?; - projects - .iter() - .map(|project| { - let row = rows - .iter() - .find(|row| row.get("id").and_then(Value::as_str) == Some(project)) - .ok_or_else(unavailable)?; - let revision = row - .get("revision") - .and_then(Value::as_str) - .filter(|s| { - s.len() == 71 - && s.starts_with("sha256:") - && s[7..].bytes().all(|b| b.is_ascii_hexdigit()) - }) - .ok_or_else(unavailable)?; - let path = row - .get("path") - .and_then(Value::as_str) - .filter(|s| !s.is_empty()) - .ok_or_else(unavailable)?; - Ok(UnregisterObservation { - target: target.clone(), - project: project.clone(), - expected_revision: revision.to_owned(), - path: path.to_owned(), - }) - }) - .collect() + Ok(value["output"].take()) } + pub async fn unregister( runtime: &StoredRuntime, request: &UnregisterRequest, @@ -121,12 +148,37 @@ pub async fn unregister( } let observation = observe(runtime, &request.project).await?; if observation.expected_revision != request.expected_revision { - return Err(unavailable()); + return Err(revision_changed()); } let value = crate::workspace::post(runtime, "/api/tools/call", json!({"tool":"unregister_project", "params":{"project":request.project,"expected_revision":request.expected_revision}}), Duration::from_secs(40)).await.map_err(|_| uncertain())?; if value.get("success").and_then(Value::as_bool) != Some(true) { - // Do not expose arbitrary upstream text or infer that a failed response had no effects. - return Err(uncertain()); + return Err( + match value.pointer("/output/error/code").and_then(Value::as_str) { + Some("project_projection_reconcile_required") + if value.pointer("/output/project").and_then(Value::as_str) + == Some(&request.project) + && matches!( + value + .pointer("/output/authoritative_outcome") + .and_then(Value::as_str), + Some("unregistered" | "already_unregistered") + ) => + { + DesktopError::new( + "project_projection_reconcile_required", + "Runner confirmed removal but Server inventory is pending", + "Refresh the inventory before taking further action.", + ) + } + Some("active_jobs_conflict") => DesktopError::new( + "active_jobs_conflict", + "The project still has active jobs", + "Wait for those jobs to finish before removing the project.", + ), + Some("revision_conflict") => revision_changed(), + _ => uncertain(), + }, + ); } let output = value.get("output").ok_or_else(uncertain)?; if output.get("project").and_then(Value::as_str) != Some(&request.project) @@ -242,6 +294,9 @@ pub async fn unregister_batch( Some("not_attempted_after_uncertain_outcome") => { "not_attempted_after_uncertain_outcome" } + Some("project_projection_reconcile_required") => { + "project_projection_reconcile_required" + } Some("active_jobs_conflict") => "active_jobs_conflict", Some("revision_conflict") => "revision_conflict", Some("project_not_found") => "project_not_found", diff --git a/apps/desktop/src-tauri/src/project_inventory/tests.rs b/apps/desktop/src-tauri/src/project_inventory/tests.rs index 4c2bfeead..5edd6faf8 100644 --- a/apps/desktop/src-tauri/src/project_inventory/tests.rs +++ b/apps/desktop/src-tauri/src/project_inventory/tests.rs @@ -127,7 +127,29 @@ async fn observe_many_uses_one_inventory_request() { .unwrap(); assert_eq!(rows.len(), 1); assert_eq!(rows[0].path, "D:\\repo"); - assert_eq!(task.await.unwrap().len(), 1); + let calls = task.await.unwrap(); + assert_eq!(calls.len(), 1); + assert_eq!(calls[0]["params"]["project"], "agent:mini:repo"); +} + +#[tokio::test] +async fn batch_observation_finds_a_selected_registration_beyond_the_first_page() { + let mut page = inventory(); + page["output"]["truncated"] = json!(true); + let mut exact = inventory(); + exact["output"]["projects"][0]["id"] = json!("agent:mini:last"); + let (url, calls) = server(vec![page, exact]).await; + let fixture = Fixture::new(url); + let rows = observe_many( + &fixture.runtime, + &["agent:mini:repo".into(), "agent:mini:last".into()], + ) + .await + .unwrap(); + assert_eq!(rows[1].project, "agent:mini:last"); + let calls = calls.await.unwrap(); + assert_eq!(calls.len(), 2); + assert_eq!(calls[1]["params"]["project"], "agent:mini:last"); } #[tokio::test] @@ -161,7 +183,8 @@ async fn changed_revision_never_dispatches_removal() { let fixture = Fixture::new(url); let mut request = fixture.request(); request.expected_revision = format!("sha256:{}", "b".repeat(64)); - assert!(unregister(&fixture.runtime, &request).await.is_err()); + let error = unregister(&fixture.runtime, &request).await.unwrap_err(); + assert_eq!(error.code, "project_revision_changed"); assert_eq!(task.await.unwrap().len(), 1); } @@ -192,6 +215,26 @@ async fn rejection_and_wrong_project_outcomes_are_not_retried() { } } +#[tokio::test] +async fn projection_failure_reports_only_an_exact_confirmed_removal() { + for (project, code) in [ + ("agent:mini:repo", "project_projection_reconcile_required"), + ("agent:other:repo", "project_unregister_uncertain"), + ] { + let response = json!({"success":false,"output":{ + "error":{"code":"project_projection_reconcile_required"}, + "authoritative_outcome":"unregistered","project":project + }}); + let (url, calls) = server(vec![inventory(), response]).await; + let fixture = Fixture::new(url); + let error = unregister(&fixture.runtime, &fixture.request()) + .await + .unwrap_err(); + assert_eq!(error.code, code); + assert_eq!(calls.await.unwrap().len(), 2); + } +} + #[test] fn forget_only_removes_exact_runner_registration_and_clears_default() { let fixture = Fixture::new("http://127.0.0.1:1".into()); diff --git a/apps/desktop/src-tauri/src/state/app_state.rs b/apps/desktop/src-tauri/src/state/app_state.rs index 70908bf47..ac45786e7 100644 --- a/apps/desktop/src-tauri/src/state/app_state.rs +++ b/apps/desktop/src-tauri/src/state/app_state.rs @@ -120,8 +120,10 @@ impl AppState { "Choose an existing directory that this account can access.", ) })?; - let canonical_roots = - webcodex_runner_config::paths::canonicalize_usable_allowed_roots(&effective_roots); + let canonical_roots = webcodex_runner_config::paths::canonicalize_usable_allowed_roots( + &effective_roots, + &canonical_project, + ); Ok::<_, DesktopError>( webcodex_runner_config::paths::validate_project_path_policy( &canonical_project, diff --git a/apps/desktop/src-tauri/src/state/environment.rs b/apps/desktop/src-tauri/src/state/environment.rs index b4cfa04ee..0ba0bd44e 100644 --- a/apps/desktop/src-tauri/src/state/environment.rs +++ b/apps/desktop/src-tauri/src/state/environment.rs @@ -378,12 +378,12 @@ pub(super) fn adopt_saved_environment(config: &mut StoredDesktopConfig) { .find(|entry| entry.path == *path) .map(|entry| format!("agent:{client}:{}", entry.id)) }); - ProjectSelection { - path: path.to_string_lossy().into_owned(), - allowed_root: path.to_string_lossy().into_owned(), - is_git_repository: path.join(".git").exists(), - runtime_project_id, + let mut selected = saved_project_selection(path, config.project.as_ref()); + if webcodex_runner_config::paths::project_path_probe_allowed(path, None) { + selected.is_git_repository = path.join(".git").exists(); } + selected.runtime_project_id = runtime_project_id; + selected }); config.persistent_environment = Some(record.environment_id); config.topology = Some(RuntimeTopology { @@ -509,10 +509,27 @@ pub(super) fn legacy_inventory_projects( Ok(projects) } +fn saved_project_selection(path: &Path, previous: Option<&ProjectSelection>) -> ProjectSelection { + let spelling = path.to_string_lossy().into_owned(); + ProjectSelection { + path: spelling.clone(), + allowed_root: spelling, + is_git_repository: previous.is_some_and(|project| { + webcodex_runner_config::paths::paths_equal(Path::new(&project.path), path) + && project.is_git_repository + }), + runtime_project_id: None, + } +} + fn same_desktop_path(left: &Path, right: &Path) -> bool { + use webcodex_runner_config::paths::project_path_probe_allowed; if left == right { return true; } + if !project_path_probe_allowed(left, None) || !project_path_probe_allowed(right, None) { + return false; + } match (std::fs::canonicalize(left), std::fs::canonicalize(right)) { (Ok(a), Ok(b)) => a == b, _ => false, @@ -1407,10 +1424,14 @@ impl DesktopCore { .cloned() }); let project = if let Some(path) = selected.as_ref() { - let mut project = self - .adapter - .inspect_project(&path.to_string_lossy()) - .await?; + let mut project = + if webcodex_runner_config::paths::project_path_probe_allowed(path, None) { + self.adapter + .inspect_project(&path.to_string_lossy()) + .await? + } else { + saved_project_selection(path, self.config.project.as_ref()) + }; if let (Some(client), Some(entry)) = ( record.runner_client_id.as_deref(), record diff --git a/apps/desktop/src-tauri/src/state/workspace.rs b/apps/desktop/src-tauri/src/state/workspace.rs index b1d6a8668..986cc1e31 100644 --- a/apps/desktop/src-tauri/src/state/workspace.rs +++ b/apps/desktop/src-tauri/src/state/workspace.rs @@ -116,7 +116,7 @@ impl AppState { let observations = crate::project_inventory::observe_many(&runtime, &ids).await?; for (item, observed) in request.items.iter().zip(observations.iter()) { if observed.expected_revision != item.expected_revision { - return Err(crate::workspace::unavailable()); + return Err(crate::project_inventory::revision_changed()); } } let items = @@ -178,14 +178,8 @@ impl AppState { crate::webcodex::settings::verify_target(&runtime, &request.target)?; let observed = crate::project_inventory::observe(&runtime, &request.project).await?; - if observed.expected_revision != request.expected_revision - || observed.path.is_empty() - { - return Err(DesktopError::new( - "project_revision_changed", - "The project changed since confirmation", - "Review the current project again before removing it.", - )); + if observed.expected_revision != request.expected_revision { + return Err(crate::project_inventory::revision_changed()); } let store = super::environment::store()?; let mut native = webcodex_environment::NativeEnvironment::new() diff --git a/apps/desktop/src-tauri/src/webcodex/settings.rs b/apps/desktop/src-tauri/src/webcodex/settings.rs index f4b22e817..706b0e66a 100644 --- a/apps/desktop/src-tauri/src/webcodex/settings.rs +++ b/apps/desktop/src-tauri/src/webcodex/settings.rs @@ -249,6 +249,17 @@ fn validate(paths: &[String]) -> DesktopResult<()> { } fn validate_allowed_roots(current: &[String], roots: &[String]) -> DesktopResult<()> { + // A config written by the CLI can already exceed the Desktop add limit. + // An exact deletion preserves the spelling and order of every survivor + // and needs no filesystem access (including for unavailable WSL shares). + let mut existing = current.iter(); + if roots.len() < current.len() + && roots + .iter() + .all(|root| existing.by_ref().any(|old| old == root)) + { + return Ok(()); + } validate(roots)?; for root in roots { if current.iter().any(|existing| { diff --git a/apps/desktop/src-tauri/src/webcodex/settings/tests.rs b/apps/desktop/src-tauri/src/webcodex/settings/tests.rs index c32eda10d..3385c8448 100644 --- a/apps/desktop/src-tauri/src/webcodex/settings/tests.rs +++ b/apps/desktop/src-tauri/src/webcodex/settings/tests.rs @@ -267,6 +267,24 @@ fn file_access_can_remove_stale_roots_one_at_a_time() { assert_eq!(projection.file_access.configured_roots, vec![stale_b]); } +#[test] +fn file_access_can_revoke_from_oversized_configuration_without_adding_authority() { + let f = Fixture::new(); + let original = (0..23) + .map(|i| { + f.dir + .join(format!("stale-{i}")) + .to_string_lossy() + .into_owned() + }) + .collect::>(); + let mut remaining = original.clone(); + remaining.remove(10); + validate_allowed_roots(&original, &remaining).unwrap(); + remaining[0] = f.dir.to_string_lossy().into_owned(); + assert!(validate_allowed_roots(&original, &remaining).is_err()); +} + #[cfg(windows)] #[test] fn file_access_accepts_existing_windows_drive_root() { diff --git a/apps/desktop/src/features/projects/ProjectsPanel.tsx b/apps/desktop/src/features/projects/ProjectsPanel.tsx index bbef76ba7..af093adf8 100644 --- a/apps/desktop/src/features/projects/ProjectsPanel.tsx +++ b/apps/desktop/src/features/projects/ProjectsPanel.tsx @@ -1,3 +1,4 @@ +import { normalizeDesktopError } from "../../i18n/presentation"; import { useEffect, useMemo, useRef, useState } from "react"; import { Button, Select, TextInput } from "@mantine/core"; import { Search } from "lucide-react"; @@ -50,7 +51,7 @@ export function ProjectsPanel({ onComputerSettings, onState }: { onComputerSetti }; const [removal, setRemoval] = useState(null); const [removing, setRemoving] = useState(false); - const [removeError, setRemoveError] = useState(false); + const [removeError, setRemoveError] = useState(null); const [selected, setSelected] = useState([]); const [batchConfirm, setBatchConfirm] = useState(null); const [batchProgress, setBatchProgress] = useState(""); @@ -78,7 +79,7 @@ export function ProjectsPanel({ onComputerSettings, onState }: { onComputerSetti setRemoval(null); setBatchConfirm(null); setBatchIssues([]); - setRemoveError(false); + setRemoveError(null); }, [workspace.contextKey]); const canManageProjects = Boolean(onState && workspace.state.workspace_runner); @@ -86,12 +87,12 @@ export function ProjectsPanel({ onComputerSettings, onState }: { onComputerSetti if (!canManageProjects || removing || workspace.state.current_operation || !project.id) return; const owner = beginRemoval(); if (!owner) return; - setRemoveError(false); + setRemoveError(null); try { const observation = await desktopApi.prepareProjectUnregister(project.id); if (removalOwner.current === owner) setRemoval(observation); - } catch { - if (removalOwner.current === owner) setRemoveError(true); + } catch (error) { + if (removalOwner.current === owner) setRemoveError(normalizeDesktopError(error).code); } finally { finishRemoval(owner); } @@ -101,15 +102,15 @@ export function ProjectsPanel({ onComputerSettings, onState }: { onComputerSetti if (!removal || !onState || removing || workspace.state.current_operation) return; const owner = beginRemoval(); if (!owner) return; - setRemoveError(false); + setRemoveError(null); try { const state = await desktopApi.unregisterProject(removal); if (removalOwner.current === owner) { onState(state); workspace.removeProject(removal.project); } - } catch { - if (removalOwner.current === owner) setRemoveError(true); + } catch (error) { + if (removalOwner.current === owner) setRemoveError(normalizeDesktopError(error).code); } finally { if (removalOwner.current === owner) { setRemoval(null); @@ -125,7 +126,7 @@ export function ProjectsPanel({ onComputerSettings, onState }: { onComputerSetti if (!ids.length) return; const owner = beginRemoval(); if (!owner) return; - setRemoveError(false); + setRemoveError(null); setBatchIssues([]); setBatchConfirm(null); try { @@ -142,8 +143,8 @@ export function ProjectsPanel({ onComputerSettings, onState }: { onComputerSetti // The confirmation owns these exact paths and revisions. Never replace // them with a fresh inventory after the user has confirmed. setBatchConfirm(observations); - } catch { - if (removalOwner.current === owner) setRemoveError(true); + } catch (error) { + if (removalOwner.current === owner) setRemoveError(normalizeDesktopError(error).code); } finally { finishRemoval(owner); } @@ -154,7 +155,7 @@ export function ProjectsPanel({ onComputerSettings, onState }: { onComputerSetti const observations = batchConfirm; const owner = beginRemoval(); if (!owner) return; - setRemoveError(false); + setRemoveError(null); setBatchIssues([]); setBatchConfirm(null); try { @@ -173,9 +174,9 @@ export function ProjectsPanel({ onComputerSettings, onState }: { onComputerSetti setSelected(current => current.filter(id => id !== observation.project)); completed++; setBatchProgress(`${completed}/${observations.length}`); - } catch { + } catch (error) { if (removalOwner.current === owner) { - setRemoveError(true); + setRemoveError(normalizeDesktopError(error).code); setBatchIssues([observation.project]); } return; @@ -193,13 +194,13 @@ export function ProjectsPanel({ onComputerSettings, onState }: { onComputerSetti const issues = result.items.filter(item => !item.success).map(item => `${item.project}: ${item.status}`); if (issues.length || result.items.length !== chunk.length) { setBatchIssues(issues.length ? issues : chunk.map(item => item.project)); - setRemoveError(true); + setRemoveError("project_unregister_uncertain"); return; } } } - } catch { - if (removalOwner.current === owner) setRemoveError(true); + } catch (error) { + if (removalOwner.current === owner) setRemoveError(normalizeDesktopError(error).code); } finally { if (removalOwner.current === owner) { setBatchProgress(""); @@ -245,7 +246,7 @@ export function ProjectsPanel({ onComputerSettings, onState }: { onComputerSetti setSelected(current => checked ? Array.from(new Set([...current, id])) : current.filter(value => value !== id)) : undefined} selected={selected} busy={removing || Boolean(workspace.state.current_operation)} /> - {removeError &&

{p("unregisterError")}

} + {removeError &&

{p(removeError === "project_projection_reconcile_required" ? "unregisterSyncPending" : "unregisterError")} {removeError}

} {batchIssues.length > 0 &&
    {batchIssues.map(issue =>
  • {issue}
  • )}
} {batchConfirm && setBatchConfirm(null)} busy={removing}>

{p("unregisterDescription")}

diff --git a/apps/desktop/src/i18n/product.ts b/apps/desktop/src/i18n/product.ts index a948a2aa3..053138965 100644 --- a/apps/desktop/src/i18n/product.ts +++ b/apps/desktop/src/i18n/product.ts @@ -203,6 +203,7 @@ export const PRODUCT_MESSAGES = { removeSelectedProjects: ["Remove selected ({count})", "批量移除({count})", "Ausgewählte entfernen ({count})", "Retirer la sélection ({count})", "選択項目を削除 ({count})", "선택 항목 제거 ({count})", "批量移除({count})"], failedProjects: ["Unremoved projects", "未移除的项目", "Nicht entfernte Projekte", "Projets non retirés", "削除されなかったプロジェクト", "제거되지 않은 프로젝트", "未移除的專案"], unregisterDescription: ["Only the WebCodex project registration is removed. Your folder and Git files stay on disk, and file access permissions are unchanged. Active jobs may prevent removal.", "只从 WebCodex 项目列表中移除此注册,不会删除磁盘上的文件夹或 Git 文件,也不会更改文件访问权限。有运行中的任务时可能无法移除。", "Nur die WebCodex-Projektregistrierung wird entfernt. Ordner und Git-Dateien bleiben auf dem Datenträger, und die Dateizugriffsrechte ändern sich nicht. Aktive Jobs können dies verhindern.", "Seule l’inscription du projet WebCodex est retirée. Le dossier et les fichiers Git restent sur le disque et les autorisations d’accès aux fichiers ne changent pas. Des tâches actives peuvent bloquer l’opération.", "WebCodex のプロジェクト登録だけを削除します。フォルダーと Git ファイルはディスクに残り、ファイルアクセス権限も変わりません。実行中のジョブがある場合は削除できないことがあります。", "WebCodex 프로젝트 등록만 제거합니다. 폴더와 Git 파일은 디스크에 남고 파일 접근 권한도 변경되지 않습니다. 실행 중인 작업이 있으면 제거가 차단될 수 있습니다.", "只從 WebCodex 專案清單中移除此註冊,不會刪除磁碟上的資料夾或 Git 檔案,也不會變更檔案存取權限。有執行中的工作時可能無法移除。"], + unregisterSyncPending: ["The Runner confirmed removal. Refresh the project list to verify Server synchronization.", "Runner 已确认取消注册。请刷新项目列表,核对 Server 的同步状态。", "Der Runner hat die Entfernung bestätigt. Aktualisieren Sie die Projektliste, um die Serversynchronisierung zu prüfen.", "Le Runner a confirmé le retrait. Actualisez la liste des projets pour vérifier la synchronisation du serveur.", "Runner が登録解除を確認しました。プロジェクト一覧を更新してサーバーの同期状態を確認してください。", "Runner가 등록 해제를 확인했습니다. 프로젝트 목록을 새로 고쳐 서버 동기화 상태를 확인하세요.", "Runner 已確認取消註冊。請重新整理專案清單,核對 Server 的同步狀態。"], unregisterError: ["Unregister was not confirmed. Refresh the inventory before trying again; the Runner may be busy or the registration may have changed.", "尚未确认取消注册成功。请先刷新项目列表;Runner 可能正忙,或注册状态已变化。", "Entfernung nicht bestätigt. Vor einem neuen Versuch die Liste aktualisieren.", "Désinscription non confirmée. Actualisez la liste avant de réessayer.", "登録解除を確認できません。再試行前に一覧を更新してください。", "등록 해제를 확인하지 못했습니다. 다시 시도하기 전에 목록을 새로 고치세요.", "尚未確認取消註冊成功。請先重新整理專案清單;Runner 可能正忙,或註冊狀態已變化。"], projectAccessHelp: ["Projects and file access", "项目与文件访问", "Projekte und Dateizugriff", "Projets et accès aux fichiers", "プロジェクトとファイルアクセス", "프로젝트 및 파일 접근", "專案與檔案存取"], selectProject: ["Select {name}", "选择 {name}", "{name} auswählen", "Sélectionner {name}", "{name} を選択", "{name} 선택", "選擇 {name}"], diff --git a/crates/webcodex-cli/src/webcodex_cli/connect/profile.rs b/crates/webcodex-cli/src/webcodex_cli/connect/profile.rs index 2575c3583..ba20387ad 100644 --- a/crates/webcodex-cli/src/webcodex_cli/connect/profile.rs +++ b/crates/webcodex-cli/src/webcodex_cli/connect/profile.rs @@ -360,7 +360,11 @@ pub(crate) fn read_enabled_project_count(project_registry_dir: &Path) -> Result< } pub(super) fn stored_project_matches(project: &ProjectFile, canonical_project: &Path) -> bool { - Path::new(&project.path).canonicalize().is_ok_and(|path| { + webcodex_runner_config::paths::canonicalize_project_candidate( + Path::new(&project.path), + canonical_project, + ) + .is_some_and(|path| { // Windows `canonicalize` can return `\\?\`-prefixed extended paths and // the filesystem is case-insensitive, so identity uses the shared // normalization instead of raw `Path` equality. diff --git a/crates/webcodex-cli/src/webcodex_cli/project.rs b/crates/webcodex-cli/src/webcodex_cli/project.rs index 0c9f4132d..ac44fe5bf 100644 --- a/crates/webcodex-cli/src/webcodex_cli/project.rs +++ b/crates/webcodex-cli/src/webcodex_cli/project.rs @@ -102,17 +102,27 @@ fn authorize_canonical_project( // Root discovery may return empty when HOME is absent: this local explicit // selection supplies its own root below. The actual policy flag is unchanged. let effective_roots = webcodex_runner_config::effective_allowed_roots(configured_roots, true)?; - let canonical_roots = - webcodex_runner_config::paths::canonicalize_usable_allowed_roots(&effective_roots); + let canonical_roots = webcodex_runner_config::paths::canonicalize_usable_allowed_roots( + &effective_roots, + canonical_project, + ); match webcodex_runner_config::paths::validate_project_path_policy( canonical_project, &canonical_roots, allow_cwd_anywhere, ) { - // Preserve the pre-existing local registration/output contract: callers - // see canonical usable roots when no authority extension was needed. - Ok(()) => Ok((canonical_roots, false)), + Ok(()) => { + // Report configured grants that were deliberately left unprobed as well. + let mut reported = canonical_roots; + reported.extend(effective_roots.into_iter().filter(|root| { + !webcodex_runner_config::paths::project_path_probe_allowed( + root, + Some(canonical_project), + ) + })); + Ok((reported, false)) + } Err(_) => { // Only local CLI/Desktop callers reach this helper. The explicit // selection grants the exact canonical root, never its parent. @@ -508,13 +518,14 @@ async fn reconcile_project_from_inventory( }; let candidate = Path::new(path); if webcodex_runner_config::paths::paths_equal(candidate, canonical_project) - || candidate - .canonicalize() - .ok() - .as_ref() - .is_some_and(|resolved| { - webcodex_runner_config::paths::paths_equal(resolved, canonical_project) - }) + || webcodex_runner_config::paths::canonicalize_project_candidate( + candidate, + canonical_project, + ) + .as_ref() + .is_some_and(|resolved| { + webcodex_runner_config::paths::paths_equal(resolved, canonical_project) + }) { return Ok(Some(project.clone())); } diff --git a/crates/webcodex-core/src/runner_operation.rs b/crates/webcodex-core/src/runner_operation.rs index 97d773350..1bb029e8c 100644 --- a/crates/webcodex-core/src/runner_operation.rs +++ b/crates/webcodex-core/src/runner_operation.rs @@ -463,6 +463,7 @@ pub enum RunnerProjectOperationKind { Register, Create, ResolveOrRegister, + ProbeIdentity, PrepareManagedWorktree, LifecycleEnable, LifecycleDisable, @@ -476,6 +477,7 @@ impl RunnerProjectOperationKind { Self::Register => "register_project", Self::Create => "create_project", Self::ResolveOrRegister => "resolve_or_register_project", + Self::ProbeIdentity => "project_probe_identity", Self::PrepareManagedWorktree => "prepare_managed_worktree", Self::LifecycleEnable => "project_lifecycle_enable", Self::LifecycleDisable => "project_lifecycle_disable", @@ -489,6 +491,7 @@ impl RunnerProjectOperationKind { "register_project" => Self::Register, "create_project" => Self::Create, "resolve_or_register_project" => Self::ResolveOrRegister, + "project_probe_identity" => Self::ProbeIdentity, "prepare_managed_worktree" => Self::PrepareManagedWorktree, "project_lifecycle_enable" => Self::LifecycleEnable, "project_lifecycle_disable" => Self::LifecycleDisable, @@ -3450,6 +3453,7 @@ mod tests { RunnerProjectOperationKind::Register, RunnerProjectOperationKind::Create, RunnerProjectOperationKind::ResolveOrRegister, + RunnerProjectOperationKind::ProbeIdentity, RunnerProjectOperationKind::PrepareManagedWorktree, RunnerProjectOperationKind::LifecycleEnable, RunnerProjectOperationKind::LifecycleDisable, @@ -3530,6 +3534,7 @@ mod tests { "register_project", "create_project", "resolve_or_register_project", + "project_probe_identity", "prepare_managed_worktree", "project_lifecycle_enable", "project_lifecycle_disable", diff --git a/crates/webcodex-core/src/runner_protocol.rs b/crates/webcodex-core/src/runner_protocol.rs index 6a6be9145..9ea501b4e 100644 --- a/crates/webcodex-core/src/runner_protocol.rs +++ b/crates/webcodex-core/src/runner_protocol.rs @@ -1496,6 +1496,10 @@ pub struct RunnerProjectSummary { /// root. Missing means the Runner could not prove a current root identity. #[serde(default, skip_serializing_if = "Option::is_none")] pub root_fingerprint: Option, + /// Registered path for a root that passive inventory intentionally does not open. + /// After an explicit observation, path may hold the canonical root instead. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub deferred_root_path: Option, /// Explicit persisted lineage only. Never inferred from paths, repository /// names, Git remotes, registration provenance, or project kind. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1549,6 +1553,9 @@ pub struct ShellProjectInventoryStatus { pub last_error_code: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub last_sync_at: Option, + /// The receiving Server can verify a deferred Project root on explicit access. + #[serde(default, skip_serializing_if = "is_false")] + pub supports_deferred_roots: bool, pub max_summaries_per_page: usize, pub max_serialized_bytes_per_page: usize, } @@ -1562,6 +1569,7 @@ impl ShellProjectInventoryStatus { total_synced, last_error_code: None, last_sync_at: None, + supports_deferred_roots: true, max_summaries_per_page: PROJECT_INVENTORY_PAGE_MAX_SUMMARIES, max_serialized_bytes_per_page: PROJECT_INVENTORY_PAGE_MAX_SERIALIZED_BYTES, } @@ -1652,6 +1660,15 @@ pub struct ClaudeCodeProviderStatus { pub last_call: Option, } +/// Effective filesystem policy reported by the active Runner configuration. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct RunnerFileAccessPolicy { + #[serde(default)] + pub allow_cwd_anywhere: bool, + #[serde(default)] + pub allowed_roots: Vec, +} + /// Sanitized Runner policy summary. Carried in the registration payload and /// exposed in `runtime_status` / `list_runners`. Contains ONLY non-secret /// fields: it never includes the Agent Token, shell env values, init_script @@ -1664,10 +1681,8 @@ pub struct ClaudeCodeProviderStatus { pub struct RunnerPolicySummary { #[serde(default = "default_shell_true")] pub allow_raw_shell: bool, - #[serde(default)] - pub allow_cwd_anywhere: bool, - #[serde(default)] - pub allowed_roots: Vec, + #[serde(flatten)] + pub file_access: RunnerFileAccessPolicy, #[serde(default = "default_policy_max_timeout_secs")] pub max_timeout_secs: u64, #[serde(default = "default_policy_max_output_bytes")] @@ -1691,8 +1706,7 @@ impl Default for RunnerPolicySummary { fn default() -> Self { Self { allow_raw_shell: true, - allow_cwd_anywhere: false, - allowed_roots: Vec::new(), + file_access: RunnerFileAccessPolicy::default(), max_timeout_secs: default_policy_max_timeout_secs(), max_output_bytes: default_policy_max_output_bytes(), shell_profiles: None, @@ -2347,6 +2361,8 @@ pub struct RunnerJobCapacity { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RunnerPollPayload { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub file_access: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub job_capacity: Option, #[serde(flatten)] @@ -4306,6 +4322,7 @@ mod envelope_tests { #[test] fn runtime_metadata_and_legacy_poll_payloads_round_trip() { let env = RunnerEnvelope::RuntimeMetadata { + file_access: None, job_capacity: None, tool_providers: sample_tool_providers(), computer_session_availability: None, @@ -4327,6 +4344,7 @@ mod envelope_tests { let legacy = r#"{"client_id":"oe","agent_instance_id":"inst","projects":null}"#; let payload: RunnerPollPayload = serde_json::from_str(legacy).unwrap(); assert_eq!(payload.request.client_id, "oe"); + assert!(payload.file_access.is_none()); assert!(payload.job_capacity.is_none()); assert!(payload.tool_providers.is_none()); assert!(payload.mcp_gateway_providers.is_none()); @@ -4339,6 +4357,10 @@ mod envelope_tests { tool_providers: ToolProvidersStatus, } let envelope = RunnerEnvelope::RuntimeMetadata { + file_access: Some(RunnerFileAccessPolicy { + allow_cwd_anywhere: false, + allowed_roots: vec!["/reloaded".into()], + }), job_capacity: Some(RunnerJobCapacity { generation: 7, limit: 32, @@ -4354,15 +4376,22 @@ mod envelope_tests { old.tool_providers.config_reload.generation, sample_tool_providers().config_reload.generation ); + assert_eq!( + json["file_access"]["allowed_roots"], + serde_json::json!(["/reloaded"]) + ); + json.as_object_mut().unwrap().remove("file_access"); json.as_object_mut().unwrap().remove("job_capacity"); assert!(matches!( serde_json::from_value::(json).unwrap(), RunnerEnvelope::RuntimeMetadata { + file_access: None, job_capacity: None, .. } )); let poll = RunnerPollPayload { + file_access: None, job_capacity: Some(RunnerJobCapacity { generation: 7, limit: 32, diff --git a/crates/webcodex-core/src/runner_protocol/transport.rs b/crates/webcodex-core/src/runner_protocol/transport.rs index 26a5ad0dc..9cfb51bda 100644 --- a/crates/webcodex-core/src/runner_protocol/transport.rs +++ b/crates/webcodex-core/src/runner_protocol/transport.rs @@ -79,6 +79,8 @@ pub enum RunnerEnvelope { /// Runner -> server changed-only sanitized runtime metadata. It reuses the /// active transport and never requires an acknowledgement round trip. RuntimeMetadata { + #[serde(default, skip_serializing_if = "Option::is_none")] + file_access: Option, #[serde(default, skip_serializing_if = "Option::is_none")] job_capacity: Option, tool_providers: ToolProvidersStatus, diff --git a/crates/webcodex-environment/src/inventory/paths.rs b/crates/webcodex-environment/src/inventory/paths.rs index 2bb492464..45cdccb99 100644 --- a/crates/webcodex-environment/src/inventory/paths.rs +++ b/crates/webcodex-environment/src/inventory/paths.rs @@ -40,6 +40,9 @@ pub fn local_path_entry( return entry; } entry.configured_path = Some(path.to_path_buf()); + if !webcodex_runner_config::paths::project_path_probe_allowed(path, None) { + return entry; + } let parent = if kind == PathKind::Directory { path } else { diff --git a/crates/webcodex-environment/src/native.rs b/crates/webcodex-environment/src/native.rs index c2b26a3f9..1246007e5 100644 --- a/crates/webcodex-environment/src/native.rs +++ b/crates/webcodex-environment/src/native.rs @@ -64,7 +64,8 @@ fn project_requires_authority(config: &toml::Value, path: &Path) -> SetupResultV .unwrap_or(false); let effective = webcodex_runner_config::effective_allowed_roots(&roots, allow_cwd_anywhere) .map_err(|_| diagnostic("runner_policy", "Runner allowed roots are invalid"))?; - let canonical = webcodex_runner_config::paths::canonicalize_usable_allowed_roots(&effective); + let canonical = + webcodex_runner_config::paths::canonicalize_usable_allowed_roots(&effective, path); Ok(webcodex_runner_config::paths::validate_project_path_policy( path, &canonical, @@ -404,29 +405,11 @@ impl NativeEnvironment { })?; let prefix = format!("agent:{client_id}:"); let id = project_id.strip_prefix(&prefix).unwrap_or(project_id); - let mut pending: ProjectRemoval = - if let Some(pending) = store.read_json("remove-project.json")? { - pending - } else { - let project = record - .projects - .iter() - .find(|project| project.id == id) - .cloned() - .ok_or_else(|| { - diagnostic( - "local_project_required", - "Only a registered project of this local Runner can be removed", - ) - })?; - ProjectRemoval { - project, - revision: None, - dispatched: false, - confirmed: false, - } - }; - if pending.project.id != id { + let saved: Option = store.read_json("remove-project.json")?; + if saved + .as_ref() + .is_some_and(|pending| pending.project.id != id) + { return Err(diagnostic( "project_operation_conflict", "Another project removal is unfinished", @@ -438,7 +421,6 @@ impl NativeEnvironment { "The saved project identity is invalid", )); } - store.write_json("remove-project.json", &pending)?; let token = read_secret(&store.root().join("webcodex-user-token"))?; let selector = format!("{prefix}{id}"); let inventory = self @@ -461,6 +443,41 @@ impl NativeEnvironment { let visible = projects .iter() .find(|project| project.get("id").and_then(Value::as_str) == Some(selector.as_str())); + let mut pending = match saved { + Some(pending) => pending, + None => { + // Desktop can select an exact live registration created outside + // Environment setup. Require its observed revision before dispatch. + let project = record + .projects + .iter() + .find(|p| p.id == id) + .cloned() + .or_else(|| { + let row = visible?; + if project_id != selector || expected_revision.is_none() { + return None; + } + let path = PathBuf::from(row.get("path")?.as_str()?); + path.is_absolute().then(|| ProjectRecord { + id: id.to_owned(), + path, + }) + }) + .ok_or_else(|| { + diagnostic( + "local_project_required", + "Only a registered project of this local Runner can be removed", + ) + })?; + ProjectRemoval { + project, + revision: None, + dispatched: false, + confirmed: false, + } + } + }; if !pending.confirmed && pending.dispatched { let observation = self.observe(store, &record).await?; if visible.is_none() @@ -503,21 +520,43 @@ impl NativeEnvironment { .or_else(|| response.pointer("/output/error_code")) .or_else(|| response.pointer("/output/error_kind")) .and_then(Value::as_str); - if matches!( - code, - Some( - "active_jobs_conflict" - | "agent_unavailable" - | "unsupported_runner_version" - | "revision_conflict" - | "project_not_found" - | "invalid_request" + if code == Some("project_projection_reconcile_required") + && response.pointer("/output/project").and_then(Value::as_str) + == Some(selector.as_str()) + && matches!( + response + .pointer("/output/authoritative_outcome") + .and_then(Value::as_str), + Some("unregistered" | "already_unregistered") ) - ) { - pending.dispatched = false; - store.write_json("remove-project.json", &pending)?; + { + return Err(diagnostic( + "project_projection_reconcile_required", + "Runner confirmed removal but Server inventory is pending", + )); } - return Err(diagnostic("project_remove_rejected", "Server did not confirm removal; inspect active tasks and the project revision before retrying")); + if let Some( + code @ ("active_jobs_conflict" + | "agent_unavailable" + | "unsupported_runner_version" + | "revision_conflict" + | "project_not_found" + | "invalid_request"), + ) = code + { + // The authoritative gate rejected this operation before any effect. + std::fs::remove_file(store.root().join("remove-project.json")) + .map_err(|_| SetupDiagnostic::io())?; + return Err(SetupDiagnostic::new( + code, + "Server rejected project removal", + "Refresh the project revision and inspect active jobs before trying again", + )); + } + return Err(diagnostic( + "project_reconcile_required", + "Server did not confirm removal; reconcile this exact project before retrying", + )); } let output = tool_output(&response)?; if output.get("project").and_then(Value::as_str) != Some(selector.as_str()) @@ -537,10 +576,10 @@ impl NativeEnvironment { let mut removed: Vec = store .read_json("removed-projects.json")? .unwrap_or_default(); - if !removed.contains(&pending.project) { + if record.projects.contains(&pending.project) && !removed.contains(&pending.project) { removed.push(pending.project.clone()); + store.write_json("removed-projects.json", &removed)?; } - store.write_json("removed-projects.json", &removed)?; record.projects.retain(|project| project.id != id); if let Some(mut journal) = store.load_journal()? { journal.environment = record.clone(); diff --git a/crates/webcodex-environment/src/native/tests.rs b/crates/webcodex-environment/src/native/tests.rs index 39ce2674e..e1aabc8a6 100644 --- a/crates/webcodex-environment/src/native/tests.rs +++ b/crates/webcodex-environment/src/native/tests.rs @@ -1023,6 +1023,51 @@ fn project_authority_check_reuses_parent_root_and_expands_only_outside_it() { assert!(!project_requires_authority(&anywhere, &ordinary).unwrap()); } +#[tokio::test] +async fn confirmed_live_project_removal_accepts_a_registration_outside_setup_history() { + let temp = crate::test_tempdir().unwrap(); + let selected = temp.path().join("external-registration"); + let (url, requests, server) = fixture(4, move |request| match request.path.as_str() { + "/api/tools/call" if request.body["tool"] == "list_projects" => ( + 200, + vec![], + json!({"success":true,"output":{"projects":[{"id":"agent:alice-client:external","revision":"rev-1","path":selected}]}}), + ), + "/api/tools/call" if request.body["tool"] == "unregister_project" => ( + 200, + vec![], + json!({"success":true,"output":{"project":"agent:alice-client:external","outcome":"unregistered"}}), + ), + "/api/runtime-console/overview" => ( + 200, + vec![], + json!({"authenticated_user":"alice","service":"webcodex"}), + ), + "/api/runtime-console/runner" => (200, vec![], json!({"connected":true,"projects":[]})), + other => panic!("unexpected removal route: {other}"), + }); + let store = EnvironmentStore::open(temp.path().join("environment")).unwrap(); + atomic_private_write( + &store.root().join("webcodex-user-token"), + b"test-credential", + ) + .unwrap(); + let mut environment = record(url, None, EnvironmentMode::Join); + environment.username = Some("alice".into()); + environment.runner_client_id = Some("alice-client".into()); + store.save_environment(&environment).unwrap(); + let mut backend = NativeEnvironment::new().unwrap(); + backend + .remove_project(&store, "agent:alice-client:external", Some("rev-1")) + .await + .unwrap(); + server.join().unwrap(); + let requests = requests.lock().unwrap(); + assert_eq!(requests[1].body["params"]["expected_revision"], "rev-1"); + assert!(!store.root().join("remove-project.json").exists()); + assert!(!store.root().join("removed-projects.json").exists()); +} + #[tokio::test] async fn uncertain_project_removal_is_not_dispatched_again() { let (url, requests, server) = fixture(5, |request| match request.path.as_str() { diff --git a/crates/webcodex-runner-config/src/paths.rs b/crates/webcodex-runner-config/src/paths.rs index 24bf2cec0..d9a641375 100644 --- a/crates/webcodex-runner-config/src/paths.rs +++ b/crates/webcodex-runner-config/src/paths.rs @@ -390,6 +390,48 @@ fn is_windows_drive_root(_canonical_path: &Path) -> bool { false } +#[cfg(windows)] +pub fn wsl_distribution(path: &Path) -> Option<&std::ffi::OsStr> { + use std::path::{Component, Prefix}; + let Component::Prefix(prefix) = path.components().next()? else { + return None; + }; + match prefix.kind() { + Prefix::UNC(host, share) | Prefix::VerbatimUNC(host, share) + if host.eq_ignore_ascii_case("wsl$") || host.eq_ignore_ascii_case("wsl.localhost") => + { + Some(share) + } + _ => None, + } +} + +/// Opening a Windows WSL share can start its distribution. Inventory has no +/// target; a targeted lookup may probe that distribution only. This is an I/O +/// filter. Authorization still compares the actual canonical paths. +pub fn project_path_probe_allowed(candidate: &Path, target: Option<&Path>) -> bool { + #[cfg(windows)] + { + wsl_distribution(candidate).is_none_or(|distro| { + target + .and_then(wsl_distribution) + .is_some_and(|selected| distro.eq_ignore_ascii_case(selected)) + }) + } + #[cfg(not(windows))] + { + let _ = (candidate, target); + true + } +} + +pub fn canonicalize_project_candidate(candidate: &Path, target: &Path) -> Option { + if !project_path_probe_allowed(candidate, Some(target)) { + return None; + } + candidate.canonicalize().ok() +} + /// Canonicalize the `allowed_roots` entries that can currently provide path /// authority. /// @@ -399,10 +441,10 @@ fn is_windows_drive_root(_canonical_path: &Path) -> bool { /// Callers still apply the authoritative path policy after this projection; /// an empty result therefore remains fail-closed unless that policy explicitly /// permits the target through `allow_cwd_anywhere`. -pub fn canonicalize_usable_allowed_roots(roots: &[PathBuf]) -> Vec { +pub fn canonicalize_usable_allowed_roots(roots: &[PathBuf], target: &Path) -> Vec { roots .iter() - .filter_map(|root| root.canonicalize().ok()) + .filter_map(|root| canonicalize_project_candidate(root, target)) .filter(|root| root.is_dir()) .collect() } @@ -1031,6 +1073,34 @@ mod tests { ); } + #[cfg(windows)] + #[test] + fn wsl_probes_require_a_target_in_the_same_distribution() { + let target = Path::new(r"\\?\UNC\WSL.LOCALHOST\Dev-Ubuntu\home\user"); + for share in [ + r"\\wsl$\dev-ubuntu\home", + r"\\wsl.localhost\Dev-Ubuntu\home", + r"\\?\UNC\wsl$\Dev-Ubuntu\home", + ] { + let root = Path::new(share); + assert!(!project_path_probe_allowed(root, None)); + assert!(!project_path_probe_allowed( + root, + Some(Path::new(r"C:\project")) + )); + assert!(!project_path_probe_allowed( + root, + Some(Path::new(r"\\wsl.localhost\Dev-Ubuntu2\home")) + )); + assert!(project_path_probe_allowed(root, Some(target))); + } + assert!(project_path_probe_allowed(Path::new(r"C:\project"), None)); + assert!(project_path_probe_allowed( + Path::new(r"\\ordinary-server\wsl$\repo"), + None + )); + } + #[test] fn path_identity_is_case_insensitive_on_windows() { #[cfg(windows)] diff --git a/crates/webcodex-runner-registry/src/dispatch_fence.rs b/crates/webcodex-runner-registry/src/dispatch_fence.rs index a7a2d8df6..6bbfa270a 100644 --- a/crates/webcodex-runner-registry/src/dispatch_fence.rs +++ b/crates/webcodex-runner-registry/src/dispatch_fence.rs @@ -1,7 +1,9 @@ //! Complete admission-time identities for requests that must not retarget at dequeue. use super::state::RunnerRecord; use super::RunnerFeature; -use webcodex_core::runner_operation::{RunnerFileOperation, RunnerOperation}; +use webcodex_core::runner_operation::{ + RunnerFileOperation, RunnerOperation, RunnerProjectOperationKind, +}; #[derive(Debug, Clone)] pub(super) struct ProjectDispatchFence { @@ -38,6 +40,14 @@ pub struct PersistentShellTarget { pub(super) enum PendingDispatchFence { Unfenced, Project(ProjectDispatchFence), + ProjectIdentity { + runner_instance_id: String, + project_id: String, + path: String, + revision: String, + incarnation: String, + access: Option, + }, PersistentShell(PersistentShellTarget), McpGateway(McpGatewayDispatchFence), RunnerInstruction { @@ -64,6 +74,27 @@ impl PendingDispatchFence { operation: &RunnerOperation, ) -> Result<(), &'static str> { let valid = match (self, operation) { + (Self::Unfenced, RunnerOperation::Project(op)) + if op.kind == RunnerProjectOperationKind::ProbeIdentity => + { + false + } + ( + Self::ProjectIdentity { + project_id, + path, + revision, + incarnation, + .. + }, + RunnerOperation::Project(op), + ) => { + op.kind == RunnerProjectOperationKind::ProbeIdentity + && serde_json::from_str::(&op.payload).is_ok_and(|v| { + v == serde_json::json!({"project_id":project_id, + "path":path,"revision":revision,"incarnation":incarnation}) + }) + } (Self::Unfenced, operation) => !matches!( operation, RunnerOperation::McpGateway(_) @@ -148,6 +179,36 @@ impl PendingDispatchFence { } match self { Self::Unfenced | Self::McpGateway(_) => None, + Self::ProjectIdentity { + runner_instance_id, + project_id, + path, + revision, + incarnation, + access, + } => { + let valid = runner.is_some_and(|runner| { + runner.runner_instance_id == *runner_instance_id + && runner.disconnected_at.is_none() + && crate::now_ts().saturating_sub(runner.last_seen) + <= crate::RUNNER_ONLINE_WINDOW_SECS + && runner.project_inventory.status.sync_state == "complete" + && runner.supports(RunnerFeature::ProjectPathRegistration) + && access.as_ref().is_none_or(|a| { + super::access_control::assert_runner_access(Some(a), runner).is_ok() + }) + && runner.projects.iter().any(|p| { + p.id == *project_id + && p.deferred_root_path.as_ref() == Some(path) + && p.revision.as_ref() == Some(revision) + && p.registration_incarnation.as_ref() == Some(incarnation) + }) + }); + (!valid).then(|| { + "stale_project: Project identity observation target changed before dispatch" + .into() + }) + } Self::Computer { runner_instance_id, access, @@ -256,6 +317,8 @@ impl PendingDispatchFence { }) && runner.projects.iter().any(|project| { !project.disabled + && (project.deferred_root_path.is_none() + || project.root_fingerprint.is_some()) && shell.request.runtime_project_id == format!("agent:{}:{}", runner.client_id, project.id) && webcodex_core::runner_protocol::workflow_project_identity( diff --git a/crates/webcodex-runner-registry/src/project_inventory.rs b/crates/webcodex-runner-registry/src/project_inventory.rs index ee98673e2..ce19de9bf 100644 --- a/crates/webcodex-runner-registry/src/project_inventory.rs +++ b/crates/webcodex-runner-registry/src/project_inventory.rs @@ -26,6 +26,7 @@ fn status( total_synced, last_error_code, last_sync_at, + supports_deferred_roots: true, max_summaries_per_page: PROJECT_INVENTORY_PAGE_MAX_SUMMARIES, max_serialized_bytes_per_page: PROJECT_INVENTORY_PAGE_MAX_SERIALIZED_BYTES, } @@ -397,6 +398,27 @@ impl RunnerRegistry { completed .projects .sort_by(|left, right| left.id.cmp(&right.id)); + for project in &mut completed.projects { + if project.deferred_root_path.is_some() && project.root_fingerprint.is_none() { + if let Some(old) = runner.projects.iter().find(|old| { + old.id == project.id + && old.deferred_root_path.as_deref().unwrap_or(&old.path) + == project + .deferred_root_path + .as_deref() + .unwrap_or(&project.path) + && project.revision.is_some() + && old.revision == project.revision + && project.registration_incarnation.is_some() + && old.registration_incarnation == project.registration_incarnation + }) { + if old.root_fingerprint.is_some() { + project.path = old.path.clone(); + project.root_fingerprint = old.root_fingerprint.clone(); + } + } + } + } runner.projects = completed.projects; runner.project_inventory.status = status( "complete", diff --git a/crates/webcodex-runner-registry/src/projects.rs b/crates/webcodex-runner-registry/src/projects.rs index dc858360d..0e0c772e8 100644 --- a/crates/webcodex-runner-registry/src/projects.rs +++ b/crates/webcodex-runner-registry/src/projects.rs @@ -132,6 +132,9 @@ impl RunnerRegistry { .projects .iter() .find(|p| p.id == project && !p.disabled)?; + if registered.deferred_root_path.is_some() && registered.root_fingerprint.is_none() { + return None; + } let identity = webcodex_core::runner_protocol::workflow_project_identity( registered.root_fingerprint.as_deref(), ®istered.path, @@ -264,6 +267,47 @@ impl RunnerRegistry { Ok(runner.projects.clone()) } + /// Commit a targeted observation only to the exact still-active registration. + pub async fn record_deferred_project_root( + &self, + access: Option<&crate::RunnerAccess>, + client_id: &str, + instance: &str, + id: &str, + path: &str, + revision: &str, + incarnation: &str, + fingerprint: &str, + canonical_path: &str, + ) -> Result<(), String> { + let mut inner = self.inner.lock().await; + let runner = inner.runners.get_mut(client_id).ok_or("unknown Runner")?; + if runner.runner_instance_id != instance + || runner.disconnected_at.is_some() + || runner.project_inventory.status.sync_state != "complete" + || (access.is_some() && assert_runner_access(access, runner).is_err()) + { + return Err("stale Runner identity observation".into()); + } + let project = runner + .projects + .iter_mut() + .find(|p| p.id == id) + .ok_or("Project no longer registered")?; + if project.deferred_root_path.as_deref() != Some(path) + || project.revision.as_deref() != Some(revision) + || project.registration_incarnation.as_deref() != Some(incarnation) + { + return Err("stale Project identity observation".into()); + } + let mut observed = project.clone(); + observed.root_fingerprint = Some(fingerprint.to_owned()); + observed.path = canonical_path.to_owned(); + validate_project_summary(&observed).map_err(str::to_string)?; + *project = observed; + Ok(()) + } + /// Insert or replace a single project summary in the cached project list /// for `client_id`. Called by the runtime after a successful /// `register_project` / `create_project` Runner operation so that diff --git a/crates/webcodex-runner-registry/src/requests.rs b/crates/webcodex-runner-registry/src/requests.rs index 39923b03a..410bd94f3 100644 --- a/crates/webcodex-runner-registry/src/requests.rs +++ b/crates/webcodex-runner-registry/src/requests.rs @@ -2507,6 +2507,63 @@ impl RunnerRegistry { Ok((request_id, rx)) } + /// Observe a deferred root on the exact Runner and registration selected by the caller. + pub async fn enqueue_project_identity_probe( + &self, + client_id: &str, + instance: &str, + project: &webcodex_core::runner_protocol::RunnerProjectSummary, + access: Option<&crate::RunnerAccess>, + ) -> Result<(String, oneshot::Receiver), String> { + let revision = project.revision.clone().ok_or("missing Project revision")?; + let incarnation = project + .registration_incarnation + .clone() + .ok_or("missing Project incarnation")?; + let path = project + .deferred_root_path + .clone() + .ok_or("Project root is not deferred")?; + let operation = RunnerOperation::Project(RunnerProjectOperation { + kind: RunnerProjectOperationKind::ProbeIdentity, + payload: serde_json::json!({"project_id":project.id,"path":path, + "revision":revision,"incarnation":incarnation}) + .to_string(), + }); + let fence = PendingDispatchFence::ProjectIdentity { + runner_instance_id: instance.to_owned(), + project_id: project.id.clone(), + path, + revision, + incarnation, + access: access.cloned(), + }; + let mut inner = self.inner.lock().await; + if let Some(error) = fence.synchronous_rejection(&operation, inner.runners.get(client_id)) { + return Err(error); + } + let request_id = next_request_id(); + let (tx, rx) = oneshot::channel(); + let request = encode_runner_operation( + &request_id, + client_id, + "project_identity_observation".to_owned(), + operation, + )?; + enqueue_pending_request_with_fence_locked( + self.telemetry.as_ref(), + &mut inner, + client_id, + request_id.clone(), + request, + Some(tx), + None, + fence, + )?; + notify_runner_locked(&inner, client_id); + Ok((request_id, rx)) + } + /// Enqueue one typed bounded computer request. The payload is bounded JSON /// in stdin and command is always empty. Owner/auth and the exact per-kind /// computer capability requirements are rechecked under the registry lock so a diff --git a/crates/webcodex-runner-registry/src/runners.rs b/crates/webcodex-runner-registry/src/runners.rs index 93252fefd..ab36e0144 100644 --- a/crates/webcodex-runner-registry/src/runners.rs +++ b/crates/webcodex-runner-registry/src/runners.rs @@ -33,7 +33,8 @@ use webcodex_core::coding_agent::{ }; use webcodex_core::mcp_gateway::validate_providers; use webcodex_core::runner_protocol::{ - RunnerRegisterRequest, RunnerView, RUNNER_JOB_CONCURRENCY_MAX, RUNNER_JOB_CONCURRENCY_MIN, + RunnerFileAccessPolicy, RunnerRegisterRequest, RunnerView, RUNNER_JOB_CONCURRENCY_MAX, + RUNNER_JOB_CONCURRENCY_MIN, }; use webcodex_core::runner_operation::valid_computer_control_epoch; @@ -742,48 +743,11 @@ impl RunnerRegistry { /// entire metadata update before the registry record is touched. `None` /// preserves that metadata family while `Some([])` explicitly clears it. pub async fn update_runtime_metadata( - &self, - client_id: &str, - runner_instance_id: &str, - tool_providers: Option, - mcp_gateway_providers: Option>, - ) -> Result<(), String> { - self.update_runtime_metadata_checked( - client_id, - runner_instance_id, - None, - tool_providers, - mcp_gateway_providers, - ) - .await - } - - /// Connection-scoped runtime metadata for long-lived transports. The exact - /// connection lease prevents a superseded same-instance stream from - /// overwriting current routing authority. - pub async fn update_runtime_metadata_for_connection( - &self, - client_id: &str, - runner_instance_id: &str, - connection_id: &str, - tool_providers: Option, - mcp_gateway_providers: Option>, - ) -> Result<(), String> { - self.update_runtime_metadata_checked( - client_id, - runner_instance_id, - Some(connection_id), - tool_providers, - mcp_gateway_providers, - ) - .await - } - - async fn update_runtime_metadata_checked( &self, client_id: &str, runner_instance_id: &str, expected_connection_id: Option<&str>, + file_access: Option, tool_providers: Option, mcp_gateway_providers: Option>, ) -> Result<(), String> { @@ -792,6 +756,9 @@ impl RunnerRegistry { validate_providers(providers) .map_err(|error| format!("invalid MCP gateway provider inventory: {error}"))?; } + if file_access.is_some() && tool_providers.is_none() { + return Err("Runner file access update requires a config generation".into()); + } if tool_providers.is_none() && mcp_gateway_providers.is_none() { return Ok(()); } @@ -806,16 +773,31 @@ impl RunnerRegistry { client_id )); } - if let Some(expected) = expected_connection_id { - if runner.connection_id.as_deref() != Some(expected) { - return Err(format!( - "runner {} transport connection is no longer active", - client_id - )); - } + if runner.disconnected_at.is_some() + || runner.connection_id.as_deref() != expected_connection_id + || (expected_connection_id.is_none() && runner.transport != RunnerTransport::Polling) + { + return Err(format!( + "runner {} transport connection is no longer active", + client_id + )); } if let Some(policy) = runner.policy.as_mut() { if let Some(status) = tool_providers { + let generation = status.config_reload.generation; + if let Some(active) = policy.tool_providers.as_ref() { + if generation < active.config_reload.generation + || (generation == active.config_reload.generation + && file_access + .as_ref() + .is_some_and(|access| access != &policy.file_access)) + { + return Err("stale or conflicting Runner policy generation".into()); + } + } + if let Some(access) = file_access { + policy.file_access = access; + } policy.tool_providers = Some(status); } if let Some(providers) = mcp_gateway_providers { @@ -935,7 +917,7 @@ impl RunnerRegistry { runner_instance_id: &str, status: Option, ) -> Result<(), String> { - self.update_runtime_metadata(client_id, runner_instance_id, status, None) + self.update_runtime_metadata(client_id, runner_instance_id, None, None, status, None) .await } @@ -950,10 +932,11 @@ impl RunnerRegistry { connection_id: &str, status: Option, ) -> Result<(), String> { - self.update_runtime_metadata_for_connection( + self.update_runtime_metadata( client_id, runner_instance_id, - connection_id, + Some(connection_id), + None, status, None, ) diff --git a/crates/webcodex-runner-registry/src/tests.rs b/crates/webcodex-runner-registry/src/tests.rs index 6e6fea62a..9422e59e8 100644 --- a/crates/webcodex-runner-registry/src/tests.rs +++ b/crates/webcodex-runner-registry/src/tests.rs @@ -43,6 +43,7 @@ fn agent_auth_context( fn project_summary(id: &str, path: &str) -> RunnerProjectSummary { RunnerProjectSummary { + deferred_root_path: None, registration_incarnation: None, id: id.to_string(), name: Some(id.to_string()), diff --git a/crates/webcodex-runner-registry/src/tests/connection_lease.rs b/crates/webcodex-runner-registry/src/tests/connection_lease.rs index 80c00949a..b16b22a25 100644 --- a/crates/webcodex-runner-registry/src/tests/connection_lease.rs +++ b/crates/webcodex-runner-registry/src/tests/connection_lease.rs @@ -391,12 +391,19 @@ async fn stale_connection_runtime_metadata_does_not_overwrite_current() { // Current connection B reports both observational provider status and the // authoritative MCP routing inventory in one lease-fenced metadata update. + let access = webcodex_core::runner_protocol::RunnerFileAccessPolicy { + allowed_roots: vec!["/new".into()], + allow_cwd_anywhere: false, + }; + let mut current = provider_status("claude_code"); + current.config_reload.generation = 2; registry - .update_runtime_metadata_for_connection( + .update_runtime_metadata( "oe", "inst-x", - "conn-b", - Some(provider_status("claude_code")), + Some("conn-b"), + Some(access.clone()), + Some(current.clone()), Some(mcp_inventory("mcp-b")), ) .await @@ -428,13 +435,44 @@ async fn stale_connection_runtime_metadata_does_not_overwrite_current() { ); } + for (lease, generation) in [ + (Some("conn-b"), 1), + (Some("conn-b"), 2), + (None, 3), + (Some("conn-a"), 3), + ] { + let mut delayed = current.clone(); + delayed.config_reload.generation = generation; + assert!(registry + .update_runtime_metadata( + "oe", + "inst-x", + lease, + Some(Default::default()), + Some(delayed), + None + ) + .await + .is_err()); + } + assert_eq!( + registry + .get_runner_view("oe") + .await + .unwrap() + .policy + .unwrap() + .file_access, + access + ); // Stale connection A tries to overwrite both metadata families. The exact // connection lease rejects the whole update, including MCP routing authority. let err = registry - .update_runtime_metadata_for_connection( + .update_runtime_metadata( "oe", "inst-x", - "conn-a", + Some("conn-a"), + None, Some(provider_status("native")), Some(mcp_inventory("mcp-stale")), ) @@ -476,7 +514,7 @@ async fn stale_connection_runtime_metadata_does_not_overwrite_current() { // The active connection can explicitly clear the MCP inventory. `None` // means no update, while `Some([])` is an authoritative empty inventory. registry - .update_runtime_metadata_for_connection("oe", "inst-x", "conn-b", None, Some(Vec::new())) + .update_runtime_metadata("oe", "inst-x", Some("conn-b"), None, None, Some(Vec::new())) .await .unwrap(); let inner = registry.inner.lock().await; diff --git a/crates/webcodex-runner-registry/src/tests/mcp_gateway.rs b/crates/webcodex-runner-registry/src/tests/mcp_gateway.rs index 9a04ddd54..439d065d2 100644 --- a/crates/webcodex-runner-registry/src/tests/mcp_gateway.rs +++ b/crates/webcodex-runner-registry/src/tests/mcp_gateway.rs @@ -428,7 +428,14 @@ async fn invalid_runtime_mcp_inventory_is_rejected_without_mutating_authority() }, ]; assert!(registry - .update_runtime_metadata("bridge-runner", "bridge-instance", None, Some(duplicate),) + .update_runtime_metadata( + "bridge-runner", + "bridge-instance", + None, + None, + None, + Some(duplicate), + ) .await .unwrap_err() .contains("invalid MCP gateway provider inventory")); @@ -460,6 +467,8 @@ async fn bridge_dequeue_rechecks_exact_provider_instance_after_inventory_change( "bridge-runner", "bridge-instance", None, + None, + None, Some(vec![bridge_provider("replacement-provider-instance")]), ) .await diff --git a/crates/webcodex-runner-registry/src/tests/project_inventory.rs b/crates/webcodex-runner-registry/src/tests/project_inventory.rs index ee81f4a32..43315d682 100644 --- a/crates/webcodex-runner-registry/src/tests/project_inventory.rs +++ b/crates/webcodex-runner-registry/src/tests/project_inventory.rs @@ -1111,3 +1111,108 @@ async fn staging_capacity_and_timeout_are_bounded_without_taking_runners_offline ); assert!(expired.connected); } + +#[tokio::test] +async fn deferred_project_identity_is_fenced_and_passive_refresh_keeps_only_matching_proof() { + let registry = RunnerRegistry::default(); + let client = "deferred"; + let instance = "deferred-instance"; + let mut registration = paged_registration(client, instance); + registration.capabilities.project_path_registration = true; + registry.register(registration).await.unwrap(); + let mut project = project_summary("repo", "/fixture"); + project.deferred_root_path = Some(project.path.clone()); + let revision = format!("sha256:{}", "1".repeat(64)); + let incarnation = uuid::Uuid::new_v4().to_string(); + let fingerprint = format!("wc_projroot_{}", "2".repeat(64)); + project.revision = Some(revision.clone()); + project.registration_incarnation = Some(incarnation.clone()); + apply_snapshot(®istry, client, instance, "first", 1, &[project.clone()]).await; + let target = "agent:deferred:repo"; + assert!(registry + .with_live_session_registration(None, target, "s", |_, _| ()) + .await + .is_none()); + assert!(registry + .enqueue_project_identity_probe(client, "wrong", &project, None) + .await + .is_err()); + assert!(registry + .record_deferred_project_root( + None, + client, + instance, + "repo", + "/fixture", + "wrong", + &incarnation, + &fingerprint, + "/canonical" + ) + .await + .is_err()); + assert!(registry + .record_deferred_project_root( + None, + client, + instance, + "repo", + "/fixture", + &revision, + &incarnation, + "invalid", + "/canonical" + ) + .await + .is_err()); + registry + .record_deferred_project_root( + None, + client, + instance, + "repo", + "/fixture", + &revision, + &incarnation, + &fingerprint, + "/canonical", + ) + .await + .unwrap(); + let identity = registry + .with_live_session_registration(None, target, "s", |id, _| id.to_owned()) + .await + .unwrap(); + apply_snapshot(®istry, client, instance, "second", 2, &[project.clone()]).await; + assert_eq!( + registry + .with_live_session_registration(None, target, "s", |id, _| id.to_owned()) + .await, + Some(identity) + ); + let view = registry + .get_runner_view_for_auth(client, None) + .await + .unwrap(); + assert_eq!(view.projects[0].path, "/canonical"); + assert_eq!( + view.projects[0].deferred_root_path.as_deref(), + Some("/fixture") + ); + let (request_id, _rx) = registry + .enqueue_project_identity_probe(client, instance, &project, None) + .await + .unwrap(); + project.revision = Some(format!("sha256:{}", "3".repeat(64))); + apply_snapshot(®istry, client, instance, "third", 3, &[project]).await; + assert!(registry + .with_live_session_registration(None, target, "s", |_, _| ()) + .await + .is_none()); + let inner = registry.inner.lock().await; + let pending = inner.pending_by_id.get(&request_id).unwrap(); + assert!(pending + .dispatch_fence + .synchronous_rejection(&pending.operation, inner.runners.get(client)) + .is_some()); +} diff --git a/crates/webcodex-runner-registry/src/tests/reconciliation.rs b/crates/webcodex-runner-registry/src/tests/reconciliation.rs index 0d44379c5..4741b6865 100644 --- a/crates/webcodex-runner-registry/src/tests/reconciliation.rs +++ b/crates/webcodex-runner-registry/src/tests/reconciliation.rs @@ -55,6 +55,7 @@ fn reconciliation_capabilities() -> RunnerCapabilities { fn project_summary() -> RunnerProjectSummary { RunnerProjectSummary { + deferred_root_path: None, registration_incarnation: None, id: PROJECT_ID.to_string(), name: Some("Demo".to_string()), diff --git a/crates/webcodex-runner-registry/src/validation.rs b/crates/webcodex-runner-registry/src/validation.rs index 9170a6d2b..e20fe6e5f 100644 --- a/crates/webcodex-runner-registry/src/validation.rs +++ b/crates/webcodex-runner-registry/src/validation.rs @@ -679,6 +679,13 @@ pub(super) fn validate_project_summary(project: &RunnerProjectSummary) -> Result if project.path.is_empty() || project.path.len() > 4096 || project.path.contains('\0') { return Err("project_summary_invalid_path"); } + if project + .deferred_root_path + .as_deref() + .is_some_and(|path| path.is_empty() || path.len() > 4096 || path.contains('\0')) + { + return Err("project_summary_invalid_deferred_root_path"); + } if project .name .as_deref() diff --git a/crates/webcodex-runner/src/webcodex_runner/config.rs b/crates/webcodex-runner/src/webcodex_runner/config.rs index 2caa47c74..297193a3f 100644 --- a/crates/webcodex-runner/src/webcodex_runner/config.rs +++ b/crates/webcodex-runner/src/webcodex_runner/config.rs @@ -81,8 +81,10 @@ fn validate_managed_worktree_root_config(policy: &RunnerPolicy) -> Result<(), St "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); + let roots = webcodex_runner_config::paths::canonicalize_usable_allowed_roots( + &policy.allowed_roots, + &canonical, + ); if !roots .iter() .any(|root| webcodex_runner_config::paths::path_is_within(&canonical, root)) @@ -617,6 +619,15 @@ impl HotRunnerConfig { }) } + pub(crate) fn file_access_policy( + &self, + ) -> webcodex_core::runner_protocol::RunnerFileAccessPolicy { + webcodex_core::runner_protocol::RunnerFileAccessPolicy { + allow_cwd_anywhere: self.policy.allow_cwd_anywhere, + allowed_roots: self.policy.allowed_roots.clone(), + } + } + pub(crate) fn reload_status(&self) -> RunnerConfigReloadStatus { self.reload_status.lock().unwrap().clone() } diff --git a/crates/webcodex-runner/src/webcodex_runner/dispatch.rs b/crates/webcodex-runner/src/webcodex_runner/dispatch.rs index 85ee70400..056f94bf4 100644 --- a/crates/webcodex-runner/src/webcodex_runner/dispatch.rs +++ b/crates/webcodex-runner/src/webcodex_runner/dispatch.rs @@ -5,7 +5,7 @@ use super::transport::ResultSubmission; use super::validation::handle_validation_request; use super::{ handle_browser_operation, handle_computer_operation, handle_prepare_managed_worktree_operation, - handle_project_lifecycle_operation, handle_project_operation, + handle_probe_project_identity, handle_project_lifecycle_operation, handle_project_operation, handle_resolve_or_register_project_operation, handle_runner_instruction_request, handle_runner_skill_request, run_ssh_shell_with_execution_state, CommandResult, HotRunnerConfig, PersistentShellManager, ReloadableRunnerConfig, RunnerSink, @@ -676,6 +676,12 @@ pub(crate) fn dispatch_request_with_outcome( RunnerProjectOperationKind::Register | RunnerProjectOperationKind::Create => { handle_project_operation(policy, project_registry_dir, &client_id, &operation) } + RunnerProjectOperationKind::ProbeIdentity => handle_probe_project_identity( + policy, + project_registry_dir, + &client_id, + &operation, + ), RunnerProjectOperationKind::ResolveOrRegister => { handle_resolve_or_register_project_operation( policy, diff --git a/crates/webcodex-runner/src/webcodex_runner/mod.rs b/crates/webcodex-runner/src/webcodex_runner/mod.rs index 62a111953..5f3b7a945 100644 --- a/crates/webcodex-runner/src/webcodex_runner/mod.rs +++ b/crates/webcodex-runner/src/webcodex_runner/mod.rs @@ -86,8 +86,9 @@ pub(crate) use projects::{ handle_resolve_or_register_project, load_runner_project_summaries_from_dir, }; pub(crate) use projects::{ - handle_prepare_managed_worktree_operation, handle_project_lifecycle_operation, - handle_project_operation, handle_resolve_or_register_project_operation, + handle_prepare_managed_worktree_operation, handle_probe_project_identity, + handle_project_lifecycle_operation, handle_project_operation, + handle_resolve_or_register_project_operation, }; #[cfg(test)] pub(crate) use projects::{ diff --git a/crates/webcodex-runner/src/webcodex_runner/plugin.rs b/crates/webcodex-runner/src/webcodex_runner/plugin.rs index a1731cf93..23a96ba6b 100644 --- a/crates/webcodex-runner/src/webcodex_runner/plugin.rs +++ b/crates/webcodex-runner/src/webcodex_runner/plugin.rs @@ -454,7 +454,10 @@ impl PluginManager { let Some(configured_cwd) = provider.config.cwd.as_deref() else { continue; }; - let Ok(provider_root) = Path::new(configured_cwd).canonicalize() else { + let Some(provider_root) = webcodex_runner_config::paths::canonicalize_project_candidate( + Path::new(configured_cwd), + project_root, + ) else { continue; }; if !webcodex_runner_config::paths::paths_equal(&provider_root, project_root) { diff --git a/crates/webcodex-runner/src/webcodex_runner/projects.rs b/crates/webcodex-runner/src/webcodex_runner/projects.rs index 353ad0e7b..f8d135eb5 100644 --- a/crates/webcodex-runner/src/webcodex_runner/projects.rs +++ b/crates/webcodex-runner/src/webcodex_runner/projects.rs @@ -38,7 +38,6 @@ pub(crate) use managed_worktree::handle_prepare_managed_worktree_operation; #[cfg(test)] use registration::build_project_toml; -pub(crate) use registration::handle_resolve_or_register_project_operation; #[cfg(all(test, unix))] use registration::sync_parent_dir; #[cfg(test)] @@ -46,6 +45,9 @@ pub(crate) use registration::{ fail_next_project_parent_sync_after_rename, fail_next_project_publish_before_rename, validate_project_path_policy, }; +pub(crate) use registration::{ + handle_probe_project_identity, handle_resolve_or_register_project_operation, +}; static PROJECT_REGISTRY_WRITE_LOCK: OnceLock> = OnceLock::new(); @@ -277,6 +279,71 @@ mod durability_tests { assert_eq!(projects[0].id, "demo"); } + #[test] + fn identity_probe_is_read_only_and_rechecks_exact_registration_and_policy() { + use webcodex_core::runner_operation::{RunnerProjectOperation, RunnerProjectOperationKind}; + let tmp = tempfile::tempdir().unwrap(); + let registry = tmp.path().join("registry"); + let root = tmp.path().join("root"); + std::fs::create_dir_all(®istry).unwrap(); + std::fs::create_dir_all(&root).unwrap(); + let content = build_project_toml("demo", "Demo", root.to_str().unwrap(), &None, true); + let mut project = parse_runner_project_toml(&content).unwrap(); + project.registration_incarnation = Some(uuid::Uuid::new_v4().to_string()); + let content = toml::to_string(&project).unwrap(); + let file = registry.join("demo.toml"); + std::fs::write(&file, &content).unwrap(); + let summary = runner_project_summary(&project, 1, false); + let mut payload = serde_json::json!({"project_id":"demo", "path":project.path, + "revision":summary.revision, "incarnation":project.registration_incarnation}); + let mut policy = RunnerPolicy::default(); + policy.allowed_roots = vec![root.clone()]; + let probe = |policy: &RunnerPolicy, payload: &serde_json::Value| { + handle_probe_project_identity( + policy, + ®istry, + "fixture", + &RunnerProjectOperation { + kind: RunnerProjectOperationKind::ProbeIdentity, + payload: payload.to_string(), + }, + ) + }; + let result = probe(&policy, &payload); + assert_eq!(result.exit_code, Some(0), "{result:?}"); + let output: serde_json::Value = serde_json::from_str(&result.stdout.unwrap()).unwrap(); + assert_eq!(output["outcome"], "observed"); + assert_eq!( + output["root_fingerprint"], + serde_json::json!(summary.root_fingerprint) + ); + assert_eq!(std::fs::read_to_string(&file).unwrap(), content); + #[cfg(unix)] + { + let other = tmp.path().join("other"); + std::fs::create_dir(&other).unwrap(); + policy.allowed_roots.push(other.clone()); + std::fs::remove_dir(&root).unwrap(); + std::os::unix::fs::symlink(&other, &root).unwrap(); + let result = probe(&policy, &payload); + assert_eq!(result.exit_code, Some(0), "{result:?}"); + let observed: serde_json::Value = + serde_json::from_str(&result.stdout.unwrap()).unwrap(); + assert_eq!( + observed["path"], + other.canonicalize().unwrap().to_str().unwrap() + ); + assert_ne!(observed["root_fingerprint"], output["root_fingerprint"]); + assert_eq!(observed["revision"], output["revision"]); + } + let mut denied = policy.clone(); + denied.allowed_roots = vec![registry.clone()]; + assert_ne!(probe(&denied, &payload).exit_code, Some(0)); + payload["revision"] = serde_json::json!("stale"); + assert_ne!(probe(&policy, &payload).exit_code, Some(0)); + assert_eq!(std::fs::read_to_string(&file).unwrap(), content); + } + #[cfg(unix)] #[test] fn project_summary_reports_retargeted_symlinks_as_distinct_canonical_roots() { diff --git a/crates/webcodex-runner/src/webcodex_runner/projects/catalog.rs b/crates/webcodex-runner/src/webcodex_runner/projects/catalog.rs index 1e269812c..af6d6dc68 100644 --- a/crates/webcodex-runner/src/webcodex_runner/projects/catalog.rs +++ b/crates/webcodex-runner/src/webcodex_runner/projects/catalog.rs @@ -185,7 +185,10 @@ pub(crate) fn find_project_shell_context( load_runner_project_shell_contexts_from_dir(project_registry_dir) .into_iter() .filter_map(|project| { - let project_path = PathBuf::from(&project.path).canonicalize().ok()?; + let project_path = webcodex_runner_config::paths::canonicalize_project_candidate( + Path::new(&project.path), + &cwd, + )?; // Windows filesystems are case-insensitive and `canonicalize` may // return `\\?\`-prefixed paths, so containment uses the shared // path identity rules instead of raw `==`/`starts_with`. @@ -562,15 +565,21 @@ fn runner_project_summary_with_shutdown( // identity. Report the actual root, not a mutable symlink alias, so a // retargeted project registration cannot inherit another repository's // current Workflow Session. - let canonical_root = canonicalize_existing(Path::new(&project.path)) - .ok() - .filter(|path| path.is_dir()); + let path = Path::new(&project.path); + let probe = webcodex_runner_config::paths::project_path_probe_allowed(path, None); + let canonical_root = if probe { + canonicalize_existing(path) + .ok() + .filter(|path| path.is_dir()) + } else { + None + }; let root_fingerprint = canonical_root.as_deref().map(project_root_fingerprint); let resolved_path = canonical_root .unwrap_or_else(|| PathBuf::from(&project.path)) .to_string_lossy() .to_string(); - let (git_branch, git_head, git_dirty) = if include_git { + let (git_branch, git_head, git_dirty) = if probe && include_git { let branch = run_git_capture( &resolved_path, &["rev-parse", "--abbrev-ref", "HEAD"], @@ -593,6 +602,7 @@ fn runner_project_summary_with_shutdown( // temporarily project that sentinel on the wire when there is no genuine // project kind. New Servers ignore it in favor of `registration_source`. RunnerProjectSummary { + deferred_root_path: (!probe).then(|| project.path.clone()), id: project.id.clone(), name: project.name.clone().or_else(|| Some(project.id.clone())), path: resolved_path, diff --git a/crates/webcodex-runner/src/webcodex_runner/projects/managed_worktree.rs b/crates/webcodex-runner/src/webcodex_runner/projects/managed_worktree.rs index c3bce453b..0e6ce9829 100644 --- a/crates/webcodex-runner/src/webcodex_runner/projects/managed_worktree.rs +++ b/crates/webcodex-runner/src/webcodex_runner/projects/managed_worktree.rs @@ -133,8 +133,10 @@ fn managed_worktree_namespace_candidate( let root = validate_configured_managed_worktree_root(policy, Some(source))?; return Ok(root); } - let mut roots = - webcodex_runner_config::paths::canonicalize_usable_allowed_roots(&policy.allowed_roots); + let mut roots = webcodex_runner_config::paths::canonicalize_usable_allowed_roots( + &policy.allowed_roots, + source, + ); roots.sort_by_key(|root| std::cmp::Reverse(root.components().count())); for root in roots { if !webcodex_runner_config::paths::path_is_within(source, &root) { @@ -753,8 +755,8 @@ pub(crate) fn handle_prepare_managed_worktree_operation( // an unresolvable root stays denied. The derived worktree destination is // not part of this check; allowed_roots above still governs it. let admitted = granted_roots.iter().any(|root| { - canonicalize_existing(root) - .is_ok_and(|root| webcodex_runner_config::paths::path_is_within(&source, &root)) + webcodex_runner_config::paths::canonicalize_project_candidate(root, &source) + .is_some_and(|root| webcodex_runner_config::paths::path_is_within(&source, &root)) }); if !admitted { return managed_worktree_error( diff --git a/crates/webcodex-runner/src/webcodex_runner/projects/registration.rs b/crates/webcodex-runner/src/webcodex_runner/projects/registration.rs index 9741ac930..8e1f068db 100644 --- a/crates/webcodex-runner/src/webcodex_runner/projects/registration.rs +++ b/crates/webcodex-runner/src/webcodex_runner/projects/registration.rs @@ -59,8 +59,10 @@ pub(super) fn validate_model_network_project_ingress_authority( // A configured mapped drive may canonicalize to the same UNC share. It is // safe to resolve configured roots here because those roots are already // user-authorized; never canonicalize the untrusted target before this gate. - let canonical_roots = - webcodex_runner_config::paths::canonicalize_usable_allowed_roots(&policy.allowed_roots); + let canonical_roots = webcodex_runner_config::paths::canonicalize_usable_allowed_roots( + &policy.allowed_roots, + path, + ); if canonical_roots .iter() .any(|root| webcodex_runner_config::paths::path_is_within(path, root)) @@ -189,8 +191,10 @@ pub(crate) fn validate_project_path_policy( policy: &RunnerPolicy, canonical_path: &Path, ) -> Result<(), String> { - let canonical_roots = - webcodex_runner_config::paths::canonicalize_usable_allowed_roots(&policy.allowed_roots); + let canonical_roots = webcodex_runner_config::paths::canonicalize_usable_allowed_roots( + &policy.allowed_roots, + canonical_path, + ); webcodex_runner_config::paths::validate_project_path_policy( canonical_path, &canonical_roots, @@ -364,7 +368,10 @@ pub(super) fn projects_matching_canonical_path( projects .iter() .filter_map(|project| { - let registered_path = canonicalize_existing(Path::new(&project.path)).ok()?; + let registered_path = webcodex_runner_config::paths::canonicalize_project_candidate( + Path::new(&project.path), + canonical_path, + )?; (registered_path.is_dir() && paths_equal(®istered_path, canonical_path)) .then(|| project.clone()) }) @@ -572,8 +579,69 @@ fn existing_path_resolution_result( )) } +/// An explicit, read-only observation of one exact registration. This must +/// never fall back to registration or create a directory. +pub(crate) fn handle_probe_project_identity( + policy: &RunnerPolicy, + project_registry_dir: &Path, + client_id: &str, + operation: &RunnerProjectOperation, +) -> CommandResult { + #[derive(serde::Deserialize)] + #[serde(deny_unknown_fields)] + struct Request { + project_id: String, + path: String, + revision: String, + incarnation: String, + } + let start = Instant::now(); + let fail = |code| structured_project_error_cmd(start, code, false, serde_json::json!({})); + let Ok(request) = serde_json::from_str::(&operation.payload) else { + return fail("invalid_request"); + }; + let Ok(_guard) = project_registry_write_lock().lock() else { + return fail("operation_failed"); + }; + let projects = match load_project_files_for_path_resolution(project_registry_dir) { + Ok(projects) => projects, + Err(code) => return fail(code), + }; + let mut matches = projects.iter().filter(|p| p.id == request.project_id); + let Some(project) = matches.next() else { + return fail("project_not_found"); + }; + if matches.next().is_some() + || project.path != request.path + || project_revision(project) != request.revision + || project.registration_incarnation.as_deref() != Some(request.incarnation.as_str()) + { + return fail("revision_conflict"); + } + let path = Path::new(&project.path); + if let Err(code) = validate_windows_project_root(path) { + return fail(code); + } + if let Err(code) = validate_model_network_project_ingress_authority(policy, path) { + return fail(code); + } + let Ok(canonical) = canonicalize_existing(path) else { + return fail("project_path_unavailable"); + }; + if let Err(code) = validate_windows_project_root(&canonical) { + return fail(code); + } + if !canonical.is_dir() || validate_project_path_policy(policy, &canonical).is_err() { + return fail("path_outside_allowed_roots"); + } + ok_cmd( + start, + path_resolution_success(client_id, project, &canonical, "observed", false, None), + ) +} + /// Resolve an existing Runner registration by canonical path or atomically -/// persist a new one. This is an internal Server↔Runner operation, not a +/// persist a new one. This is an internal Server-Runner operation, not a /// model-visible runtime tool. pub(crate) fn handle_resolve_or_register_project_operation( policy: &RunnerPolicy, @@ -759,9 +827,10 @@ pub(crate) fn handle_resolve_or_register_project_operation( // the grant, and the Runner filesystem allowed_roots above is a coarser // boundary that never substitutes for it. let admitted = granted_roots.iter().any(|root| { - canonicalize_existing(root).is_ok_and(|root| { - webcodex_runner_config::paths::path_is_within(&canonical_path, &root) - }) + webcodex_runner_config::paths::canonicalize_project_candidate(root, &canonical_path) + .is_some_and(|root| { + webcodex_runner_config::paths::path_is_within(&canonical_path, &root) + }) }); if !admitted { return structured_project_error_cmd( diff --git a/crates/webcodex-runner/src/webcodex_runner/shell.rs b/crates/webcodex-runner/src/webcodex_runner/shell.rs index 3ac92c465..f8a21d66f 100644 --- a/crates/webcodex-runner/src/webcodex_runner/shell.rs +++ b/crates/webcodex-runner/src/webcodex_runner/shell.rs @@ -101,8 +101,19 @@ pub(crate) struct PreparedDetachedProcessLaunch { mod desktop_mcp_env_tests; pub(crate) fn canonicalize_existing(path: &Path) -> Result { - path.canonicalize() - .map_err(|e| format!("failed to access {}: {}", path.display(), e)) + let result = path.canonicalize(); + #[cfg(windows)] + let result = result.or_else(|error| { + // The first UNC open can start a stopped WSL2 distribution and still + // return ERROR_BAD_NET_NAME. Reopen only that share, before any effect. + if error.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_BAD_NET_NAME as i32) + && webcodex_runner_config::paths::wsl_distribution(path).is_some() + { + return path.canonicalize(); + } + Err(error) + }); + result.map_err(|e| format!("failed to access {}: {}", path.display(), e)) } pub(crate) fn cwd_allowed(policy: &RunnerPolicy, cwd: &Path) -> Result<(), String> { @@ -111,7 +122,9 @@ pub(crate) fn cwd_allowed(policy: &RunnerPolicy, cwd: &Path) -> Result<(), Strin } let cwd = canonicalize_existing(cwd)?; for root in &policy.allowed_roots { - if let Ok(root) = canonicalize_existing(root) { + if let Some(root) = + webcodex_runner_config::paths::canonicalize_project_candidate(root, &cwd) + { // Case-insensitive component-wise containment on Windows. if webcodex_runner_config::paths::path_is_within(&cwd, &root) { return Ok(()); diff --git a/crates/webcodex-runner/src/webcodex_runner/transport/bootstrap.rs b/crates/webcodex-runner/src/webcodex_runner/transport/bootstrap.rs index 8807fedaa..e7f88a80b 100644 --- a/crates/webcodex-runner/src/webcodex_runner/transport/bootstrap.rs +++ b/crates/webcodex-runner/src/webcodex_runner/transport/bootstrap.rs @@ -36,6 +36,7 @@ pub(super) fn send_provider_metadata( transport, tx, RunnerEnvelope::RuntimeMetadata { + file_access: Some(config.file_access_policy()), job_capacity: Some(webcodex_core::runner_protocol::RunnerJobCapacity { generation: config.generation, limit: config.max_concurrent_jobs, diff --git a/crates/webcodex-runner/src/webcodex_runner/transport/poll_dispatch.rs b/crates/webcodex-runner/src/webcodex_runner/transport/poll_dispatch.rs index 6d5ba0774..f7c5f0601 100644 --- a/crates/webcodex-runner/src/webcodex_runner/transport/poll_dispatch.rs +++ b/crates/webcodex-runner/src/webcodex_runner/transport/poll_dispatch.rs @@ -525,6 +525,9 @@ pub(crate) fn handle_one_poll( }); let computer_session_update = webcodex_runner::computer_session::changed_availability(); let poll = RunnerPollPayload { + file_access: provider_update + .as_ref() + .map(|_| metadata_config.file_access_policy()), job_capacity: Some(webcodex_core::runner_protocol::RunnerJobCapacity { generation: metadata_config.generation, limit: metadata_config.max_concurrent_jobs, diff --git a/crates/webcodex-runner/src/webcodex_runner/transport/polling.rs b/crates/webcodex-runner/src/webcodex_runner/transport/polling.rs index 10627f43f..7f36bf128 100644 --- a/crates/webcodex-runner/src/webcodex_runner/transport/polling.rs +++ b/crates/webcodex-runner/src/webcodex_runner/transport/polling.rs @@ -265,14 +265,16 @@ pub(super) fn run_polling_session( jobs.prepared_profiles().len(), &jobs, ) { - Ok((projects_count, registered_jobs, registered_projects, _inventory_status)) => { + Ok((projects_count, registered_jobs, registered_projects, inventory_status)) => { + runtime.set_inventory_contract(&inventory_status); registered = true; lease_conflict_started = None; recovery_backoff.reset(); idle_backoff.reset(); project_refresh.mark_sent(Instant::now()); - project_inventory_sync = - Some(paged_sync_after_registration(registered_projects)); + project_inventory_sync = Some(paged_sync_after_registration( + runtime.inventory_for_server(registered_projects), + )); let sink = RunnerSink::Http(HttpSendConfig { client: client.clone(), server_url: cfg.server_url.clone(), @@ -402,7 +404,9 @@ pub(super) fn run_polling_session( None }; if let Some(projects) = refresh_projects { - project_inventory_sync = Some(ProjectInventorySync::new(projects)); + project_inventory_sync = Some(ProjectInventorySync::new( + runtime.inventory_for_server(projects), + )); } let mut project_inventory_page = None; diff --git a/crates/webcodex-runner/src/webcodex_runner/transport/project_inventory.rs b/crates/webcodex-runner/src/webcodex_runner/transport/project_inventory.rs index 3444d66cb..15447f4e9 100644 --- a/crates/webcodex-runner/src/webcodex_runner/transport/project_inventory.rs +++ b/crates/webcodex-runner/src/webcodex_runner/transport/project_inventory.rs @@ -53,6 +53,7 @@ pub(super) type ProjectScanReceiver = tokio::sync::watch::Receiver, pub(super) generation: u64, pub(super) changed: tokio::sync::watch::Sender<()>, @@ -62,6 +63,7 @@ impl Default for InitialProjectScanState { fn default() -> Self { let (changed, _) = tokio::sync::watch::channel(()); Self { + legacy_root_identity: false, receiver: None, generation: 0, changed, diff --git a/crates/webcodex-runner/src/webcodex_runner/transport/quic.rs b/crates/webcodex-runner/src/webcodex_runner/transport/quic.rs index 723b10c73..d909a60ae 100644 --- a/crates/webcodex-runner/src/webcodex_runner/transport/quic.rs +++ b/crates/webcodex-runner/src/webcodex_runner/transport/quic.rs @@ -264,7 +264,7 @@ pub(super) async fn quic_session( let ack = ack_result .map_err(|_| "quic register ack timed out".to_string())? .map_err(|e| format!("failed to read quic register ack: {}", e))?; - let _inventory_status = registered_ack(ack)?; + runtime.set_inventory_contract(®istered_ack(ack)?); provider.mark_status_reported(provider_revision); eprintln!( "{}", diff --git a/crates/webcodex-runner/src/webcodex_runner/transport/registration.rs b/crates/webcodex-runner/src/webcodex_runner/transport/registration.rs index 712ae3694..ea267dbb3 100644 --- a/crates/webcodex-runner/src/webcodex_runner/transport/registration.rs +++ b/crates/webcodex-runner/src/webcodex_runner/transport/registration.rs @@ -693,8 +693,7 @@ pub(crate) fn register_policy_summary( ) -> RunnerPolicySummary { RunnerPolicySummary { allow_raw_shell: cfg.policy.allow_raw_shell, - allow_cwd_anywhere: cfg.policy.allow_cwd_anywhere, - allowed_roots: cfg.policy.allowed_roots.clone(), + file_access: cfg.file_access_policy(), max_timeout_secs: cfg.policy.max_timeout_secs, max_output_bytes: cfg.policy.max_output_bytes, shell_profiles: Some(build_shell_profiles_summary( diff --git a/crates/webcodex-runner/src/webcodex_runner/transport/runtime.rs b/crates/webcodex-runner/src/webcodex_runner/transport/runtime.rs index bc55109f4..f5ff1d38e 100644 --- a/crates/webcodex-runner/src/webcodex_runner/transport/runtime.rs +++ b/crates/webcodex-runner/src/webcodex_runner/transport/runtime.rs @@ -90,7 +90,7 @@ impl RunnerRuntimeState { cfg: &RunnerConfig, ) -> Vec { let shutdown = self.shutdown_flag(); - cache.get_with_shutdown(cfg, Some(shutdown.as_ref())) + self.inventory_for_server(cache.get_with_shutdown(cfg, Some(shutdown.as_ref()))) } pub(super) fn project_metadata_summaries( @@ -98,7 +98,58 @@ impl RunnerRuntimeState { cfg: &RunnerConfig, ) -> Vec { let shutdown = self.shutdown_flag(); - crate::webcodex_runner::projects::load_runner_project_metadata(cfg, Some(shutdown.as_ref())) + self.inventory_for_server( + crate::webcodex_runner::projects::load_runner_project_metadata( + cfg, + Some(shutdown.as_ref()), + ), + ) + } + + pub(super) fn set_inventory_contract(&self, status: &ShellProjectInventoryStatus) { + let mut scan = self + .initial_project_scan + .lock() + .unwrap_or_else(|e| e.into_inner()); + let legacy = !status.supports_deferred_roots; + if scan.legacy_root_identity != legacy { + scan.legacy_root_identity = legacy; + scan.generation = scan.generation.wrapping_add(1); + scan.changed.send_replace(()); + } + } + + pub(super) fn inventory_for_server( + &self, + mut projects: Vec, + ) -> Vec { + let legacy = self + .initial_project_scan + .lock() + .unwrap_or_else(|e| e.into_inner()) + .legacy_root_identity; + if legacy { + // v0.5.1 hashes an absent fingerprint as a different Session identity. + // Preserve its canonical-root contract until the Server upgrades. + projects.retain_mut(|project| { + let Some(path) = project.deferred_root_path.take() else { + return true; + }; + let Ok(root) = crate::webcodex_runner::shell::canonicalize_existing(path.as_ref()) + else { + return false; + }; + if !root.is_dir() { + return false; + } + project.root_fingerprint = Some( + crate::webcodex_runner::projects::project_root_fingerprint(&root), + ); + project.path = root.to_string_lossy().into_owned(); + true + }); + } + projects } /// Registration, keepalive and the first authorized catalog must not wait diff --git a/crates/webcodex-runner/src/webcodex_runner/transport/websocket.rs b/crates/webcodex-runner/src/webcodex_runner/transport/websocket.rs index 16443b91a..3e2c4c175 100644 --- a/crates/webcodex-runner/src/webcodex_runner/transport/websocket.rs +++ b/crates/webcodex-runner/src/webcodex_runner/transport/websocket.rs @@ -140,7 +140,7 @@ where .map_err(|_| "register ack was not text".to_string())?; let ack = RunnerEnvelope::from_slice(ack_text.as_bytes()) .map_err(|e| format!("register ack is not a valid envelope: {}", e))?; - let _inventory_status = registered_ack(ack)?; + runtime.set_inventory_contract(®istered_ack(ack)?); provider.mark_status_reported(provider_revision); eprintln!( "{}", diff --git a/crates/webcodex-runner/src/webcodex_runner/transport_tests/polling_recovery.rs b/crates/webcodex-runner/src/webcodex_runner/transport_tests/polling_recovery.rs index d45c18f68..1eb027fb5 100644 --- a/crates/webcodex-runner/src/webcodex_runner/transport_tests/polling_recovery.rs +++ b/crates/webcodex-runner/src/webcodex_runner/transport_tests/polling_recovery.rs @@ -1161,16 +1161,7 @@ async fn send_registered_ack_only(ws: &mut tokio_tungstenite::WebSocketStream RunnerProjectSummary { RunnerProjectSummary { + deferred_root_path: None, registration_incarnation: None, id: id.to_string(), name: Some(id.to_string()), diff --git a/crates/webcodex-runner/src/webcodex_runner/transport_tests/stream_telemetry.rs b/crates/webcodex-runner/src/webcodex_runner/transport_tests/stream_telemetry.rs index 0512b591a..e51f2edb1 100644 --- a/crates/webcodex-runner/src/webcodex_runner/transport_tests/stream_telemetry.rs +++ b/crates/webcodex-runner/src/webcodex_runner/transport_tests/stream_telemetry.rs @@ -265,6 +265,7 @@ fn synthetic_project_summary(index: usize, path_bytes: Option) -> RunnerP None => format!("/tmp/project-{index:04}"), }; RunnerProjectSummary { + deferred_root_path: None, registration_incarnation: None, id: format!("project-{index:04}"), name: Some(format!("Project {index:04}")), @@ -299,6 +300,7 @@ fn inventory_status( total_synced, last_error_code: None, last_sync_at: Some(1), + supports_deferred_roots: true, max_summaries_per_page: PROJECT_INVENTORY_PAGE_MAX_SUMMARIES, max_serialized_bytes_per_page: PROJECT_INVENTORY_PAGE_MAX_SERIALIZED_BYTES, } @@ -489,14 +491,25 @@ fn hot_capacity_metadata_retries_backpressure_and_registration_uses_active_gener let path = temp.path().join("runner.toml"); let cfg = test_runner_config("http://127.0.0.1:1".into()); let runtime = ReloadableRunnerConfig::new(cfg.clone(), path.clone()); - std::fs::write(&path, "server_url='http://127.0.0.1:1'\ntoken='test-token'\nclient_id='oe'\nmax_concurrent_jobs=6\n").unwrap(); + std::fs::write(&path, "server_url='http://127.0.0.1:1'\ntoken='test-token'\nclient_id='oe'\nmax_concurrent_jobs=6\n[policy]\nallowed_roots=['hot-root']\n").unwrap(); assert_eq!(runtime.reload_config(1).valid, Some(true)); let (tx, mut rx) = mpsc::channel(1); tx.try_send(RunnerEnvelope::Pong { ts: 1 }).unwrap(); send_provider_metadata(transport, &tx, &runtime, Some(1)); assert!(matches!(rx.try_recv(), Ok(RunnerEnvelope::Pong { .. }))); send_provider_metadata(transport, &tx, &runtime, Some(1)); - let RunnerEnvelope::RuntimeMetadata { job_capacity: Some(capacity), .. } = rx.try_recv().unwrap() else { panic!("missing capacity"); }; + let RunnerEnvelope::RuntimeMetadata { + job_capacity: Some(capacity), + file_access: Some(access), + .. + } = rx.try_recv().unwrap() + else { + panic!("missing reload metadata"); + }; + assert_eq!( + access.allowed_roots, + vec![std::path::PathBuf::from("hot-root")] + ); assert_eq!(capacity.generation, 2); assert_eq!(capacity.limit, 6); assert_eq!(runtime.jobs.concurrency_limit(), 6); @@ -504,5 +517,6 @@ fn hot_capacity_metadata_retries_backpressure_and_registration_uses_active_gener // remains the immutable startup/transport identity. let (registered, _, _) = build_register_request_with_provider_status(&cfg, &runtime, "instance", 0, runtime.jobs.inventory()); assert_eq!(registered.job_concurrency_limit, Some(6)); + assert_eq!(registered.policy.unwrap().file_access, access); } } diff --git a/crates/webcodex-workflow-session/src/discovery_tests.rs b/crates/webcodex-workflow-session/src/discovery_tests.rs index 25480fdaf..97dd51833 100644 --- a/crates/webcodex-workflow-session/src/discovery_tests.rs +++ b/crates/webcodex-workflow-session/src/discovery_tests.rs @@ -28,21 +28,21 @@ fn discovery_filters_authority_before_counting_and_pagination() { .map(|index| create(&store, "project", &owner, &format!("task {index}"))) .collect::>(); create(&store, "other-project", &owner, "unrelated"); - let all = store.discover_sessions("project", &owner, None, 0, 1000); + let all = store.discover_sessions("project", &owner, None, None, 0, 1000); assert_eq!(all.total, 4); assert_eq!(all.sessions.len(), 4); assert_eq!(all.next_offset, None); assert!(all.sessions.iter().all(|row| ids.contains(&row.session_id))); - let first = store.discover_sessions("project", &owner, None, 0, 2); - let second = store.discover_sessions("project", &owner, None, 2, 2); + let first = store.discover_sessions("project", &owner, None, None, 0, 2); + let second = store.discover_sessions("project", &owner, None, None, 2, 2); assert_eq!(first.next_offset, Some(2)); assert_eq!(second.next_offset, None); assert_eq!([first.sessions, second.sessions].concat(), all.sessions); - let past = store.discover_sessions("project", &owner, None, usize::MAX, usize::MAX); + let past = store.discover_sessions("project", &owner, None, None, usize::MAX, usize::MAX); assert!(past.sessions.is_empty()); assert_eq!(past.total, 4); assert_eq!(past.next_offset, None); - let absent = store.discover_sessions("missing", &owner, None, 0, 10); + let absent = store.discover_sessions("missing", &owner, None, None, 0, 10); assert_eq!(absent.total, 0); assert!(absent.sessions.is_empty()); } @@ -58,7 +58,7 @@ fn discovery_redacts_bounds_titles_and_caps_inventory_rows() { "Authorization: Bearer super-secret-value", ); let long = create(&store, "project", &owner, &"界".repeat(1000)); - let page = store.discover_sessions("project", &owner, None, 0, 10); + let page = store.discover_sessions("project", &owner, None, None, 0, 10); let secret_row = page .sessions .iter() @@ -76,12 +76,12 @@ fn discovery_redacts_bounds_titles_and_caps_inventory_rows() { for _ in 0..25 { create(&store, "project", &owner, "ordinary"); } - let capped = store.discover_sessions("project", &owner, None, 0, usize::MAX); + let capped = store.discover_sessions("project", &owner, None, None, 0, usize::MAX); assert_eq!(capped.sessions.len(), 20); assert_eq!(capped.next_offset, Some(20)); assert_eq!( store - .discover_sessions("project", &owner, None, 0, 0) + .discover_sessions("project", &owner, None, None, 0, 0) .sessions .len(), 1 @@ -99,9 +99,15 @@ fn discovery_preserves_closed_cold_history_and_restart_order() { store.close_session(&closed).unwrap(); store.flush_persistence(); assert_eq!(store.status().cold_sessions, 1); - let before = store.discover_sessions("project", &owner, None, 0, 10); - let closed_page = - store.discover_sessions("project", &owner, Some(SessionLifecycle::Closed), 0, 10); + let before = store.discover_sessions("project", &owner, None, None, 0, 10); + let closed_page = store.discover_sessions( + "project", + &owner, + None, + Some(SessionLifecycle::Closed), + 0, + 10, + ); assert_eq!(closed_page.total, 1); assert_eq!(closed_page.sessions[0].session_id, closed); assert_eq!( @@ -109,21 +115,27 @@ fn discovery_preserves_closed_cold_history_and_restart_order() { 1, "discovery must not warm Active or Closed identities" ); - let active_page = - store.discover_sessions("project", &owner, Some(SessionLifecycle::Active), 0, 10); + let active_page = store.discover_sessions( + "project", + &owner, + None, + Some(SessionLifecycle::Active), + 0, + 10, + ); assert_eq!(active_page.total, 1); assert_eq!(active_page.sessions[0].session_id, active); store.flush_persistence(); let restored = SessionStore::with_persistence(ledger, 1, 10); assert_eq!( - restored.discover_sessions("project", &owner, None, 0, 10), + restored.discover_sessions("project", &owner, None, None, 0, 10), before ); assert_eq!(restored.status().cold_sessions, 2); assert_eq!(restored.status().active_cold_sessions, 1); assert_eq!( restored - .discover_sessions("project", &"b".repeat(64), None, 0, 10) + .discover_sessions("project", &"b".repeat(64), None, None, 0, 10) .total, 0 ); diff --git a/crates/webcodex-workflow-session/src/store.rs b/crates/webcodex-workflow-session/src/store.rs index df22db37d..446e12f48 100644 --- a/crates/webcodex-workflow-session/src/store.rs +++ b/crates/webcodex-workflow-session/src/store.rs @@ -939,6 +939,7 @@ impl SessionStore { &self, project: &str, owner_authority_fingerprint: &str, + project_identity: Option<&str>, lifecycle: Option, offset: usize, limit: usize, @@ -953,6 +954,7 @@ impl SessionStore { .filter(|record| { record.project() == Some(project) && record.owner_authority_fingerprint() == owner_authority_fingerprint + && project_identity.is_none_or(|id| record.project_identity() == Some(id)) }) .inspect(|_| has_project_history = true) .filter(|record| lifecycle.is_none_or(|state| record.lifecycle() == state)) @@ -970,6 +972,8 @@ impl SessionStore { self.with_record_for_query(&session_id, |record, _| { if record.project.as_deref() != Some(project) || record.owner_authority_fingerprint != owner_authority_fingerprint + || project_identity + .is_some_and(|id| record.project_identity.as_deref() != Some(id)) || lifecycle.is_some_and(|state| record.lifecycle != state) { return None; diff --git a/docs/CLI.md b/docs/CLI.md index 1142ce79f..e8a919fe8 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -167,6 +167,16 @@ Model-facing registration requires preconfigured network authority even with `allow_cwd_anywhere = true`; use a direct path without `..` components. Creating new network projects with `create_project` remains unsupported. +On Windows, background project inventory lists registrations under `\\wsl.localhost` and +`\\wsl$` from the saved configuration. Git status and the canonical root fingerprint +are omitted to keep the distribution asleep. Explicit registration and project tasks +can start the selected distribution and check the actual path. Unregistering a +project preserves its file access grant, which can be revoked separately in Desktop. +After a Server restart, the original Project Ref can list the caller’s bound Session +history while WSL is stopped. During a Runner-first upgrade, the Runner supplies +the canonical root to older Servers so existing Sessions keep their identity. +Background root checks stop once both components support deferred inventory. + Root login also provides a foreground Runner command, with a warning that project commands run as root. On Linux its system-service installation command includes `--allow-root-runner`. The same login credentials are reused. diff --git a/docs/CLI.zh-CN.md b/docs/CLI.zh-CN.md index 58c233936..1ec508405 100644 --- a/docs/CLI.zh-CN.md +++ b/docs/CLI.zh-CN.md @@ -110,6 +110,13 @@ structured unregister,再删除本地 registration;Runner 已停止时,只 `..` traversal 仍拒绝。模型注册入口仍受既有 Runner policy 约束,UNC 仍先检查网络授权。 已运行 Runner 若需要 reload,按命令输出处理。 +在 Windows 上,后台项目列表从配置读取 `\\wsl.localhost` 和 `\\wsl$` 下的注册记录。 +为避免唤醒发行版,列表会省略这些项目的 Git 状态和真实根目录指纹。显式注册项目或运行项目任务时, +Runner 可以启动目标发行版并检查实际路径。取消注册会保留文件访问授权,可在 Desktop 中单独撤销。 +Server 重启后,WSL 即使处于停止状态,原 Project Ref 仍可列出调用者已绑定的 Session 历史。 +如果先升级 Runner,它会继续向旧 Server 提供实际根目录指纹,已有 Session 可以原样续接。 +双方都支持延迟探测后,后台列表就会跳过根目录检查。 + root login 会给出可直接运行的 foreground 命令,并提示项目命令拥有 root 权限; Linux system service 安装命令明确包含 `--allow-root-runner`,无需重新 login。 diff --git a/docs/TESTING.md b/docs/TESTING.md index 139136c13..57fbe4bf6 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -77,6 +77,7 @@ adopt the CLI text ordering policy. | Runner/LSP real-process | Process-tree ownership, real shell timeout/stop, polling dispatch timing, Plugin startup, validation/Git `ManagedChild`, JobManager descendant cleanup, and native LSP child lifecycle. Runner coverage is gated by `runner-real-process-tests`, which also enables the LSP crate's `real-process-tests` feature; these tests are ignored by default execution and share the `runner_real_process_` name prefix. | Real local child processes only; no external network. Run serially because the assertions intentionally exercise OS scheduling and process teardown. | `cargo test --locked -p webcodex-runner -p webcodex-lsp --features runner-real-process-tests runner_real_process -- --ignored --test-threads=1` | | Process lifecycle real-process | `ManagedChild` ownership, graceful/forced termination, descendants, EOF, liveness, and reaping. Most lifecycle tests in the integration target are ignored; pure type/spawn-error smoke remains ordinary. | Real local helper processes and OS liveness probes. | `cargo test --locked -p webcodex-process --test managed_child -- --ignored --test-threads=1` | | Persistent-shell timing | Timeout, concurrent busy-state, close-vs-exec, idle expiry, descendant teardown, and heavy adversarial PowerShell timing/status coverage. Fast state/error/exit smoke remains ordinary. | Real shell processes; serial execution only. | `cargo test --locked -p webcodex-persistent-shell -- --ignored --test-threads=1` | +| Windows WSL2 idle and file access | Verify cold history by Project Ref, idle inventory, native Windows and WSL tasks, Session continuity and hot revocation. | Native Windows, dogfood Server and Runner binaries, one stopped disposable WSL2 distribution. The test starts and terminates that distribution. | `python scripts/e2e_windows_wsl_idle.py --distro MyTestDistro`. Add `--released-bin-dir PATH` to create the Session with released binaries and upgrade the Runner first. | | Desktop Windows real-process | Windows Desktop stdin-EOF shutdown and bounded-command process-tree reclamation. These tests are ignored by the ordinary Desktop suite and share the `desktop_real_process_windows_` name prefix. | Real local child processes only; no external network. Run serially so PowerShell startup and process teardown do not compete with the ordinary Desktop libtest pool. | `cargo test --locked --manifest-path apps/desktop/src-tauri/Cargo.toml desktop_real_process_windows_ -- --ignored --test-threads=1` | | Session ledger scale/recovery | Construct actual retained Session snapshots, restore exact Active/Closed identities, measure full-ledger writes and bounded reads at 100/1,000/10,000 minimal Sessions. The small smoke and damaged-copy checks are ordinary unit tests. | Disposable temporary files; larger experiment explicitly ignored, serial, no production data or timing threshold. | `cargo test --locked -p webcodex-workflow-session --lib session_store_scale_and_recovery -- --ignored --test-threads=1 --nocapture` | | slow/manual ignored | Valuable coverage that is local but slow, serial, large-input, or global-state-sensitive. | Explicit operator opt-in; often `--ignored` and `--test-threads=1`. | Run the specific ignored test/filter documented by its subsystem. | diff --git a/scripts/e2e_session_continuity_ws.py b/scripts/e2e_session_continuity_ws.py index 2c9e4e915..a276a42c3 100644 --- a/scripts/e2e_session_continuity_ws.py +++ b/scripts/e2e_session_continuity_ws.py @@ -79,13 +79,13 @@ def launch(self, binary: str, args: list[str], env: dict) -> subprocess.Popen: return subprocess.Popen([str(self.bin_dir / binary), *args], env=env, stdin=subprocess.DEVNULL, stdout=log, stderr=log) - def post(self, path: str, body: dict, token: str) -> dict: + def post(self, path: str, body: dict, token: str, *, timeout: int = 20) -> dict: request = Request(self.url + path, json.dumps(body).encode(), method="POST", headers={"Authorization": "Bearer " + token, "Content-Type": "application/json", "Accept": "application/json, text/event-stream"}) try: - with self.opener.open(request, timeout=20) as response: + with self.opener.open(request, timeout=timeout) as response: raw = response.read(2 * 1024 * 1024) except HTTPError as error: raw = error.read(2 * 1024 * 1024) diff --git a/scripts/e2e_windows_wsl_idle.py b/scripts/e2e_windows_wsl_idle.py new file mode 100644 index 000000000..62b589a11 --- /dev/null +++ b/scripts/e2e_windows_wsl_idle.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +"""Windows + WSL2 regression for #1448. Supply a stopped, disposable distribution. + +python scripts/e2e_windows_wsl_idle.py --distro MyTestDistro [--bin-dir target/dogfood] +The test starts and terminates only the named distribution. It uses /tmp as an +existing project directory, a temporary native Server/Runner, and a loopback WebSocket. +""" +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import time + +from e2e_session_continuity_ws import ROOT, Smoke, check + + +def wsl(*args): + return subprocess.run(["wsl.exe", *args], stdin=subprocess.DEVNULL, capture_output=True, + timeout=30, check=True).stdout + + +def names(*args): + raw = wsl("--list", "--quiet", *args) + encoding = "utf-16-le" if b"\x00" in raw else "utf-8-sig" + return {line.strip().casefold() for line in raw.decode(encoding).lstrip("\ufeff").splitlines()} + + +def stop_distribution(distro): + wsl("--terminate", distro) + deadline = time.monotonic() + 15 + while distro.casefold() in names("--running"): + check(time.monotonic() < deadline, "distribution did not reach the stopped state") + time.sleep(0.2) + + +def run(smoke, distro, released): + candidate = smoke.bin_dir + if released: + smoke.bin_dir = released + name = distro.casefold() + remote = rf"\\wsl.localhost\{distro}\tmp" + local = smoke.root / "local" + registry = smoke.root / "registry" + local.mkdir() + registry.mkdir() + # Keep both WebCodex processes' per-user state inside the temporary fixture. + for key in ["APPDATA", "LOCALAPPDATA", "USERPROFILE"]: + path = smoke.root / key + path.mkdir() + smoke.env[key] = str(path) + smoke.start_server() + client = "wsl-smoke" + check(smoke.post("/api/users/create", {"username": "owner"}, smoke.bootstrap)["success"], + "test owner creation failed") + owner = smoke.pat("owner", ["runtime:read", "runner:manage", "project:read", "project:write", "job:run", "session:collaborate"]) + agent = smoke.post("/api/agent-tokens/create", {"client_id": client, "username": "owner", + "name": "wsl-smoke"}, smoke.bootstrap) + config = smoke.root / "runner.toml" + + def configure(roots): + config.write_text("\n".join([f'server_url = "{smoke.url}"', f'token = {json.dumps(agent["token"])}', + f'client_id = "{client}"', 'owner = "owner"', 'transport = "websocket"', + f'project_registry_dir = {json.dumps(str(registry))}', '[policy]', 'allow_raw_shell = true', + 'allow_cwd_anywhere = false', f'allowed_roots = {json.dumps(roots)}']), encoding="utf-8") + + def call(tool, **params): + response = smoke.post("/api/tools/call", {"tool": tool, "params": params}, owner, timeout=90) + output = response.get("output", {}) + check(response.get("success") is True, f"{tool} failed: {response.get('error')} " + f"({output.get('error_kind') or output.get('error_code')})") + return response["output"] + + def stopped(): + check(name not in names("--running"), "WSL was started by an unrelated operation") + check(smoke.runner.poll() is None and smoke.server.poll() is None, "fixture exited") + + configure([remote, str(local)]) + (registry / "local.toml").write_text(f'id = "local"\npath = {json.dumps(str(local))}\n', encoding="utf-8") + smoke.runner = smoke.launch("webcodex-runner", ["--config", str(config)], smoke.env) + local_id, remote_id = [f"agent:{client}:{p}" for p in ("local", "wsl")] + smoke.wait_ready(local_id, owner) + stopped() + if released: + # Set up the released baseline on an already reachable share. + wsl("--distribution", distro, "--exec", "/bin/true") + call("register_project", client_id=client, id="wsl", name="WSL", path=remote) + check(name in names("--running"), "explicit WSL registration did not start the test distribution") + + def project_ref(): + rows = call("list_projects", project=remote_id, limit=1)["projects"] + return rows[0]["project_ref"] + + call("start_session", project=remote_id) + original, = call("list_sessions", project=remote_id)["sessions"] + session_id, session_ref = original["session_id"], original["session_ref"] + ref = project_ref() + + def resume(selector): + result = call("work_on_project", project=ref, session_id=selector, + instruction="Resume the exact WSL task") + check(result["session_id"] == session_id, "existing selector resolved to a different Session") + + def restart_runner(restart_server=False): + previous = call("list_runners", client_id=client, summary_only=False)["runners"][0]["runner_instance_id"] + smoke.runner.terminate() + smoke.runner.wait(timeout=20) + smoke.runner = None + smoke.bin_dir = candidate + if restart_server: + smoke.server.terminate() + smoke.server.wait(timeout=20) + smoke.start_server() + smoke.runner = smoke.launch("webcodex-runner", ["--config", str(config)], smoke.env) + deadline = time.monotonic() + 45 + while True: + rows = call("list_runners", client_id=client, summary_only=False, include_projects=True)["runners"] + if any(row["connected"] and row["runner_instance_id"] != previous + and row["project_inventory"]["sync_state"] == "complete" + and any(p["id"] == "wsl" for p in row["projects"]) for row in rows): + return + check(time.monotonic() < deadline, "fresh Runner inventory did not arrive") + time.sleep(0.2) + + if released: + stop_distribution(distro) + restart_runner() + resume(session_id) + resume(session_ref) + print("PASS: released Server resumed original Project and Session refs with the new Runner", flush=True) + + # Clear the Server's in-memory observation. Only durable refs and Session + # bindings survive, and the new catalog must leave the distribution asleep. + stop_distribution(distro) + restart_runner(restart_server=True) + sessions = call("list_sessions", project=ref)["sessions"] + check(any(s["session_id"] == session_id and s["session_ref"] == session_ref for s in sessions), + "original Project Ref lost authorized history after restart") + stopped() + + def task(project, directory): + program = ("from pathlib import Path\nimport sys\n" + "if Path.cwd().name != sys.argv[1]: sys.exit(1)\n" + "print('verified-cwd=' + sys.argv[1])") + result = call("run_process", project=project, executable=sys.executable, + args=["-c", program, directory], timeout_secs=20, sync_wait_secs=20) + # Successful compact results carry stdout and omit the zero exit code. + check(result.get("exit_code", 0) == 0 and f"verified-cwd={directory}" in result.get("stdout_tail", ""), + f"Task did not confirm its working directory: {directory}") + + def local_task(): + task(local_id, "local") + stopped() + + def idle_window(): + for _ in range(12): + time.sleep(5) + stopped() + + idle_window() + local_task() + shell = call("run_shell", project=local_id, command="echo verified-shell", timeout_secs=10, sync_wait_secs=10) + check("verified-shell" in shell.get("stdout_tail", ""), "Windows shell did not execute") + stopped() + print("PASS: cold Project Ref history, idle inventory and native Windows task", flush=True) + task(remote_id, "tmp") + check(name in names("--running"), "explicit WSL task did not start its distribution") + resume(session_ref) + resume(session_id) + stop_distribution(distro) + call("read_session_handoff", project=ref, session_id=session_ref) + stopped() + print("PASS: default handoff left the previously accessed WSL distribution stopped", flush=True) + listed = call("list_projects", project=remote_id, limit=1, summary_only=False) + removed = call("unregister_project", project=remote_id, expected_revision=listed["projects"][0]["revision"]) + check(removed["outcome"] == "unregistered", "selected registration was not removed") + rows = call("list_runners", client_id=client, summary_only=False)["runners"] + check(remote in rows[0]["policy"]["allowed_roots"], "unregister unexpectedly revoked a grant") + idle_window() + local_task() + configure([str(local)]) + generation = call("check_runner_config", client_id=client)["current_generation"] + call("reload_runner_config", client_id=client, expected_generation=generation) + deadline = time.monotonic() + 15 + while True: + rows = call("list_runners", client_id=client, summary_only=False)["runners"] + if rows and rows[0]["policy"]["allowed_roots"] == [str(local)]: + break + check(time.monotonic() < deadline, "Server still reports the revoked file access") + time.sleep(0.2) + local_task() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--distro", required=True) + parser.add_argument("--released-bin-dir", type=Path, help="Exercise an in-place upgrade from a released Server and Runner") + parser.add_argument("--bin-dir", type=Path, default=ROOT / "target/dogfood") + args = parser.parse_args() + check(os.name == "nt", "This smoke requires a native Windows host with WSL2") + check(args.distro and not any(c in args.distro for c in "/\\\r\n") and not args.distro.startswith("-"), + "Supply a distribution name") + name = args.distro.casefold() + check(name in names() and name not in names("--running"), "Supply a stopped test distribution") + with tempfile.TemporaryDirectory(prefix="webcodex-wsl-smoke-") as root: + smoke = Smoke(args.bin_dir.resolve(), Path(root)) + try: + run(smoke, args.distro, args.released_bin_dir.resolve() if args.released_bin_dir else None) + finally: + for process in [smoke.runner, smoke.server]: + if process and process.poll() is None: + process.terminate() + process.wait(timeout=20) + for log in smoke.logs: + log.close() + if name in names("--running"): + stop_distribution(args.distro) + print("PASS: WSL stayed stopped during idle inventory, Windows tasks and revocation") + + +if __name__ == "__main__": + main() diff --git a/src/admin_project_lifecycle.rs b/src/admin_project_lifecycle.rs index a71731ee4..deb42d3e0 100644 --- a/src/admin_project_lifecycle.rs +++ b/src/admin_project_lifecycle.rs @@ -308,7 +308,7 @@ impl AdminProjectLifecycleService { .await .map_err(|_| api_error(503, "agent_unavailable"))?; } - let client = runtime + let mut client = runtime .runner_registry .get_runner_semantic_view_for_auth(&client_id, access.as_ref()) .await @@ -323,6 +323,26 @@ impl AdminProjectLifecycleService { { return Err(api_error(409, "unsupported_runner_version")); } + if action == "update_allow_patch" { + if let Some(project) = client.view.projects.iter().find(|p| { + p.id == project_id && p.deferred_root_path.is_some() && p.root_fingerprint.is_none() + }) { + if project.revision.as_deref() != Some(expected_revision) { + return Err(api_error(409, "revision_conflict")); + } + let instance = client.view.runner_instance_id.clone(); + runtime + .observe_deferred_project_root(&client_id, &instance, project, auth) + .await + .map_err(|_| api_error(409, "project_root_unverified"))?; + client = runtime + .runner_registry + .get_runner_semantic_view_for_auth(&client_id, access.as_ref()) + .await + .filter(|v| v.view.runner_instance_id == instance && v.view.connected) + .ok_or_else(|| api_error(503, "agent_unavailable"))?; + } + } let project = client.view.projects.iter().find(|p| p.id == project_id); if action != "unregister" && project.is_none() { return Err(api_error(404, "project_not_found")); @@ -831,6 +851,7 @@ fn lifecycle_summary(output: &Value, id: &str) -> Option { let incarnation = output.get("registration_incarnation")?.as_str()?; uuid::Uuid::parse_str(incarnation).ok()?; Some(RunnerProjectSummary { + deferred_root_path: None, registration_incarnation: Some(incarnation.to_string()), id: id.to_string(), name: output diff --git a/src/mcp_tests/artifact_export.rs b/src/mcp_tests/artifact_export.rs index f83f628da..caec5a0d7 100644 --- a/src/mcp_tests/artifact_export.rs +++ b/src/mcp_tests/artifact_export.rs @@ -42,6 +42,7 @@ async fn mcp_export_runtime_inner( "exporter", "inst-export", vec![RunnerProjectSummary { + deferred_root_path: None, registration_incarnation: None, id: "demo".to_string(), name: Some("demo".to_string()), diff --git a/src/mcp_tests/cli/peer_clients.rs b/src/mcp_tests/cli/peer_clients.rs index 68119c972..272adc9f8 100644 --- a/src/mcp_tests/cli/peer_clients.rs +++ b/src/mcp_tests/cli/peer_clients.rs @@ -151,6 +151,7 @@ fn cli_preserves_peer_audit_identity_without_consuming_or_acknowledging_delivery }).await.unwrap(); crate::test_support::apply_project_inventory_snapshot(&runtime.runner_registry, "peer-client-runner", "instance", vec![RunnerProjectSummary { + deferred_root_path: None, registration_incarnation: None, id: "repo".into(), name: Some("Peer fixture".into()), path: temp.path().to_string_lossy().to_string(), allow_patch: true, kind: Some("repo".into()), registration_source: None, description: None, diff --git a/src/mcp_tests/file_import.rs b/src/mcp_tests/file_import.rs index 3abd5d140..38e35386e 100644 --- a/src/mcp_tests/file_import.rs +++ b/src/mcp_tests/file_import.rs @@ -333,6 +333,7 @@ async fn mcp_import_runtime_inner( "importer", "inst-import", vec![RunnerProjectSummary { + deferred_root_path: None, registration_incarnation: None, id: "demo".to_string(), name: Some("demo".to_string()), diff --git a/src/mcp_tests/fixed_scope.rs b/src/mcp_tests/fixed_scope.rs index 38af13138..d51e34247 100644 --- a/src/mcp_tests/fixed_scope.rs +++ b/src/mcp_tests/fixed_scope.rs @@ -70,6 +70,7 @@ async fn scope_fixture_runner( client_id, &format!("inst-{client_id}"), vec![RunnerProjectSummary { + deferred_root_path: None, registration_incarnation: None, id: "repo".to_string(), name: None, diff --git a/src/mcp_tests/http_transport.rs b/src/mcp_tests/http_transport.rs index 6a7b65c50..73267c0a9 100644 --- a/src/mcp_tests/http_transport.rs +++ b/src/mcp_tests/http_transport.rs @@ -138,6 +138,7 @@ async fn stateless_observation_runner_registry() -> Arc Arc) -> crate::auth::Auth fn project_summary(id: &str, path: &str) -> RunnerProjectSummary { RunnerProjectSummary { + deferred_root_path: None, registration_incarnation: None, id: id.to_string(), name: Some(id.to_string()), diff --git a/src/runner_quic.rs b/src/runner_quic.rs index dcfde0c64..9a8d5864a 100644 --- a/src/runner_quic.rs +++ b/src/runner_quic.rs @@ -958,6 +958,7 @@ mod tests { write_quic_frame( &mut send, &RunnerEnvelope::RuntimeMetadata { + file_access: None, job_capacity: Some(RunnerJobCapacity { generation: update_generation, limit: update_limit, diff --git a/src/runner_session.rs b/src/runner_session.rs index b8db3ec7b..29fb22fe6 100644 --- a/src/runner_session.rs +++ b/src/runner_session.rs @@ -602,6 +602,7 @@ async fn dispatch_inbound( } } RunnerEnvelope::RuntimeMetadata { + file_access, job_capacity, tool_providers, mcp_gateway_providers, @@ -624,15 +625,19 @@ async fn dispatch_inbound( job_capacity, ) .await; - let _ = registry - .update_runtime_metadata_for_connection( + if let Err(error) = registry + .update_runtime_metadata( client_id, runner_instance_id, - connection_id, + Some(connection_id), + file_access, Some(tool_providers), mcp_gateway_providers, ) - .await; + .await + { + tracing::warn!(%client_id, %error, "Runner runtime metadata update rejected"); + } let _ = registry .update_computer_session_availability( client_id, diff --git a/src/runner_ws.rs b/src/runner_ws.rs index 028e57c89..ad3a6b623 100644 --- a/src/runner_ws.rs +++ b/src/runner_ws.rs @@ -813,6 +813,10 @@ mod tests { ws.send(TungsteniteMessage::Text( RunnerEnvelope::RuntimeMetadata { + file_access: Some(crate::runner_protocol::RunnerFileAccessPolicy { + allowed_roots: vec!["/new".into()], + allow_cwd_anywhere: false, + }), job_capacity: Some(crate::runner_protocol::RunnerJobCapacity { generation: 2, limit: 6, @@ -852,6 +856,10 @@ mod tests { } let view = registry.get_runner_view("ws-roundtrip").await.unwrap(); assert_eq!(view.job_concurrency_limit, Some(6)); + assert_eq!( + view.policy.as_ref().unwrap().file_access.allowed_roots, + vec![std::path::PathBuf::from("/new")] + ); let call = view .policy .unwrap() diff --git a/src/runtime_console_http/tests/mod.rs b/src/runtime_console_http/tests/mod.rs index 3e4ab6484..2d2d76575 100644 --- a/src/runtime_console_http/tests/mod.rs +++ b/src/runtime_console_http/tests/mod.rs @@ -34,6 +34,7 @@ mod window_visibility; fn project(id: &str, private_path: &str) -> RunnerProjectSummary { RunnerProjectSummary { + deferred_root_path: None, registration_incarnation: Some(uuid::Uuid::new_v4().to_string()), id: id.to_string(), name: Some(format!("Project {id}")), diff --git a/src/runtime_http_tests.rs b/src/runtime_http_tests.rs index 6eaef6639..c26a9314b 100644 --- a/src/runtime_http_tests.rs +++ b/src/runtime_http_tests.rs @@ -282,6 +282,7 @@ async fn register_import_agent_with_capabilities( "importer", "inst-import", vec![RunnerProjectSummary { + deferred_root_path: None, registration_incarnation: Some(uuid::Uuid::new_v4().to_string()), id: "demo".to_string(), name: Some("demo".to_string()), @@ -633,6 +634,7 @@ fn http_runtime_status_after_runner_registration_fits_default_worker_stack() { "status-stack-runner", "status-stack-instance", vec![RunnerProjectSummary { + deferred_root_path: None, registration_incarnation: Some(uuid::Uuid::new_v4().to_string()), id: "smoke-proj".to_string(), name: Some("Smoke Project".to_string()), diff --git a/src/tool_runtime/admin_dashboard.rs b/src/tool_runtime/admin_dashboard.rs index 6de4bd122..834b34cf8 100644 --- a/src/tool_runtime/admin_dashboard.rs +++ b/src/tool_runtime/admin_dashboard.rs @@ -273,6 +273,7 @@ mod tests { fn project(id: &str, disabled: bool) -> RunnerProjectSummary { RunnerProjectSummary { + deferred_root_path: None, registration_incarnation: None, id: id.to_string(), name: Some(id.to_string()), diff --git a/src/tool_runtime/checkpoint.rs b/src/tool_runtime/checkpoint.rs index b0b181c43..e5741fb93 100644 --- a/src/tool_runtime/checkpoint.rs +++ b/src/tool_runtime/checkpoint.rs @@ -313,8 +313,17 @@ impl ToolRuntime { Ok(resolved) => resolved, Err(err) => return err.into_tool_result(), }; + self.list_resolved_checkpoints(&project, &resolved.resolved_id, limit) + } + + pub(super) fn list_resolved_checkpoints( + &self, + project: &str, + resolved_id: &str, + limit: Option, + ) -> ToolResult { let limit = limit.unwrap_or(DEFAULT_LIST_LIMIT).clamp(1, MAX_LIST_LIMIT); - let checkpoints = match self.checkpoint_store.list(&resolved.resolved_id, limit) { + let checkpoints = match self.checkpoint_store.list(resolved_id, limit) { Ok(values) => values, Err(err) => return ToolResult::err(err), }; @@ -324,7 +333,7 @@ impl ToolRuntime { .collect(); ToolResult::ok(json!({ "project": project, - "resolved_project": resolved.resolved_id, + "resolved_project": resolved_id, "limit": limit, "checkpoints": items, })) diff --git a/src/tool_runtime/coding_task/startup.rs b/src/tool_runtime/coding_task/startup.rs index bcfac12b7..fe2441e03 100644 --- a/src/tool_runtime/coding_task/startup.rs +++ b/src/tool_runtime/coding_task/startup.rs @@ -3,7 +3,7 @@ use super::observations::repository_overview_not_requested; use super::project::{ attach_permission, attach_project_resolution, invalid_project_source, resolve_project_source, - ManagedWorktreeRequest, + CodingProjectSource, ManagedWorktreeRequest, }; use super::projection::{ owning_runner_available, project_coding_agent_providers, project_work_on_project_output_inner, @@ -141,6 +141,9 @@ impl ToolRuntime { trusted_recording_session_id, trusted_recording_session_project, ) { + (Some(id), Some(_)) if Some(id) == resume_session_id.as_deref() => { + resume_session_project.clone() + } (Some(id), Some(_)) => match self .explicit_coding_session_project(id, Some(&project), startup.tool_name, auth) .await @@ -195,6 +198,8 @@ impl ToolRuntime { } None => None, }; + let existing_checkout = matches!(project_source, CodingProjectSource::Existing { .. }) + && managed_worktree.is_none(); let (project, mut project_resolution) = match self .resolve_coding_startup_project( project_source, @@ -211,11 +216,18 @@ impl ToolRuntime { Ok(resolved) => resolved, Err(result) => return result, }; - let resolved = match self.resolve_project_input_for_auth(&project, auth).await { - Ok(resolved) => resolved, - Err(err) => { - return attach_project_resolution(err.into_tool_result(), &project_resolution) - } + let resolved = match resume_session_project + .as_ref() + .or(trusted_recording_session_resolved_project.as_ref()) + .filter(|p| existing_checkout && (p.resolved_id == project || p.input == project)) + { + Some(verified) => verified.clone(), + None => match self.resolve_project_input_for_auth(&project, auth).await { + Ok(resolved) => resolved, + Err(err) => { + return attach_project_resolution(err.into_tool_result(), &project_resolution) + } + }, }; project_resolution.resolved_project = resolved.resolved_id.clone(); // Reject already-closed exact resumes before startup observations. The diff --git a/src/tool_runtime/coding_task/tests.rs b/src/tool_runtime/coding_task/tests.rs index a72db8d30..7aaf7ef61 100644 --- a/src/tool_runtime/coding_task/tests.rs +++ b/src/tool_runtime/coding_task/tests.rs @@ -202,6 +202,7 @@ fn output_guidance_preserves_unproven_validation_and_rejects_invalid_receipts() fn resolved_agent(client_id: &str) -> ResolvedProject { ResolvedProject { + root_probe_deferred: false, input: "demo".to_string(), resolved_id: format!("agent:{client_id}:demo"), config: ProjectConfig { diff --git a/src/tool_runtime/context_projection.rs b/src/tool_runtime/context_projection.rs index c9f6c3a10..9249c5fe4 100644 --- a/src/tool_runtime/context_projection.rs +++ b/src/tool_runtime/context_projection.rs @@ -245,7 +245,7 @@ impl ToolRuntime { if link.project.as_deref() != Some(project.as_str()) { continue; } - let Ok(resolved) = self.resolve_project_input_for_auth(&project, auth).await else { + let Ok(resolved) = self.resolve_project_metadata_for_auth(&project, auth).await else { continue; }; if resolved.resolved_id != project diff --git a/src/tool_runtime/dispatch.rs b/src/tool_runtime/dispatch.rs index c1b8fb996..91ec51d88 100644 --- a/src/tool_runtime/dispatch.rs +++ b/src/tool_runtime/dispatch.rs @@ -224,11 +224,9 @@ mod tests { purpose: None, shell: None, }; - let (shell_project, shell_output) = canonical_execution_project_binding(&mut shell) - .expect("legacy shell execution needs canonical binding"); - assert_eq!(shell_output, CanonicalProjectOutput::Canonical); - shell_project.clone_from(&"agent:special:webcodex".to_string()); - assert_eq!(shell.project(), Some("agent:special:webcodex")); + // Shell execution receives the authorized ResolvedProject directly. + assert!(canonical_execution_project_binding(&mut shell).is_none()); + assert_eq!(shell.project(), Some("~p7")); let mut hygiene = ToolCall::WorkspaceHygieneCheck { project: "~p7".to_string(), diff --git a/src/tool_runtime/dispatch/execution.rs b/src/tool_runtime/dispatch/execution.rs index 8b14cf302..6d315270a 100644 --- a/src/tool_runtime/dispatch/execution.rs +++ b/src/tool_runtime/dispatch/execution.rs @@ -68,8 +68,19 @@ impl ToolRuntime { | ToolCall::RunDetachedProcess { .. } | ToolCall::RunScript { .. } | ToolCall::RunShell { .. }) => { - self.dispatch_shell_tool(call, ssh_resource, validation_assertion_name, auth) - .await + let target = match project_resolution { + Some(Ok(target)) => target, + Some(Err(error)) => return error.into_tool_result(), + None => return ToolResult::err("execution requires a resolved Project"), + }; + self.dispatch_shell_tool( + call, + target, + ssh_resource, + validation_assertion_name, + auth, + ) + .await } ToolCall::ProjectFormat { diff --git a/src/tool_runtime/dispatch/governance.rs b/src/tool_runtime/dispatch/governance.rs index bf4a17357..1f4b87bb9 100644 --- a/src/tool_runtime/dispatch/governance.rs +++ b/src/tool_runtime/dispatch/governance.rs @@ -75,6 +75,11 @@ impl ToolRuntime { recorder_metadata.mark_business_execution(); let recorder_metadata = &context.recorder; let project_resolution = match call.project() { + Some(project) + if super::super::session_tools::passive_project_read(call.tool_name()) => + { + Some(self.resolve_project_metadata_for_auth(project, auth).await) + } Some(project) => Some(self.resolve_project_input_for_auth(project, auth).await), None => None, }; @@ -123,7 +128,16 @@ impl ToolRuntime { // Fence that exact Session before lifecycle/guard inheritance, // project mismatch logic, or any ledger mutation. if let Err(mut result) = self - .authorize_session_target(session_id, call.tool_name(), call.project(), auth) + .authorize_session_access( + session_id, + call.tool_name(), + auth, + super::super::session_tools::SessionAccess::for_business( + call.tool_name(), + call.project(), + resolved_project, + ), + ) .await { decorate_structured_execution_prestart_denial( diff --git a/src/tool_runtime/dispatch/preflight.rs b/src/tool_runtime/dispatch/preflight.rs index 1bc8dc256..ba0a6d716 100644 --- a/src/tool_runtime/dispatch/preflight.rs +++ b/src/tool_runtime/dispatch/preflight.rs @@ -33,11 +33,7 @@ pub(super) fn canonical_execution_project_binding( | ToolCall::WorkspaceCheckpointDelete { project, .. } => { Some((project, CanonicalProjectOutput::Requested)) } - ToolCall::RunProcess { project, .. } - | ToolCall::RunDetachedProcess { project, .. } - | ToolCall::StartAgentTaskCodingRun { project, .. } - | ToolCall::RunScript { project, .. } - | ToolCall::RunShell { project, .. } + ToolCall::StartAgentTaskCodingRun { project, .. } | ToolCall::OpenSessionShell { project, .. } | ToolCall::SessionShellExec { project, .. } | ToolCall::SessionShellStatus { project, .. } diff --git a/src/tool_runtime/git/show_changes.rs b/src/tool_runtime/git/show_changes.rs index 88d6fe3f7..72fcebd5d 100644 --- a/src/tool_runtime/git/show_changes.rs +++ b/src/tool_runtime/git/show_changes.rs @@ -2650,6 +2650,7 @@ impl ToolRuntime { max_hunk_lines, session_event_limit, false, + None, ) .await } @@ -2660,11 +2661,11 @@ impl ToolRuntime { &self, project: String, ) -> ToolResult { - self.show_changes_observation(project, None, Some(false), None, None, None, true) + self.show_changes_observation(project, None, Some(false), None, None, None, true, None) .await } - async fn show_changes_observation( + pub(in crate::tool_runtime) async fn show_changes_observation( &self, project: String, session_id: Option, @@ -2673,6 +2674,7 @@ impl ToolRuntime { max_hunk_lines: Option, session_event_limit: Option, read_only_presentation: bool, + observed: Option<&crate::tool_runtime::ResolvedProject>, ) -> ToolResult { let include_diff = include_diff.unwrap_or(false); let max_hunks = max_hunks @@ -2713,10 +2715,17 @@ set +e safe_config = super::super::changes::CHANGES_GIT_SAFE_CONFIG_SETUP, ); } - let output = match self - .run_project_internal_posix_script_capture(&project, command, 30, None) - .await - { + let capture = match observed { + Some(target) => { + self.run_resolved_project_command_capture(&target.config, command, 30, None, true) + .await + } + None => { + self.run_project_internal_posix_script_capture(&project, command, 30, None) + .await + } + }; + let output = match capture { Ok(output) => output, Err(e) => return ToolResult::err(e), }; diff --git a/src/tool_runtime/handoff.rs b/src/tool_runtime/handoff.rs index 2bc76a623..9f8899bfd 100644 --- a/src/tool_runtime/handoff.rs +++ b/src/tool_runtime/handoff.rs @@ -179,35 +179,54 @@ impl ToolRuntime { .filter(|n| *n > 0) .unwrap_or(DEFAULT_HANDOFF_LIMIT) .min(MAX_HANDOFF_LIMIT); - let include_workspace = include_workspace.unwrap_or(true); - let include_checkpoints = include_checkpoints.unwrap_or(true); - #[cfg(not(feature = "workspace-checkpoints"))] - let _ = include_checkpoints; - let include_validation = include_validation.unwrap_or(true); - - let authorized_target = match self + let authorized_target = self .authorize_session_target( &session_id, "read_session_handoff", project.as_deref(), auth, ) - .await - { - Ok(resolved) => resolved, - Err(result) => return Err(result), + .await?; + // The ledger remains readable with a cold Project Ref. Only an explicit + // workspace/checkpoint request may open that root for live evidence. + let deferred_target = authorized_target.as_ref().filter(|p| p.root_probe_deferred); + let include_workspace = include_workspace.unwrap_or(deferred_target.is_none()); + let include_checkpoints = include_checkpoints.unwrap_or(deferred_target.is_none()); + let include_validation = include_validation.unwrap_or(true); + let observed = if let Some(target) = deferred_target.filter(|_| { + include_workspace || (cfg!(feature = "workspace-checkpoints") && include_checkpoints) + }) { + let observed = self + .resolve_project_input_for_auth(&target.input, auth) + .await + .map_err(super::ProjectResolverError::into_tool_result)?; + self.authorize_session_access( + &session_id, + "read_session_handoff", + auth, + super::session_tools::SessionAccess::Live { + requested_project: project.as_deref(), + resolved: Some(&observed), + }, + ) + .await?; + Some(observed) + } else { + None }; let session_project = self .sessions .session_project(&session_id) .expect("authorized Workflow Session must still exist"); - let requested_project = if let Some(request_project) = project + let requested_project = if authorized_target.is_some() { + authorized_target + } else if let Some(request_project) = project .as_deref() .map(str::trim) .filter(|project| !project.is_empty()) { let requested = match self - .resolve_project_input_for_auth(request_project, auth) + .resolve_project_metadata_for_auth(request_project, auth) .await { Ok(resolved) => resolved, @@ -236,8 +255,6 @@ impl ToolRuntime { // already-authorized stored Project instead of treating it as unscoped. let project = if let Some(requested) = requested_project { Some(requested.resolved_id) - } else if let Some(target) = authorized_target { - Some(target.resolved_id) } else { // The Session project was canonicalized and authority-fenced when the // Session was created. Concrete workspace/Job reads keep their own @@ -360,21 +377,12 @@ impl ToolRuntime { }); let mut warnings = Vec::new(); - let jobs_project = match project + let jobs_project = project .as_deref() - .map(str::trim) - .filter(|project| !project.is_empty()) - { - Some(project) => self - .resolve_project_input_for_auth(project, auth) - .await - .map(|resolved| resolved.resolved_id) - .unwrap_or_else(|_| project.to_string()), - None => summary.project.clone().unwrap_or_default(), - }; - let jobs_project = (!jobs_project.is_empty()).then_some(jobs_project); + .or(summary.project.as_deref()) + .filter(|p| !p.is_empty()); let job_snapshot = self - .active_jobs_snapshot(jobs_project.as_deref(), Some(&summary.session_id), auth, 10) + .active_jobs_snapshot(jobs_project, Some(&summary.session_id), auth, 10) .await; let jobs = job_snapshot.to_value(); if let Some(job_warnings) = jobs.get("warnings").and_then(Value::as_array) { @@ -432,7 +440,12 @@ impl ToolRuntime { }) .unwrap_or_else(|| (Vec::new(), false)); let (workspace, continuity, observation) = self - .handoff_workspace_summary(&project, &continuity_changed_paths, history_complete) + .handoff_workspace_summary( + &project, + observed.as_ref(), + &continuity_changed_paths, + history_complete, + ) .await; closeout_workspace = observation; output["workspace"] = workspace; @@ -443,7 +456,9 @@ impl ToolRuntime { #[cfg(feature = "workspace-checkpoints")] if has_project && include_checkpoints { let project = project.clone().unwrap_or_default(); - let checkpoints = self.handoff_checkpoint_summary(&project, limit).await; + let checkpoints = self + .handoff_checkpoint_summary(&project, observed.as_ref(), limit) + .await; output["checkpoints"] = checkpoints; } @@ -633,11 +648,21 @@ impl ToolRuntime { async fn handoff_workspace_summary( &self, project: &str, + observed: Option<&super::ResolvedProject>, session_changed_paths: &[Value], history_complete: bool, ) -> (Value, Value, Observation) { let show_result = self - .show_changes(project.to_string(), None, Some(false), None, None, None) + .show_changes_observation( + project.to_string(), + None, + Some(false), + None, + None, + None, + false, + observed, + ) .await; if !show_result.success { // Non-git project or git failure: do not fail the whole handoff. @@ -737,10 +762,21 @@ impl ToolRuntime { /// `last_known_good` checkpoint (preferring `validation_status == passed`) /// and a bounded recent list. Never returns validation.commands or diffs. #[cfg(feature = "workspace-checkpoints")] - async fn handoff_checkpoint_summary(&self, project: &str, limit: usize) -> Value { - let list_result = self - .workspace_checkpoint_list(project.to_string(), Some(limit)) - .await; + async fn handoff_checkpoint_summary( + &self, + project: &str, + observed: Option<&super::ResolvedProject>, + limit: usize, + ) -> Value { + let list_result = match observed { + Some(target) => { + self.list_resolved_checkpoints(project, &target.resolved_id, Some(limit)) + } + None => { + self.workspace_checkpoint_list(project.to_string(), Some(limit)) + .await + } + }; if !list_result.success { return json!({ "latest_last_known_good": Value::Null, diff --git a/src/tool_runtime/job_input.rs b/src/tool_runtime/job_input.rs index e788722a9..d839dd30d 100644 --- a/src/tool_runtime/job_input.rs +++ b/src/tool_runtime/job_input.rs @@ -1,4 +1,5 @@ //! Explicit pipe interaction on the existing public Job and authorization path. +use super::project_resolution::ResolvedProject; use super::{ExecutionPurpose, ToolResult, ToolRuntime}; use crate::auth::AuthContext; use serde_json::json; @@ -38,7 +39,7 @@ impl ToolRuntime { #[allow(clippy::too_many_arguments)] pub(crate) async fn run_interactive_process( &self, - project: String, + target: ResolvedProject, executable: String, args: Vec, stdin: Option, @@ -59,14 +60,8 @@ impl ToolRuntime { if super::process::validate_process_input(&process, None, cwd.as_deref()).is_err() { return rejected("interactive_process_arguments_invalid"); } - let resolved = match self.resolve_project_input_for_auth(&project, auth).await { - Ok(v) => v, - Err(error) => return error.into_tool_result(), - }; - let target = match self.resolve_project(&resolved.resolved_id).await { - Ok(v) => v, - Err(_) => return rejected("interactive_process_project_unavailable"), - }; + let project = target.resolved_id; + let target = target.config; let effective_cwd = match super::helpers::resolve_runner_cwd(&target, cwd.as_deref()) { Ok(v) => v, Err(_) => return rejected("interactive_process_cwd_invalid"), @@ -86,7 +81,7 @@ impl ToolRuntime { timeout_secs: budget.effective_timeout_secs, execution: JobStartExecution::InteractiveProcess(process), context: JobStartContext { - project_id: Some(resolved.resolved_id), + project_id: Some(project), session_id: session_id, project_cwd: cwd, purpose: purpose.map(|p| p.as_str().into()), diff --git a/src/tool_runtime/kernel/recording.rs b/src/tool_runtime/kernel/recording.rs index c1155a35c..cdc0b22d7 100644 --- a/src/tool_runtime/kernel/recording.rs +++ b/src/tool_runtime/kernel/recording.rs @@ -54,9 +54,11 @@ impl PreparedInvocation { let scopes_allow_binding = tool_scope.is_ok() && resolution_scope.is_ok(); let recorder_access = |requested_project| { if scopes_allow_binding { - SessionAccess::Live { requested_project } + SessionAccess::for_business(&request.tool_name, requested_project, None) } else { - SessionAccess::BoundTarget + SessionAccess::BoundTarget { + requested_project: None, + } } }; // A wrapper recording_session_id is authority-bearing internal context, @@ -123,19 +125,16 @@ impl PreparedInvocation { .unwrap_or(&recorder_metadata.ack_session_message_ids), ) }); - if collaboration_session_tool(&request.tool_name) { - if let (Some(recorder_session_id), Some(target_session_id)) = ( - context.session_id, - collaboration_target_session_id(&request.tool_name, &concrete_arguments), - ) { + if collaboration_session_tool(&request.tool_name) && context.session_id.is_some() { + if let Some(target_session_id) = + collaboration_target_session_id(&request.tool_name, &concrete_arguments) + .filter(|target| Some(*target) != context.session_id) + { // Both ends of a cross-Session collaboration relationship must // be independently authorized before comparing scope. This makes // None/None safe while rejecting either mixed scoped/unscoped // direction without any cross-project escape. - let recorder_project = runtime - .sessions - .session_project(recorder_session_id) - .expect("authorized recording Session must exist"); + let recorder_project = recorder_metadata.recording_session_project.clone(); if let Err(result) = runtime .authorize_session_access( target_session_id, @@ -167,19 +166,19 @@ impl PreparedInvocation { } } let session_contract = sessions::session_tool_contract(&request.tool_name); - let recording_session_project_mismatch = match context.session_id { - Some(session_id) => { - runtime - .recording_session_project_mismatch( - session_id, - &request.tool_name, - &concrete_arguments, - context.auth, - ) - .await - } - None => None, - }; + let recording_session_project_mismatch = + match recorder_metadata.recording_session_project.as_deref() { + Some(session_project) => { + runtime + .recording_session_project_mismatch( + session_project, + &concrete_arguments, + context.auth, + ) + .await + } + None => None, + }; if let (Some(session_id), Some(mismatch)) = ( context.session_id, recording_session_project_mismatch.as_ref(), @@ -512,27 +511,28 @@ impl ToolRuntime { async fn recording_session_project_mismatch( &self, - session_id: &str, - _tool_name: &str, + session_project: &str, arguments: &Value, auth: Option<&AuthContext>, ) -> Option { - let session_project = self.sessions.session_project(session_id)??; let request_project = arguments .as_object() .and_then(|obj| obj.get("project")) .and_then(Value::as_str) .map(str::trim) .filter(|project| !project.is_empty())?; + if request_project == session_project { + return None; + } let resolved = self - .resolve_project_input_for_auth(request_project, auth) + .resolve_project_metadata_for_auth(request_project, auth) .await .ok()?; if session_project == resolved.resolved_id { return None; } Some(session_context::SessionProjectMismatch { - session_project, + session_project: session_project.to_owned(), request_project: resolved.resolved_id, }) } diff --git a/src/tool_runtime/memory.rs b/src/tool_runtime/memory.rs index 2997cf78b..c75715af6 100644 --- a/src/tool_runtime/memory.rs +++ b/src/tool_runtime/memory.rs @@ -763,6 +763,7 @@ mod tests { fn scope_identity_changes_with_runner_or_registered_root_without_exposure() { fn resolved(client: &str, path: &str) -> ResolvedProject { ResolvedProject { + root_probe_deferred: false, input: "demo".to_string(), resolved_id: format!("agent:{client}:demo"), config: crate::projects::ProjectConfig { diff --git a/src/tool_runtime/process.rs b/src/tool_runtime/process.rs index 640780cf7..7f072a88f 100644 --- a/src/tool_runtime/process.rs +++ b/src/tool_runtime/process.rs @@ -1,3 +1,4 @@ +use super::project_resolution::ResolvedProject; use serde_json::json; use super::helpers::{ @@ -141,6 +142,17 @@ pub(crate) fn process_tool_failure_result( ) } +pub(super) fn execution_project_rejected(error: super::ProjectResolverError) -> ToolResult { + process_tool_failure_result( + command_rejected_message( + error.to_message(), + "verify the project id with list_projects, then retry with a registered project.", + ), + "agent_offline", + ShellCommandExecutionState::NotStarted, + ) +} + /// Project the typed rejection for this admission attempt. Previously admitted /// Jobs retain their own lifecycle; callers handle detached recovery separately. pub(crate) fn execution_admission_failure_result( @@ -462,7 +474,7 @@ impl ToolRuntime { #[allow(clippy::too_many_arguments)] pub(crate) async fn run_process_with_contract_for_resource( &self, - project: String, + target: ResolvedProject, executable: String, args: Vec, stdin: Option, @@ -476,7 +488,7 @@ impl ToolRuntime { auth: Option<&AuthContext>, ) -> ToolResult { self.run_process_with_contract_mode( - project, + target, executable, args, stdin, @@ -497,7 +509,7 @@ impl ToolRuntime { #[allow(clippy::too_many_arguments)] pub(crate) async fn run_skill_resource_with_contract( &self, - project: String, + target: ResolvedProject, request: RunnerSkillExecutionRequest, timeout_secs: Option, sync_wait_secs: Option, @@ -507,7 +519,7 @@ impl ToolRuntime { auth: Option<&AuthContext>, ) -> ToolResult { self.run_process_with_contract_mode( - project, + target, String::new(), Vec::new(), None, @@ -531,7 +543,7 @@ impl ToolRuntime { #[allow(clippy::too_many_arguments)] pub(crate) async fn run_detached_process_with_contract( &self, - project: String, + target: ResolvedProject, idempotency_key: String, executable: String, args: Vec, @@ -543,6 +555,8 @@ impl ToolRuntime { session_id: Option, auth: Option<&AuthContext>, ) -> ToolResult { + let project = target.resolved_id; + let proj = target.config; let requested_timeout_secs = timeout_secs.unwrap_or(STRUCTURED_EXECUTION_TIMEOUT_DEFAULT_SECS); let budget = match StructuredExecutionBudget::resolve_process(timeout_secs) { @@ -582,19 +596,7 @@ impl ToolRuntime { } let summary = format!("detached process ({} args)", process.args.len()); let declared_purpose = purpose.unwrap_or_default(); - let proj = match self.resolve_project(&project).await { - Ok(project) => project, - Err(error) => { - return process_tool_failure_result( - command_rejected_message( - error.to_message(), - "verify the project id with list_projects, then retry with a registered Runner project.", - ), - "agent_offline", - ShellCommandExecutionState::NotStarted, - ) - } - }; + let client_id = proj.client_id.clone(); let effective_cwd = match resolve_runner_cwd(&proj, cwd.as_deref()) { Ok(cwd) => cwd, @@ -775,6 +777,10 @@ impl ToolRuntime { args: Vec, timeout_secs: u64, ) -> ToolResult { + let project = match self.resolve_project_input(&project).await { + Ok(project) => project, + Err(error) => return execution_project_rejected(error), + }; self.run_process_with_contract_mode( project, executable, @@ -797,7 +803,7 @@ impl ToolRuntime { #[allow(clippy::too_many_arguments)] async fn run_process_with_contract_mode( &self, - project: String, + target: ResolvedProject, executable: String, args: Vec, stdin: Option, @@ -812,6 +818,8 @@ impl ToolRuntime { allow_async_handoff: bool, skill_resource: Option, ) -> ToolResult { + let project = target.resolved_id; + let proj = target.config; let budget = match if skill_resource.is_some() { StructuredExecutionBudget::resolve_with_sync_wait(timeout_secs, sync_wait_secs) } else { @@ -911,19 +919,7 @@ impl ToolRuntime { } identity }); - let proj = match self.resolve_project(&project).await { - Ok(project) => project, - Err(error) => { - return process_tool_failure_result( - command_rejected_message( - error.to_message(), - "verify the project id with list_projects, then retry with a registered project.", - ), - "agent_offline", - ShellCommandExecutionState::NotStarted, - ) - } - }; + let client_id = proj.client_id.clone(); let (budget, timeout_notice) = apply_runner_timeout_cap( &self.runner_registry, diff --git a/src/tool_runtime/project_resolution.rs b/src/tool_runtime/project_resolution.rs index e6f3ed1f6..be7e958a1 100644 --- a/src/tool_runtime/project_resolution.rs +++ b/src/tool_runtime/project_resolution.rs @@ -14,6 +14,7 @@ pub(crate) struct ProjectResolverCandidate { pub(crate) name: Option, pub(crate) path: String, pub(crate) allow_patch: bool, + pub(crate) root_probe_deferred: bool, pub(crate) root_fingerprint: Option, pub(crate) registration_incarnation: Option, pub(crate) runner_instance_id: String, @@ -63,6 +64,8 @@ pub(crate) struct ResolvedProject { pub(crate) input: String, pub(crate) resolved_id: String, pub(crate) config: ProjectConfig, + /// Inventory defers this root, even after an earlier request observed it. + pub(crate) root_probe_deferred: bool, /// Root identity from the same Runner project-inventory snapshot that /// produced this resolution. It is descriptive only and never authorizes /// access by itself. @@ -76,7 +79,23 @@ pub(crate) struct ResolvedProject { } impl ResolvedProject { + // Only a stored Session binding may be compared with this historical pin. + // Execution and first binding require a fingerprint supplied by the Runner. + pub(super) fn deferred_history_identity(&self, pin: Option<&str>) -> Option { + if self.root_fingerprint.is_some() { + return None; + } + webcodex_core::runner_protocol::workflow_project_identity( + Some(pin?), + &self.config.path, + self.registration_incarnation.as_deref(), + ) + } + pub(crate) fn workflow_project_identity(&self) -> Option { + if self.root_probe_deferred && self.root_fingerprint.is_none() { + return None; + } webcodex_core::runner_protocol::workflow_project_identity( self.root_fingerprint.as_deref(), &self.config.path, @@ -111,6 +130,7 @@ impl ResolvedProject { pub(crate) enum ProjectResolverErrorKind { UnknownProject, AmbiguousProject, + IdentityUnavailable, } impl ProjectResolverErrorKind { @@ -118,6 +138,7 @@ impl ProjectResolverErrorKind { match self { Self::UnknownProject => "unknown_project", Self::AmbiguousProject => "ambiguous_project", + Self::IdentityUnavailable => "project_root_unverified", } } } @@ -486,6 +507,7 @@ impl ToolRuntime { name: project.name.clone(), path: project.path.clone(), allow_patch: project.allow_patch, + root_probe_deferred: project.deferred_root_path.is_some(), root_fingerprint: project.root_fingerprint.clone(), // Keep the registration identity from the last complete inventory // across a disconnect. An incomplete inventory proves no binding. @@ -519,6 +541,7 @@ impl ToolRuntime { input: input.to_string(), resolved_id: candidate.id.clone(), config: Self::project_config_from_candidate(candidate), + root_probe_deferred: candidate.root_probe_deferred, root_fingerprint: candidate.root_fingerprint.clone(), registration_incarnation: candidate.registration_incarnation.clone(), runner_instance_id: candidate.runner_instance_id.clone(), @@ -556,11 +579,157 @@ impl ToolRuntime { candidates } + /// Targeted identity observation. Passive inventory never calls this. + /// The Runner re-reads the exact registry revision before opening the share; + /// the Server does not synthesize a canonical fingerprint from its spelling. + pub(crate) async fn observe_deferred_project_root( + &self, + client_id: &str, + instance: &str, + project: &RunnerProjectSummary, + auth: Option<&AuthContext>, + ) -> Result<(String, String), String> { + let revision = project + .revision + .as_deref() + .ok_or("missing Project revision")?; + let incarnation = project + .registration_incarnation + .as_deref() + .ok_or("missing Project incarnation")?; + let access = crate::runner_http::runner_access_from_auth(auth); + if access.is_some() { + self.runner_registry + .assert_runner_access(access.as_ref(), client_id) + .await?; + } + let (request, response) = self + .runner_registry + .enqueue_project_identity_probe(client_id, instance, project, access.as_ref()) + .await?; + let result = match tokio::time::timeout(std::time::Duration::from_secs(32), response).await + { + Ok(Ok(result)) => result, + _ => { + self.runner_registry + .cancel_request_dispatch_state(&request) + .await; + return Err("Project root observation unavailable".into()); + } + }; + if result.exit_code != Some(0) || result.error.is_some() { + return Err("Project root observation rejected".into()); + } + let value: Value = + serde_json::from_str(result.stdout.as_deref().ok_or("missing observation")?) + .map_err(|_| "invalid Project root observation")?; + if value["agent_project_id"].as_str() != Some(&project.id) + || value["revision"].as_str() != Some(revision) + || value["registration_incarnation"].as_str() != Some(incarnation) + || value["outcome"].as_str() != Some("observed") + || value["changed"].as_bool() != Some(false) + { + return Err("Project root observation identity changed".into()); + } + let path = value["path"].as_str().ok_or("missing observed path")?; + let fingerprint = value["root_fingerprint"] + .as_str() + .ok_or("missing observed root")?; + self.runner_registry + .record_deferred_project_root( + access.as_ref(), + client_id, + instance, + &project.id, + project + .deferred_root_path + .as_deref() + .ok_or("missing deferred path")?, + revision, + incarnation, + fingerprint, + path, + ) + .await?; + Ok((path.to_owned(), fingerprint.to_owned())) + } + pub(crate) async fn resolve_project_input_for_auth( &self, project: &str, auth: Option<&AuthContext>, ) -> Result { + let (mut resolved, reference_root) = self.select_project_for_auth(project, auth).await?; + if !resolved.root_probe_deferred { + return Ok(resolved); + } + let unavailable = || ProjectResolverError { + kind: ProjectResolverErrorKind::IdentityUnavailable, + project: project.to_owned(), + candidates: Vec::new(), + }; + if !resolved.runner_connected { + return Err(unavailable()); + } + let access = crate::runner_http::runner_access_from_auth(auth); + let view = self + .runner_registry + .get_runner_view_for_auth(&resolved.config.client_id, access.as_ref()) + .await + .ok_or_else(unavailable)?; + if view.runner_instance_id != resolved.runner_instance_id { + return Err(unavailable()); + } + let id = resolved + .resolved_id + .strip_prefix(&format!("agent:{}:", view.client_id)) + .ok_or_else(unavailable)?; + let row = view + .projects + .iter() + .find(|row| { + row.id == id + && !row.disabled + && row.deferred_root_path.is_some() + && row.path == resolved.config.path + && row.registration_incarnation == resolved.registration_incarnation + }) + .ok_or_else(unavailable)?; + let (path, fingerprint) = self + .observe_deferred_project_root(&view.client_id, &view.runner_instance_id, row, auth) + .await + .map_err(|_| unavailable())?; + if reference_root.is_some_and(|root| root != fingerprint) { + return Err(unavailable()); + } + resolved.config.path = path; + resolved.root_fingerprint = Some(fingerprint); + Ok(resolved) + } + + pub(crate) async fn resolve_project_metadata_for_auth( + &self, + project: &str, + auth: Option<&AuthContext>, + ) -> Result { + let (resolved, reference_root) = self.select_project_for_auth(project, auth).await?; + if reference_root.is_some() && resolved.root_fingerprint.is_none() { + return Err(ProjectResolverError { + kind: ProjectResolverErrorKind::IdentityUnavailable, + project: project.into(), + candidates: Vec::new(), + }); + } + Ok(resolved) + } + + // The optional root belongs to the principal's durable Ref. It is a pin to + // compare with live evidence or stored Session history, never live evidence itself. + pub(super) async fn select_project_for_auth( + &self, + project: &str, + auth: Option<&AuthContext>, + ) -> Result<(ResolvedProject, Option), ProjectResolverError> { let raw = project.trim(); if raw.is_empty() { return Err(ProjectResolverError { @@ -592,10 +761,18 @@ impl ToolRuntime { }; if let Some(candidate) = all_candidates.iter().find(|candidate| { candidate.id == reference.canonical_project_id - && candidate.root_fingerprint.as_deref() - == Some(reference.root_fingerprint.as_str()) + && match candidate.root_fingerprint.as_deref() { + Some(root) => root == reference.root_fingerprint, + None => { + candidate.root_probe_deferred + && candidate.registration_incarnation.is_some() + } + } }) { - return Ok(Self::resolved_from_candidate(project, candidate)); + return Ok(( + Self::resolved_from_candidate(project, candidate), + Some(reference.root_fingerprint), + )); } return Err(ProjectResolverError { kind: ProjectResolverErrorKind::UnknownProject, @@ -623,7 +800,7 @@ impl ToolRuntime { }); } if let Some(candidate) = all_candidates.iter().find(|candidate| candidate.id == raw) { - return Ok(Self::resolved_from_candidate(project, candidate)); + return Ok((Self::resolved_from_candidate(project, candidate), None)); } let mut same_client: Vec = all_candidates .iter() @@ -652,7 +829,7 @@ impl ToolRuntime { match matches.len() { 1 => { let candidate = matches.remove(0); - return Ok(Self::resolved_from_candidate(project, &candidate)); + return Ok((Self::resolved_from_candidate(project, &candidate), None)); } 0 => { let mut same_client: Vec = all_candidates @@ -687,7 +864,7 @@ impl ToolRuntime { match short_id_matches.len() { 1 => { let candidate = short_id_matches.remove(0); - return Ok(Self::resolved_from_candidate(project, &candidate)); + return Ok((Self::resolved_from_candidate(project, &candidate), None)); } n if n > 1 => { return Err(ProjectResolverError { @@ -708,7 +885,7 @@ impl ToolRuntime { match name_matches.len() { 1 => { let candidate = name_matches.remove(0); - Ok(Self::resolved_from_candidate(project, &candidate)) + Ok((Self::resolved_from_candidate(project, &candidate), None)) } n if n > 1 => Err(ProjectResolverError { kind: ProjectResolverErrorKind::AmbiguousProject, diff --git a/src/tool_runtime/projects.rs b/src/tool_runtime/projects.rs index da9e991f1..b444397e5 100644 --- a/src/tool_runtime/projects.rs +++ b/src/tool_runtime/projects.rs @@ -1584,6 +1584,7 @@ fn parse_project_summary_from_result( Some(value) => Some(serde_json::from_value(value.clone()).ok()?), }; Some(RunnerProjectSummary { + deferred_root_path: None, registration_incarnation: result .get("registration_incarnation") .and_then(Value::as_str) @@ -1633,6 +1634,7 @@ mod tests { #[test] fn legacy_managed_temporary_kind_is_projected_as_ordinary_registration() { let project = RunnerProjectSummary { + deferred_root_path: None, registration_incarnation: None, id: "legacy".to_string(), name: Some("Legacy".to_string()), @@ -1658,6 +1660,7 @@ mod tests { #[test] fn old_runner_auto_registered_kind_is_compatibility_fallback() { let mut project = RunnerProjectSummary { + deferred_root_path: None, registration_incarnation: None, id: "legacy-auto".to_string(), name: Some("Legacy Auto".to_string()), diff --git a/src/tool_runtime/resource_references.rs b/src/tool_runtime/resource_references.rs index 47c6f7e4b..086d02e35 100644 --- a/src/tool_runtime/resource_references.rs +++ b/src/tool_runtime/resource_references.rs @@ -139,7 +139,7 @@ impl ToolRuntime { if super::kernel::check_runtime_tool_scope(auth, "list_projects").is_err() { return error("resource_access_denied"); } - match self.resolve_project_input_for_auth(&raw, auth).await { + match self.resolve_project_metadata_for_auth(&raw, auth).await { Ok(r) => Some(r.resolved_id), Err(_) => return error("resource_unavailable"), } @@ -349,7 +349,7 @@ impl ToolRuntime { incomplete = true; continue; }; - let resolved = match self.resolve_project_input_for_auth(id, auth).await { + let resolved = match self.resolve_project_metadata_for_auth(id, auth).await { Ok(r) => r, Err(_) => { incomplete = true; diff --git a/src/tool_runtime/runtime_info.rs b/src/tool_runtime/runtime_info.rs index 76982709b..5e914862d 100644 --- a/src/tool_runtime/runtime_info.rs +++ b/src/tool_runtime/runtime_info.rs @@ -1688,8 +1688,8 @@ fn sanitized_policy_summary(policy: Option<&crate::runner_protocol::RunnerPolicy match policy { Some(p) => json!({ "allow_raw_shell": p.allow_raw_shell, - "allow_cwd_anywhere": p.allow_cwd_anywhere, - "allowed_roots": p.allowed_roots, + "allow_cwd_anywhere": p.file_access.allow_cwd_anywhere, + "allowed_roots": p.file_access.allowed_roots, "max_timeout_secs": p.max_timeout_secs, "max_output_bytes": p.max_output_bytes, }), diff --git a/src/tool_runtime/script.rs b/src/tool_runtime/script.rs index 31e93bce4..e9293ebc8 100644 --- a/src/tool_runtime/script.rs +++ b/src/tool_runtime/script.rs @@ -1,3 +1,4 @@ +use super::project_resolution::ResolvedProject; use serde_json::json; use super::helpers::{command_rejected_message, project_relative_runner_cwd, resolve_runner_cwd}; @@ -40,7 +41,7 @@ impl ToolRuntime { #[allow(clippy::too_many_arguments)] pub(crate) async fn run_script_with_contract_for_resource( &self, - project: String, + target: ResolvedProject, language: ShellScriptLanguage, script: String, args: Vec, @@ -54,6 +55,8 @@ impl ToolRuntime { validation_assertion_name: Option<&str>, auth: Option<&AuthContext>, ) -> ToolResult { + let project = target.resolved_id; + let proj = target.config; let budget = match StructuredExecutionBudget::resolve_script_with_sync_wait(timeout_secs, sync_wait_secs) { Ok(budget) => budget, @@ -112,19 +115,7 @@ impl ToolRuntime { } identity }); - let proj = match self.resolve_project(&project).await { - Ok(project) => project, - Err(error) => { - return process_tool_failure_result( - command_rejected_message( - error.to_message(), - "verify the project id with list_projects, then retry with a registered project.", - ), - "agent_offline", - ShellCommandExecutionState::NotStarted, - ) - } - }; + let client_id = proj.client_id.clone(); let (budget, timeout_notice) = apply_runner_timeout_cap( &self.runner_registry, diff --git a/src/tool_runtime/session_tools.rs b/src/tool_runtime/session_tools.rs index 85c377242..3a3bf4a72 100644 --- a/src/tool_runtime/session_tools.rs +++ b/src/tool_runtime/session_tools.rs @@ -14,8 +14,43 @@ use sha2::{Digest, Sha256}; #[derive(Clone, Copy)] pub(super) enum SessionAccess<'a> { Record, - BoundTarget, - Live { requested_project: Option<&'a str> }, + BoundTarget { + requested_project: Option<&'a str>, + }, + Live { + requested_project: Option<&'a str>, + resolved: Option<&'a super::project_resolution::ResolvedProject>, + }, +} + +pub(super) fn passive_project_read(tool: &str) -> bool { + matches!( + tool, + "list_sessions" + | "read_session_handoff" + | "get_session_handoff_state" + | "get_work_result_state" + | "read_work_result_activity_detail" + | "list_external_observations" + | "read_validation_summary" + ) +} + +impl<'a> SessionAccess<'a> { + pub(super) fn for_business( + tool: &str, + requested_project: Option<&'a str>, + resolved: Option<&'a super::project_resolution::ResolvedProject>, + ) -> Self { + if passive_project_read(tool) { + Self::BoundTarget { requested_project } + } else { + Self::Live { + requested_project, + resolved, + } + } + } } impl ToolRuntime { @@ -220,12 +255,16 @@ impl ToolRuntime { limit: Option, auth: Option<&AuthContext>, ) -> ToolResult { - // Aliases and Project refs retain their ordinary live resolution. An - // exact retired Project ID can also select the caller's stored history. - let resolution = self.resolve_project_input_for_auth(&project, auth).await; + // A cold deferred root can still match the original owner's persisted + // Session binding. Reading history never promotes that pin to live authority. + let resolution = self.select_project_for_auth(&project, auth).await; + let history_identity = resolution + .as_ref() + .ok() + .and_then(|(p, pin)| p.deferred_history_identity(pin.as_deref())); let project = resolution .as_ref() - .map_or(project.as_str(), |p| p.resolved_id.as_str()); + .map_or(project.as_str(), |(p, _)| p.resolved_id.as_str()); if !self.session_project_history_visible(project, auth).await { if let Err(error) = resolution { return error.into_tool_result(); @@ -263,6 +302,7 @@ impl ToolRuntime { let page = self.sessions.discover_sessions( project, &owner, + history_identity.as_deref(), lifecycle, offset, limit.unwrap_or(10), @@ -639,8 +679,15 @@ impl ToolRuntime { tool_name: &str, auth: Option<&AuthContext>, ) -> Result, ToolResult> { - self.authorize_session_access(session_id, tool_name, auth, SessionAccess::BoundTarget) - .await + self.authorize_session_access( + session_id, + tool_name, + auth, + SessionAccess::BoundTarget { + requested_project: None, + }, + ) + .await } pub(crate) async fn authorize_session_target( @@ -654,7 +701,7 @@ impl ToolRuntime { session_id, tool_name, auth, - SessionAccess::Live { requested_project }, + SessionAccess::for_business(tool_name, requested_project, None), ) .await } @@ -675,6 +722,9 @@ impl ToolRuntime { #[cfg(not(test))] let fixture = false; + let owner_matches = fixture + || workflow_session_authority_fingerprint(auth).ok().as_deref() == Some(owner.as_str()); + let mut history_identity = None; let resolved = match (project.as_deref(), access) { _ if fixture && auth.is_none() => None, (None, _) if !fixture && auth.is_some_and(AuthContext::is_open_anonymous) => { @@ -687,6 +737,40 @@ impl ToolRuntime { } None } + (Some(project), SessionAccess::BoundTarget { requested_project }) => { + let selector = requested_project + .filter(|p| !p.trim().is_empty()) + .unwrap_or(project); + let (target, pin) = self + .select_project_for_auth(selector, auth) + .await + .map_err(super::ProjectResolverError::into_tool_result)?; + if target.resolved_id != project { + self.resolve_project_metadata_for_auth(project, auth) + .await + .map_err(super::ProjectResolverError::into_tool_result)?; + if !owner_matches { + return Err(session_authority_denied_result(session_id, tool_name)); + } + return Err(session_project_mismatch_result( + session_id, + tool_name, + &SessionProjectMismatch { + session_project: project.into(), + request_project: target.resolved_id, + }, + )); + } + history_identity = target.deferred_history_identity(pin.as_deref()); + Some(target) + } + ( + Some(project), + SessionAccess::Live { + resolved: Some(target), + .. + }, + ) if target.resolved_id == project => Some(target.clone()), (Some(project), _) => Some( self.resolve_session_project(session_id, tool_name, project, project, auth) .await?, @@ -694,9 +778,7 @@ impl ToolRuntime { }; // Resolve the stored Project in the caller's partition first. A caller who // cannot see it gets the usual unknown_project response for the exact ID. - if !fixture - && workflow_session_authority_fingerprint(auth).ok().as_deref() != Some(owner.as_str()) - { + if !owner_matches { return Err(session_authority_denied_result(session_id, tool_name)); } self.sessions @@ -707,17 +789,24 @@ impl ToolRuntime { return Ok(None); }; if !fixture { - let identity = resolved.require_live_workflow_project_identity()?; + let identity = match history_identity { + Some(identity) if resolved.runner_connected => identity, + _ => resolved.require_live_workflow_project_identity()?, + }; match (self.sessions.session_project_identity(session_id), access) { (Some(Some(stored)), _) if stored == identity => {} - (Some(None), SessionAccess::Live { requested_project }) => { + ( + Some(None), + SessionAccess::Live { + requested_project, .. + }, + ) => { if auth.is_some_and(|a| !a.has_scope(crate::auth::SCOPE_PROJECT_READ)) { return Err(session_authority_denied_result(session_id, tool_name)); } - if let Some(input) = requested_project - .map(str::trim) - .filter(|p| !p.is_empty() && *p != resolved.resolved_id) - { + if let Some(input) = requested_project.map(str::trim).filter(|p| { + !p.is_empty() && *p != resolved.resolved_id && *p != resolved.input + }) { self.resolve_session_project( session_id, tool_name, @@ -737,7 +826,7 @@ impl ToolRuntime { ) .await?; } - (Some(None), SessionAccess::BoundTarget) => { + (Some(None), SessionAccess::BoundTarget { .. }) => { return Err(session_authority_denied_result(session_id, tool_name)) } _ => { diff --git a/src/tool_runtime/shell.rs b/src/tool_runtime/shell.rs index d5230c6fd..490dc9cd7 100644 --- a/src/tool_runtime/shell.rs +++ b/src/tool_runtime/shell.rs @@ -1,3 +1,4 @@ +use super::project_resolution::ResolvedProject; use serde_json::json; use std::time::Duration; @@ -117,8 +118,14 @@ impl ToolRuntime { timeout_secs: u64, cwd: Option, ) -> Result { - self.run_project_command_capture_impl(project, command, timeout_secs, cwd, false) - .await + self.run_resolved_project_command_capture( + &self.resolve_project(project).await?, + command, + timeout_secs, + cwd, + false, + ) + .await } pub(crate) async fn run_project_internal_posix_script_capture( @@ -128,19 +135,24 @@ impl ToolRuntime { timeout_secs: u64, cwd: Option, ) -> Result { - self.run_project_command_capture_impl(project, script, timeout_secs, cwd, true) - .await + self.run_resolved_project_command_capture( + &self.resolve_project(project).await?, + script, + timeout_secs, + cwd, + true, + ) + .await } - async fn run_project_command_capture_impl( + pub(super) async fn run_resolved_project_command_capture( &self, - project: &str, + proj: &crate::projects::ProjectConfig, command: String, timeout_secs: u64, cwd: Option, internal_posix_script: bool, ) -> Result { - let proj = self.resolve_project(project).await?; // Shared root of the sync agent-wait contract: wait_timeout_secs and // command timeout must both stay within 1..=120 before enqueue so // Runner HTTP validation never rejects with implementation-detail @@ -152,7 +164,7 @@ impl ToolRuntime { } let timeout = timeout_secs; let client_id = proj.client_id.clone(); - let effective_cwd = Some(resolve_runner_cwd(&proj, cwd.as_deref())?); + let effective_cwd = Some(resolve_runner_cwd(proj, cwd.as_deref())?); let wait_timeout = timeout; let (request_id, rx) = if internal_posix_script { self.runner_registry @@ -338,7 +350,7 @@ impl ToolRuntime { shell: Option, ) -> ToolResult { self.run_shell_with_contract_for_resource( - project, + self.resolve_project_input(&project), command, timeout_secs, sync_wait_secs, @@ -356,7 +368,8 @@ impl ToolRuntime { #[allow(clippy::too_many_arguments)] pub(crate) async fn run_shell_with_contract_for_resource( &self, - project: String, + target: impl std::future::Future> + + Send, command: String, timeout_secs: Option, sync_wait_secs: Option, @@ -422,19 +435,13 @@ impl ToolRuntime { ShellCommandExecutionState::NotStarted, ); } - let proj = match self.resolve_project(&project).await { - Ok(p) => p, - Err(e) => { - return process_tool_failure_result( - command_rejected_message( - e.to_message(), - "verify the project id with list_projects, then retry with a registered project.", - ), - "agent_offline", - ShellCommandExecutionState::NotStarted, - ) - } + + let target = match target.await { + Ok(target) => target, + Err(error) => return super::process::execution_project_rejected(error), }; + let project = target.resolved_id; + let proj = target.config; let declared_purpose = purpose.unwrap_or_default(); let command_summary = command_preview(&command); let client_id = proj.client_id.clone(); diff --git a/src/tool_runtime/shell_tools.rs b/src/tool_runtime/shell_tools.rs index deeae4d28..50c1aa603 100644 --- a/src/tool_runtime/shell_tools.rs +++ b/src/tool_runtime/shell_tools.rs @@ -1,5 +1,6 @@ //! Runtime dispatch adapter for shell tool calls. +use super::project_resolution::ResolvedProject; use super::{ToolCall, ToolResult, ToolRuntime}; use crate::auth::AuthContext; @@ -7,6 +8,7 @@ impl ToolRuntime { pub(crate) async fn dispatch_shell_tool( &self, call: ToolCall, + target: ResolvedProject, ssh_resource: Option<&str>, validation_assertion_name: Option<&str>, auth: Option<&AuthContext>, @@ -14,7 +16,7 @@ impl ToolRuntime { match call { ToolCall::RunProcess { interactive, - project, + project: _, executable, args, stdin, @@ -27,7 +29,7 @@ impl ToolRuntime { if interactive { return self .run_interactive_process( - project, + target, executable, args, stdin, @@ -41,7 +43,7 @@ impl ToolRuntime { .await; } self.run_process_with_contract_for_resource( - project, + target, executable, args, stdin, @@ -57,7 +59,7 @@ impl ToolRuntime { .await } ToolCall::RunDetachedProcess { - project, + project: _, idempotency_key, executable, args, @@ -68,7 +70,7 @@ impl ToolRuntime { purpose, } => { self.run_detached_process_with_contract( - project, + target, idempotency_key, executable, args, @@ -83,7 +85,7 @@ impl ToolRuntime { .await } ToolCall::RunScript { - project, + project: _, language, script, args, @@ -95,7 +97,7 @@ impl ToolRuntime { purpose, } => { self.run_script_with_contract_for_resource( - project, + target, language, script, args, @@ -112,7 +114,7 @@ impl ToolRuntime { .await } ToolCall::RunShell { - project, + project: _, command, session_id, timeout_secs, @@ -123,7 +125,7 @@ impl ToolRuntime { login, } => { self.run_shell_with_contract_for_resource( - project, + std::future::ready(Ok(target)), command, timeout_secs, sync_wait_secs, diff --git a/src/tool_runtime/skills.rs b/src/tool_runtime/skills.rs index cc7c8de9b..9e6898332 100644 --- a/src/tool_runtime/skills.rs +++ b/src/tool_runtime/skills.rs @@ -1095,7 +1095,7 @@ impl ToolRuntime { }; let mut result = self .run_skill_resource_with_contract( - project.resolved_id.clone(), + project.clone(), execution_request, timeout_secs, sync_wait_secs, diff --git a/src/tool_runtime/startup_brief.rs b/src/tool_runtime/startup_brief.rs index 27c36e236..d87ab978b 100644 --- a/src/tool_runtime/startup_brief.rs +++ b/src/tool_runtime/startup_brief.rs @@ -1882,6 +1882,7 @@ mod tests { SessionGuards::default(), ); let resolved = ResolvedProject { + root_probe_deferred: false, input: "agent:size:demo".to_string(), resolved_id: "agent:size:demo".to_string(), config: ProjectConfig { diff --git a/src/tool_runtime/tests/coding_task.rs b/src/tool_runtime/tests/coding_task.rs index 760e8cc2a..9d6e917ae 100644 --- a/src/tool_runtime/tests/coding_task.rs +++ b/src/tool_runtime/tests/coding_task.rs @@ -291,7 +291,10 @@ async fn coding_workflow_minimal_brief_is_bounded_and_path_safe() { init_git_repo(tmp.path()); let runtime = test_runtime(); let policy = RunnerPolicySummary { - allowed_roots: vec![PathBuf::from("/tmp/startup-full-allowed-root")], + file_access: crate::runner_protocol::RunnerFileAccessPolicy { + allow_cwd_anywhere: false, + allowed_roots: vec![PathBuf::from("/tmp/startup-full-allowed-root")], + }, ..Default::default() }; register_agent_with_shell_profiles( @@ -356,7 +359,10 @@ async fn coding_workflow_standard_returns_model_facing_brief_without_diagnostics init_git_repo(tmp.path()); let runtime = test_runtime(); let policy = RunnerPolicySummary { - allowed_roots: vec![PathBuf::from("/tmp/compact-allowed-root-never-emit")], + file_access: crate::runner_protocol::RunnerFileAccessPolicy { + allow_cwd_anywhere: false, + allowed_roots: vec![PathBuf::from("/tmp/compact-allowed-root-never-emit")], + }, ..Default::default() }; register_agent_with_shell_profiles( diff --git a/src/tool_runtime/tests/memory.rs b/src/tool_runtime/tests/memory.rs index d3fc39b2b..018ba516a 100644 --- a/src/tool_runtime/tests/memory.rs +++ b/src/tool_runtime/tests/memory.rs @@ -16,6 +16,7 @@ use std::sync::Arc; fn resolved(id: &str, client: &str, root: &str) -> ResolvedProject { ResolvedProject { + root_probe_deferred: false, input: id.to_string(), resolved_id: id.to_string(), config: ProjectConfig { diff --git a/src/tool_runtime/tests/metadata.rs b/src/tool_runtime/tests/metadata.rs index 5dfa5932e..0f51498ef 100644 --- a/src/tool_runtime/tests/metadata.rs +++ b/src/tool_runtime/tests/metadata.rs @@ -1472,8 +1472,10 @@ async fn list_projects_shows_shell_profile_resolution() { }; let policy = RunnerPolicySummary { allow_raw_shell: true, - allow_cwd_anywhere: true, - allowed_roots: Vec::new(), + file_access: crate::runner_protocol::RunnerFileAccessPolicy { + allow_cwd_anywhere: true, + allowed_roots: Vec::new(), + }, max_timeout_secs: 3600, max_output_bytes: 262144, shell_profiles: Some(summary), @@ -1606,8 +1608,10 @@ async fn runtime_status_shell_profiles_summary_is_sanitized() { owner: Some("alice".to_string()), policy: Some(RunnerPolicySummary { allow_raw_shell: true, - allow_cwd_anywhere: false, - allowed_roots: Vec::new(), + file_access: crate::runner_protocol::RunnerFileAccessPolicy { + allow_cwd_anywhere: false, + allowed_roots: Vec::new(), + }, max_timeout_secs: 3600, max_output_bytes: 262144, shell_profiles: Some(summary), @@ -2562,9 +2566,12 @@ async fn runtime_status_compact_and_summary_only_return_sanitized_summary() { let _env = crate::test_support::TestEnvGuard::new(); let runtime = test_runtime(); let policy = RunnerPolicySummary { - allowed_roots: vec![PathBuf::from( - "/tmp/runtime-compact-allowed-root-never-emit", - )], + file_access: crate::runner_protocol::RunnerFileAccessPolicy { + allow_cwd_anywhere: false, + allowed_roots: vec![PathBuf::from( + "/tmp/runtime-compact-allowed-root-never-emit", + )], + }, shell_profiles: Some(ShellProfilesSummary { default_dialect: None, available_dialects: None, @@ -2925,8 +2932,10 @@ async fn runtime_status_includes_sanitized_policy_summary() { registration.owner = Some("alice".to_string()); registration.policy = Some(RunnerPolicySummary { allow_raw_shell: true, - allow_cwd_anywhere: false, - allowed_roots: vec![std::path::PathBuf::from("/root")], + file_access: crate::runner_protocol::RunnerFileAccessPolicy { + allow_cwd_anywhere: false, + allowed_roots: vec![std::path::PathBuf::from("/root")], + }, max_timeout_secs: 3600, max_output_bytes: 262144, shell_profiles: None, @@ -3370,8 +3379,10 @@ async fn list_runners_includes_sanitized_policy_summary() { registration.owner = Some("alice".to_string()); registration.policy = Some(RunnerPolicySummary { allow_raw_shell: false, - allow_cwd_anywhere: true, - allowed_roots: vec![], + file_access: crate::runner_protocol::RunnerFileAccessPolicy { + allow_cwd_anywhere: true, + allowed_roots: vec![], + }, max_timeout_secs: 120, max_output_bytes: 4096, shell_profiles: None, diff --git a/src/tool_runtime/tests/project_references.rs b/src/tool_runtime/tests/project_references.rs index bafee52fe..b9edb395f 100644 --- a/src/tool_runtime/tests/project_references.rs +++ b/src/tool_runtime/tests/project_references.rs @@ -562,3 +562,253 @@ async fn stale_project_ref_never_retargets_and_survives_store_reopen() { canonical ); } + +#[tokio::test] +async fn deferred_root_discovery_is_passive_and_explicit_reference_rechecks_identity() { + let tmp = tempfile::tempdir().unwrap(); + let open = || { + let db = tmp.path().join("refs.db"); + runtime_with_reference_db(&db) + .with_session_database(&db, &tmp.path().join("sessions.json")) + .unwrap() + }; + let runtime = open(); + let canonical = "agent:deferred:repo"; + let owner_auth = auth_context(Some("owner"), false); + let auth = Some(&owner_auth); + let path = r"\\wsl.localhost\Distro\repo"; + let canonical_path = r"\\?\UNC\wsl.localhost\Distro\repo"; + let mut row = project("deferred", "repo", "repo", path, '5'); + row.revision = Some(format!("sha256:{}", "1".repeat(64))); + let caps = RunnerCapabilities { + project_path_registration: true, + shell: true, + internal_posix_script: true, + ..Default::default() + }; + register_agent_projects( + &runtime, + "deferred", + Some("owner"), + caps.clone(), + vec![row.clone()], + ) + .await; + let before = runtime + .resolve_project_input_for_auth(canonical, auth) + .await + .unwrap(); + let reference = runtime + .project_reference_for_resolved(&before, auth) + .unwrap(); + let identity = before.workflow_project_identity().unwrap(); + let owner = crate::tool_runtime::workflow_session_authority_fingerprint(auth).unwrap(); + let start = |identity: String| { + runtime + .sessions + .start_session_with_options( + webcodex_workflow_session::SessionCreateOptions::new( + Some(canonical.into()), + None, + crate::tool_runtime::SessionMode::Normal, + Default::default(), + ) + .with_owner_authority_fingerprint(Some(owner.clone())) + .with_project_identity(Some(identity)), + ) + .unwrap() + .session_id + }; + let original_session = start(identity.clone()); + start("f".repeat(64)); + runtime.sessions.flush().await.unwrap(); + row.root_fingerprint = None; + row.deferred_root_path = Some(row.path.clone()); + drop(runtime); + let runtime = open(); + register_agent_projects(&runtime, "deferred", Some("owner"), caps, vec![row.clone()]).await; + // Metadata discovery must not wait for any request to the remote filesystem. + let passive = tokio::time::timeout( + std::time::Duration::from_secs(1), + runtime.resolve_project_metadata_for_auth(canonical, auth), + ) + .await + .unwrap() + .unwrap(); + assert!(passive.root_probe_deferred); + let history = tokio::time::timeout( + std::time::Duration::from_secs(1), + runtime.list_sessions_tool(reference.clone(), None, None, None, auth), + ) + .await + .unwrap(); + assert!(history.success, "{history:?}"); + assert_eq!(history.output["total"], 1); + assert_eq!( + history.output["sessions"][0]["session_id"], + original_session + ); + let summary = tokio::time::timeout( + std::time::Duration::from_secs(1), + runtime.validation_summary_tool(reference.clone(), original_session.clone(), None, auth), + ) + .await + .unwrap(); + assert!(summary.success, "{summary:?}"); + let default_handoff = || async { + let handoff = tokio::time::timeout( + std::time::Duration::from_secs(1), + runtime.session_handoff_summary( + original_session.clone(), + Some(reference.clone()), + None, + None, + None, + true, + None, + auth, + ), + ) + .await + .unwrap(); + assert!(handoff.success, "{handoff:?}"); + assert!(handoff.output.get("workspace").is_none()); + assert!(handoff.output.get("checkpoints").is_none()); + }; + default_handoff().await; + async fn reply( + runtime: &ToolRuntime, + row: &RunnerProjectSummary, + path: &str, + fingerprint: String, + ) { + let request = + wait_for_runner_request_for_instance(runtime, "deferred", "inst-deferred").await; + assert_eq!(request.kind, "project_probe_identity"); + let output = json!({"agent_project_id":"repo","revision":row.revision, + "registration_incarnation":row.registration_incarnation, "outcome":"observed", + "changed":false,"path":path,"root_fingerprint":fingerprint}); + complete_patch_agent_request_for_instance( + runtime, + "deferred", + "inst-deferred", + &request.request_id, + 0, + &output.to_string(), + "", + ) + .await; + } + let (resolved, ()) = tokio::join!( + runtime.resolve_project_input_for_auth(&reference, auth), + reply(&runtime, &row, canonical_path, root('5')) + ); + let resolved = resolved.unwrap(); + assert_eq!( + resolved.config.path, canonical_path, + "dispatch must use the observed canonical path" + ); + assert_eq!( + resolved.workflow_project_identity().as_deref(), + Some(identity.as_str()) + ); + default_handoff().await; + let (explicit_handoff, ()) = tokio::join!( + runtime.session_handoff_summary( + original_session.clone(), + Some(reference.clone()), + Some(true), + Some(true), + None, + true, + None, + auth + ), + async { + reply(&runtime, &row, canonical_path, root('5')).await; + let request = + wait_for_runner_request_for_instance(&runtime, "deferred", "inst-deferred").await; + assert_ne!( + request.kind, "project_probe_identity", + "workspace must reuse the authorized root" + ); + assert_eq!(request.cwd.as_deref(), Some(canonical_path)); + let stdout = crate::tool_runtime::framed_clean_show_changes_test_stdout("head", false); + complete_patch_agent_request_for_instance( + &runtime, + "deferred", + "inst-deferred", + &request.request_id, + 0, + &stdout, + "", + ) + .await; + } + ); + assert!(explicit_handoff.success, "{explicit_handoff:?}"); + assert_eq!(explicit_handoff.output["workspace"]["git_available"], true); + // A separate execution verifies even a previously observed ordinary root. + // Its Session guard and shell executor share that single observation. + let call = ToolCall::from_tool_name( + "run_shell", + json!({"project":reference,"session_id":original_session, + "command":"pwd","timeout_secs":10,"sync_wait_secs":10}), + ) + .unwrap(); + tokio::join!( + async { + let result = runtime.dispatch_with_auth(call, auth).await; + assert!(result.success, "{result:?}"); + }, + async { + reply(&runtime, &row, canonical_path, root('5')).await; + let command = + wait_for_runner_request_for_instance(&runtime, "deferred", "inst-deferred").await; + assert_eq!( + command.command, "pwd", + "unexpected second root probe: {}", + command.kind + ); + assert_eq!(command.cwd.as_deref(), Some(canonical_path)); + complete_patch_agent_request_for_instance( + &runtime, + "deferred", + "inst-deferred", + &command.request_id, + 0, + canonical_path, + "", + ) + .await; + } + ); + // The registration, revision and allowed roots stay the same when the + // directory becomes a symlink. Neither the previous Ref nor the Session + // may inherit the newly observed root. + let (stale_ref, ()) = tokio::join!( + runtime.resolve_project_input_for_auth(&reference, auth), + reply(&runtime, &row, "/retargeted/path", root('6')) + ); + assert!(stale_ref.is_err()); + let session_call = ToolCall::from_tool_name( + "run_shell", + json!({ + "project":canonical, "session_id":original_session, "command":"pwd" + }), + ) + .unwrap(); + let (denied, ()) = tokio::join!( + runtime.dispatch_with_auth(session_call, auth), + reply(&runtime, &row, "/retargeted/path", root('6')) + ); + assert!(!denied.success, "{denied:?}"); + assert_eq!( + denied.output["error_kind"], + "session_project_identity_changed" + ); + assert!(runtime + .resolve_project_input_for_auth(&reference, auth) + .await + .is_err()); +} diff --git a/src/tool_runtime/tests/session_shells.rs b/src/tool_runtime/tests/session_shells.rs index 0a35884ed..ff358293c 100644 --- a/src/tool_runtime/tests/session_shells.rs +++ b/src/tool_runtime/tests/session_shells.rs @@ -26,6 +26,7 @@ async fn setup( ..Default::default() }, vec![RunnerProjectSummary { + deferred_root_path: None, registration_incarnation: Some(uuid::Uuid::new_v4().to_string()), id: PROJECT_ID.to_string(), name: Some(PROJECT_ID.to_string()), @@ -1134,6 +1135,7 @@ async fn setup_ssh_with_capabilities( ..Default::default() }, vec![RunnerProjectSummary { + deferred_root_path: None, registration_incarnation: Some(uuid::Uuid::new_v4().to_string()), id: PROJECT_ID.to_string(), name: Some(PROJECT_ID.to_string()), diff --git a/src/tool_runtime/tests/support/runner.rs b/src/tool_runtime/tests/support/runner.rs index 5c5ad5014..e6fb4fe01 100644 --- a/src/tool_runtime/tests/support/runner.rs +++ b/src/tool_runtime/tests/support/runner.rs @@ -834,6 +834,7 @@ pub(in crate::tool_runtime::tests) fn registered_project( path: &str, ) -> RunnerProjectSummary { RunnerProjectSummary { + deferred_root_path: None, id: id.to_string(), name: Some(id.to_string()), path: path.to_string(), @@ -864,6 +865,7 @@ pub(in crate::tool_runtime::tests) fn named_registered_project( ) -> RunnerProjectSummary { let _ = client_id; RunnerProjectSummary { + deferred_root_path: None, id: id.to_string(), name: Some(name.to_string()), path: path.to_string(), diff --git a/src/tool_runtime/tests/workspace_reads.rs b/src/tool_runtime/tests/workspace_reads.rs index 5e069a42c..613ea2250 100644 --- a/src/tool_runtime/tests/workspace_reads.rs +++ b/src/tool_runtime/tests/workspace_reads.rs @@ -4,6 +4,7 @@ use std::time::Duration; fn resolved() -> ResolvedProject { ResolvedProject { + root_probe_deferred: false, input: "short-alias".into(), resolved_id: "agent:runner:project".into(), config: crate::projects::ProjectConfig { diff --git a/src/tool_runtime/validation_events.rs b/src/tool_runtime/validation_events.rs index c3738868a..c7faf9dec 100644 --- a/src/tool_runtime/validation_events.rs +++ b/src/tool_runtime/validation_events.rs @@ -51,15 +51,16 @@ impl ToolRuntime { limit: Option, auth: Option<&AuthContext>, ) -> ToolResult { - if let Err(result) = self + let resolved = match self .authorize_session_target(&session_id, "read_validation_summary", Some(&project), auth) .await { - return result; - } - let resolved = match self.resolve_project_input_for_auth(&project, auth).await { - Ok(resolved) => resolved, - Err(err) => return err.into_tool_result(), + Ok(Some(resolved)) => resolved, + Ok(None) => match self.resolve_project_metadata_for_auth(&project, auth).await { + Ok(resolved) => resolved, + Err(error) => return error.into_tool_result(), + }, + Err(result) => return result, }; let Some(summary) = self .sessions diff --git a/src/tool_runtime/work_result.rs b/src/tool_runtime/work_result.rs index 0eb9a4711..23cc5875a 100644 --- a/src/tool_runtime/work_result.rs +++ b/src/tool_runtime/work_result.rs @@ -267,7 +267,7 @@ impl ToolRuntime { auth: Option<&AuthContext>, ) -> Result { let resolved = self - .resolve_project_input_for_auth(project, auth) + .resolve_project_metadata_for_auth(project, auth) .await .map_err(|error| error.into_tool_result())?; let issued_ref = matches!( diff --git a/src/tool_runtime/workbench_state.rs b/src/tool_runtime/workbench_state.rs index a638c59ee..7de48b60e 100644 --- a/src/tool_runtime/workbench_state.rs +++ b/src/tool_runtime/workbench_state.rs @@ -142,7 +142,7 @@ impl ToolRuntime { ); None } else { - match self.resolve_project_input_for_auth(&input, auth).await { + match self.resolve_project_metadata_for_auth(&input, auth).await { Ok(resolved) => Some(resolved.resolved_id), Err(_) => { section_error(