From 283b01213218713be80ccfb7209ad641b52f88c0 Mon Sep 17 00:00:00 2001 From: Vincent Date: Sun, 20 Sep 2026 19:18:05 -0400 Subject: [PATCH 1/3] fix(agent): restore session view before tools and reject recording drift --- atomic-agent/src/record/mod.rs | 62 +++++ atomic-agent/src/record/tests.rs | 36 ++- .../src/turn/orchestrator/session_start.rs | 53 +++++ atomic-agent/src/turn/orchestrator/tests.rs | 218 ++++++++++++++++++ atomic-agent/src/turn/orchestrator/turn.rs | 1 + 5 files changed, 358 insertions(+), 12 deletions(-) diff --git a/atomic-agent/src/record/mod.rs b/atomic-agent/src/record/mod.rs index cc20f4cf..7b5f43cd 100644 --- a/atomic-agent/src/record/mod.rs +++ b/atomic-agent/src/record/mod.rs @@ -110,6 +110,62 @@ fn build_turn_header( .build() } +// A freshly forked view can reuse the same working copy only when the full +// visible change/dependency closure is identical. Path-table occupants and +// journal baselines cannot prove this. Sandboxes already scope their own view. +fn validate_recording_view( + repo: &atomic_repository::Repository, + options: &TurnRecordOptions<'_>, +) -> AgentResult<()> { + use atomic_core::pristine::ViewTxnT; + use atomic_repository::repository::collect_visible_change_ids_with_deps; + // A validated explicit manifest names each write/deletion deliberately; + // it does not infer absent files from the whole working directory. + let explicitly_scoped = options + .event + .raw_json + .as_ref() + .is_some_and(|raw| raw.get("record_files").is_some()); + if repo.is_sandbox() || explicitly_scoped || repo.current_view() == options.session.view_name { + return Ok(()); + } + let fail = |reason: String| AgentError::RecordFailed { + session_id: options.session.session_id.clone(), + turn_number: options.turn_number, + reason, + }; + let txn = repo + .pristine() + .read_txn() + .map_err(|e| fail(e.to_string()))?; + // A missing first-turn view may still be forked from the selected parent. + // It must not be reconstructed over a different closure at record time. + let target = txn + .get_view(&options.session.view_name) + .map_err(|e| fail(e.to_string()))?; + let target_name = target + .as_ref() + .map(|_| options.session.view_name.as_str()) + .unwrap_or_else(|| options.session.parent_view().unwrap_or(repo.current_view())); + let current = txn + .get_view(repo.current_view()) + .map_err(|e| fail(e.to_string()))?; + let target = txn.get_view(target_name).map_err(|e| fail(e.to_string()))?; + if let (Some(current), Some(target)) = (current, target) { + let current_ids = collect_visible_change_ids_with_deps(&txn, ¤t) + .map_err(|e| fail(e.to_string()))?; + let target_ids = + collect_visible_change_ids_with_deps(&txn, &target).map_err(|e| fail(e.to_string()))?; + if current_ids == target_ids { + return Ok(()); + } + } + Err(fail(format!( + "working directory view '{}' differs from session view '{}'; refusing to record against a different closure. Files are unchanged; preserve pending work before resuming the session on its view", + repo.current_view(), options.session.view_name, + ))) +} + // record_turn (the main entry point) /// Record an agent turn as an Atomic change. @@ -162,6 +218,8 @@ pub fn record_turn( reason: format!("Failed to open repository (readonly): {}", e), })?; + validate_recording_view(&repo, options)?; + // `status()` reads current_view, while `record()` writes to session.view_name. // Align the read-only handle before the first status check; this keeps the // no-lock fast path and prevents direct callers from seeing false EmptyTurn. @@ -225,6 +283,10 @@ pub fn record_turn( reason: format!("Failed to open repository for recording: {}", e), })?; + // Recheck after acquiring the writer: another process may have switched + // views since the initial read-only status check. + validate_recording_view(&repo, options)?; + // Keep the write handle on the same view for post-add status and record. // First turns may target a view that record/apply will create; other failures // mean we cannot trust the detection/apply alignment. diff --git a/atomic-agent/src/record/tests.rs b/atomic-agent/src/record/tests.rs index 4da15da1..72348bef 100644 --- a/atomic-agent/src/record/tests.rs +++ b/atomic-agent/src/record/tests.rs @@ -1056,10 +1056,10 @@ fn count_occurrences(content: &str, pattern: &str) -> usize { /// This test drives two sessions through `record_turn()` directly: session /// A whose view is properly forked from `dev` beforehand (the normal path), /// and session B whose view is deliberately left unforked (the orphan -/// path). Per the fix, `record_turn()` must self-heal session B by forking -/// its view just-in-time from its intended parent (`dev`) rather than -/// silently recording onto the wrong view. After merging both sessions' -/// views into `dev`, every function in the file must appear exactly once. +/// path). Recording first rejects a mismatched working-copy closure. Once +/// the caller restores the intended parent, it may fork B's missing view. +/// After inserting both sessions' changes into dev, every function must +/// appear exactly once. #[test] fn test_orphaned_session_view_duplicates_content_on_merge() { use atomic_repository::apply::CrossViewInsertOptions; @@ -1113,13 +1113,9 @@ fn test_orphaned_session_view_duplicates_content_on_merge() { record_turn(repo_root, &options_a).unwrap(); // Session B: simulates a SessionStart fork that never ran (or failed) — - // its view does not exist yet when record_turn() is called. Per the - // orphan-view duplication fix, record_turn() must self-heal by forking - // it just-in-time from its intended parent ("dev"), NOT from whatever - // view happens to be current on the internally-opened Repository handle - // (which after session A's turn is "session-a" — forking from there - // would leak session A's edit into session B's history and, once both - // are merged into dev, resurrect it as a duplicate). + // its view does not exist yet when record_turn() is called. Do not + // repair that by recording over A's working-copy closure. Reject first, + // then retry after the caller restores B's intended parent ("dev"). let mut session_b = AgentSession::new("session-b", "claude-code", "Claude Code"); session_b.view_name = "session-b".to_string(); session_b.set_parent_view("dev"); @@ -1135,8 +1131,24 @@ fn test_orphaned_session_view_duplicates_content_on_merge() { turn_duration_ms: 1000, prompt: Some("Bump step70".to_string()), }; + let error = record_turn(repo_root, &options_b).unwrap_err(); + assert!(error.to_string().contains("different closure")); + assert_eq!(std::fs::read_to_string(&file).unwrap(), edited_b); + assert_eq!( + Repository::open_readonly(repo_root).unwrap().current_view(), + "session-a" + ); + + // Preserve the intended B edit in memory, restore A's clean content, then + // explicitly render B's intended parent before retrying the orphan fork. + std::fs::write(&file, &edited_a).unwrap(); + Repository::open_existing(repo_root) + .unwrap() + .switch_view("dev") + .unwrap(); + std::fs::write(&file, &edited_b).unwrap(); record_turn(repo_root, &options_b) - .expect("record_turn should self-heal an orphaned session view rather than fail"); + .expect("a missing view can be forked when the working copy is on its intended parent"); // Merge both session views into dev. { diff --git a/atomic-agent/src/turn/orchestrator/session_start.rs b/atomic-agent/src/turn/orchestrator/session_start.rs index 1965c2ed..d46ed8f4 100644 --- a/atomic-agent/src/turn/orchestrator/session_start.rs +++ b/atomic-agent/src/turn/orchestrator/session_start.rs @@ -12,6 +12,58 @@ use super::{vendor_from_agent_name, DispatchResult, TurnOrchestrator}; const SESSION_DATABASE_WAIT: std::time::Duration = std::time::Duration::from_secs(10); impl TurnOrchestrator { + /// Prepare the working copy before a resumed session can run tools. + /// Files absent from another closure are not user deletions. Never change + /// the selected view over unrecorded work, and never defer rendering to Stop. + pub(super) fn prepare_session_view(&self, session: &AgentSession) -> AgentResult<()> { + use atomic_repository::{status::StatusOptions, Repository}; + // Lifecycle-only callers can track sessions outside an initialized VCS. + let Ok(dot_dir) = Repository::canonical_dot_dir(&self.repo_root) else { + return Ok(()); + }; + if !dot_dir.join("pristine.redb").is_file() { + return Ok(()); + } + // No transition or database access is needed when the published view + // already matches. This also permits callers holding a read handle. + if std::fs::read_to_string(dot_dir.join("current_view")) + .is_ok_and(|view| view.trim() == session.view_name) + { + return Ok(()); + } + let fail = |reason: String| { + crate::error::AgentError::Internal(format!( + "Cannot prepare view '{}' for session {}: {reason}", + session.view_name, session.session_id, + )) + }; + let repo = Repository::open_readonly_wait(&self.repo_root, SESSION_DATABASE_WAIT) + .map_err(|e| fail(e.to_string()))?; + // A sandbox's view is scoped to its working directory. It must never + // publish a switch to the canonical user's working copy. + if repo.is_sandbox() || repo.current_view() == session.view_name { + return Ok(()); + } + drop(repo); + let mut repo = Repository::open_existing_wait(&self.repo_root, SESSION_DATABASE_WAIT) + .map_err(|e| fail(e.to_string()))?; + if repo.current_view() == session.view_name { + return Ok(()); + } + let status = repo + .status(StatusOptions::default().with_untracked(true)) + .map_err(|e| fail(e.to_string()))?; + if !status.is_clean() || status.has_untracked() || status.has_conflicts() { + return Err(fail(format!( + "working directory is on view '{}' with unrecorded files; preserve or record that work on its current view before resuming. No files were switched", + repo.current_view(), + ))); + } + repo.switch_view(&session.view_name) + .map_err(|e| fail(e.to_string()))?; + Ok(()) + } + /// Handle a SessionStart event. /// /// Creates a new session or re-enters an ended session. Creates the @@ -41,6 +93,7 @@ impl TurnOrchestrator { // Load or create session let mut session = match self.session_store.load(session_id)? { Some(mut existing) => { + self.prepare_session_view(&existing)?; // Re-entering an existing session (same session_id) let result = phase::transition( existing.phase, diff --git a/atomic-agent/src/turn/orchestrator/tests.rs b/atomic-agent/src/turn/orchestrator/tests.rs index f41d9c5e..f98ce3af 100644 --- a/atomic-agent/src/turn/orchestrator/tests.rs +++ b/atomic-agent/src/turn/orchestrator/tests.rs @@ -1311,3 +1311,221 @@ async fn test_sandbox_session_files_land_in_canonical_store() { "sandbox session must not be stranded in a sandbox-local .atomic" ); } + +// A view change is not an edit. Resuming must render the selected closure +// before a tool runs, and recording must not infer deletions from another view. +fn resume_file_inode(dir: &TempDir) -> u64 { + use atomic_core::pristine::TreeTxnT; + let repo = Repository::open_readonly(dir.path()).unwrap(); + let txn = repo.pristine().read_txn().unwrap(); + txn.get_inode("session-only.txt").unwrap().unwrap().get() +} + +async fn resume_view_fixture() -> (TempDir, TurnOrchestrator, String, u64) { + let dir = TempDir::new().unwrap(); + let repo = Repository::init(dir.path()).unwrap(); + fs::write(dir.path().join("base.txt"), "base\n").unwrap(); + repo.add("base.txt", atomic_repository::TrackingOptions::default()) + .unwrap(); + repo.record( + atomic_core::change::ChangeHeader::new("base"), + atomic_repository::RecordOptions::new() + .with_all(true) + .save_to_store(true) + .apply_after_record(true), + ) + .unwrap(); + drop(repo); + let mut orch = make_orchestrator(&dir); + orch.dispatch(session_start_event("resume-view")) + .await + .unwrap(); + orch.dispatch(turn_start_event("resume-view", "create file")) + .await + .unwrap(); + fs::write(dir.path().join("session-only.txt"), "keep me\n").unwrap(); + assert!(orch + .dispatch(turn_end_event("resume-view")) + .await + .unwrap() + .was_recorded()); + let view = orch + .session_store + .load("resume-view") + .unwrap() + .unwrap() + .view_name; + let inode = resume_file_inode(&dir); + Repository::open_existing(dir.path()) + .unwrap() + .switch_view("dev") + .unwrap(); + assert!(!dir.path().join("session-only.txt").exists()); + (dir, orch, view, inode) +} + +#[tokio::test] +async fn resume_view_materializes_before_session_or_turn_start() { + for session_start in [true, false] { + let (dir, mut orch, view, inode) = resume_view_fixture().await; + if session_start { + orch.dispatch(session_start_event("resume-view")) + .await + .unwrap(); + } else { + orch.dispatch(turn_start_event("resume-view", "resume without startup")) + .await + .unwrap(); + } + assert_eq!( + Repository::open_readonly(dir.path()) + .unwrap() + .current_view(), + view + ); + assert_eq!(resume_file_inode(&dir), inode); + assert_eq!( + fs::read_to_string(dir.path().join("session-only.txt")).unwrap(), + "keep me\n" + ); + if session_start { + orch.dispatch(turn_start_event("resume-view", "edit base")) + .await + .unwrap(); + } + fs::write(dir.path().join("base.txt"), "edited\n").unwrap(); + assert!(orch + .dispatch(turn_end_event("resume-view")) + .await + .unwrap() + .was_recorded()); + assert_eq!(resume_file_inode(&dir), inode); + assert_eq!( + fs::read_to_string(dir.path().join("session-only.txt")).unwrap(), + "keep me\n" + ); + // Reopening and switching away/back must still render the original file. + let mut repo = Repository::open_existing(dir.path()).unwrap(); + repo.switch_view("dev").unwrap(); + repo.switch_view(&view).unwrap(); + drop(repo); + assert_eq!(resume_file_inode(&dir), inode); + assert_eq!( + fs::read_to_string(dir.path().join("session-only.txt")).unwrap(), + "keep me\n" + ); + } +} + +#[tokio::test] +async fn resume_view_preserves_dirty_or_untracked_work_and_can_retry() { + for untracked in [false, true] { + let (dir, mut orch, view, inode) = resume_view_fixture().await; + let path = if untracked { + "session-only.txt" + } else { + "base.txt" + }; + fs::write(dir.path().join(path), "pending human work\n").unwrap(); + let error = orch + .dispatch(session_start_event("resume-view")) + .await + .unwrap_err(); + assert!(error.to_string().contains("unrecorded"), "{error}"); + assert_eq!( + fs::read_to_string(dir.path().join(path)).unwrap(), + "pending human work\n" + ); + assert_eq!( + Repository::open_readonly(dir.path()) + .unwrap() + .current_view(), + "dev" + ); + assert!(orch + .dispatch(turn_start_event("resume-view", "retry still dirty")) + .await + .is_err()); + // Resolve the test's pending work explicitly, then retry the lifecycle. + if untracked { + fs::remove_file(dir.path().join(path)).unwrap(); + } else { + fs::write(dir.path().join(path), "base\n").unwrap(); + } + orch.dispatch(session_start_event("resume-view")) + .await + .unwrap(); + assert_eq!( + Repository::open_readonly(dir.path()) + .unwrap() + .current_view(), + view + ); + assert_eq!(resume_file_inode(&dir), inode); + assert_eq!( + fs::read_to_string(dir.path().join("session-only.txt")).unwrap(), + "keep me\n" + ); + } +} + +#[tokio::test] +async fn resume_view_record_rejects_drift_instead_of_recording_deletions() { + let (dir, orch, _view, _) = resume_view_fixture().await; + let session = orch.session_store.load("resume-view").unwrap().unwrap(); + fs::write(dir.path().join("base.txt"), "pending edit\n").unwrap(); + let event = turn_end_event("resume-view"); + let options = crate::record::TurnRecordOptions { + session: &session, + event: &event, + turn_number: 2, + turn_duration_ms: 0, + prompt: Some("edit base".into()), + }; + let error = crate::record::record_turn(dir.path(), &options).unwrap_err(); + assert!(error.to_string().contains("view"), "{error}"); + assert_eq!( + Repository::open_readonly(dir.path()) + .unwrap() + .current_view(), + "dev" + ); + assert_eq!( + fs::read_to_string(dir.path().join("base.txt")).unwrap(), + "pending edit\n" + ); + assert_eq!( + orch.session_store + .load("resume-view") + .unwrap() + .unwrap() + .recorded_change_hashes + .len(), + 1 + ); +} + +#[tokio::test] +async fn resume_view_still_records_an_intentional_deletion() { + let (dir, mut orch, view, _) = resume_view_fixture().await; + orch.dispatch(session_start_event("resume-view")) + .await + .unwrap(); + orch.dispatch(turn_start_event("resume-view", "delete session-only.txt")) + .await + .unwrap(); + fs::remove_file(dir.path().join("session-only.txt")).unwrap(); + assert!(orch + .dispatch(turn_end_event("resume-view")) + .await + .unwrap() + .was_recorded()); + let mut repo = Repository::open_existing(dir.path()).unwrap(); + repo.switch_view("dev").unwrap(); + repo.switch_view(&view).unwrap(); + assert!(!dir.path().join("session-only.txt").exists()); + assert_eq!( + fs::read_to_string(dir.path().join("base.txt")).unwrap(), + "base\n" + ); +} diff --git a/atomic-agent/src/turn/orchestrator/turn.rs b/atomic-agent/src/turn/orchestrator/turn.rs index 32045281..0e80ab9e 100644 --- a/atomic-agent/src/turn/orchestrator/turn.rs +++ b/atomic-agent/src/turn/orchestrator/turn.rs @@ -41,6 +41,7 @@ impl TurnOrchestrator { let session_id = &event.session_id; let mut session = self.load_or_create_session(session_id, &event)?; + self.prepare_session_view(&session)?; let turn_number = session.turn_count.saturating_add(1); if session.managed_run.is_none() || self.managed_run.is_some() { self.resume_journal_turn(session_id, turn_number, event.timestamp.timestamp())?; From 848fdd340ad45f5d99cc3a97a0fa0e4bc9f13a78 Mon Sep 17 00:00:00 2001 From: Vincent Date: Sun, 20 Sep 2026 19:47:32 -0400 Subject: [PATCH 2/3] fix(agent): persist and verify incomplete view restoration --- atomic-agent/src/record/mod.rs | 46 ++++++ .../src/turn/orchestrator/session_start.rs | 83 ++++++++-- atomic-agent/src/turn/orchestrator/tests.rs | 154 ++++++++++++++++++ atomic-agent/src/turn/orchestrator/turn.rs | 4 + 4 files changed, 276 insertions(+), 11 deletions(-) diff --git a/atomic-agent/src/record/mod.rs b/atomic-agent/src/record/mod.rs index 7b5f43cd..f9171dd0 100644 --- a/atomic-agent/src/record/mod.rs +++ b/atomic-agent/src/record/mod.rs @@ -110,6 +110,50 @@ fn build_turn_header( .build() } +// Operational completion marker only: it names a target view, never paths, +// inode ownership, inverse changes, or file-history baselines. +pub(crate) const VIEW_PREPARATION_PENDING_FILE: &str = "agent-view-prepare.pending"; + +// Hooks that have not opened a repository yet only pay for a database read +// when an incomplete transition actually exists. +pub(crate) fn ensure_view_preparation_complete_at(root: &Path) -> AgentResult<()> { + let Ok(dot_dir) = atomic_repository::Repository::canonical_dot_dir(root) else { + return Ok(()); + }; + if !dot_dir + .join(VIEW_PREPARATION_PENDING_FILE) + .try_exists() + .map_err(|e| AgentError::Internal(format!("Cannot check session view restoration: {e}")))? + { + return Ok(()); + } + let repo = + atomic_repository::Repository::open_readonly_wait(root, std::time::Duration::from_secs(10)) + .map_err(|e| { + AgentError::Internal(format!("Cannot check session view restoration: {e}")) + })?; + ensure_view_preparation_complete(&repo) +} + +pub(crate) fn ensure_view_preparation_complete( + repo: &atomic_repository::Repository, +) -> AgentResult<()> { + // The marker belongs to the canonical working copy, not sandbox files. + if repo.is_sandbox() { + return Ok(()); + } + let pending = repo.dot_dir().join(VIEW_PREPARATION_PENDING_FILE); + if pending + .try_exists() + .map_err(|e| AgentError::Internal(format!("Cannot check session view restoration: {e}",)))? + { + return Err(AgentError::Internal( + "Previous session view restoration is incomplete; repair the working copy and resume its original session before starting another session or recording".into(), + )); + } + Ok(()) +} + // A freshly forked view can reuse the same working copy only when the full // visible change/dependency closure is identical. Path-table occupants and // journal baselines cannot prove this. Sandboxes already scope their own view. @@ -119,6 +163,7 @@ fn validate_recording_view( ) -> AgentResult<()> { use atomic_core::pristine::ViewTxnT; use atomic_repository::repository::collect_visible_change_ids_with_deps; + ensure_view_preparation_complete(repo)?; // A validated explicit manifest names each write/deletion deliberately; // it does not infer absent files from the whole working directory. let explicitly_scoped = options @@ -195,6 +240,7 @@ pub fn record_turn( repo_root: &Path, options: &TurnRecordOptions<'_>, ) -> AgentResult { + ensure_view_preparation_complete_at(repo_root)?; let manifest = scope::manifest(options)?; if let Some(files) = &manifest { scope::validate(repo_root, files, options)?; diff --git a/atomic-agent/src/turn/orchestrator/session_start.rs b/atomic-agent/src/turn/orchestrator/session_start.rs index d46ed8f4..c73cbf21 100644 --- a/atomic-agent/src/turn/orchestrator/session_start.rs +++ b/atomic-agent/src/turn/orchestrator/session_start.rs @@ -17,6 +17,7 @@ impl TurnOrchestrator { /// the selected view over unrecorded work, and never defer rendering to Stop. pub(super) fn prepare_session_view(&self, session: &AgentSession) -> AgentResult<()> { use atomic_repository::{status::StatusOptions, Repository}; + use std::io::Write; // Lifecycle-only callers can track sessions outside an initialized VCS. let Ok(dot_dir) = Repository::canonical_dot_dir(&self.repo_root) else { return Ok(()); @@ -24,29 +25,61 @@ impl TurnOrchestrator { if !dot_dir.join("pristine.redb").is_file() { return Ok(()); } - // No transition or database access is needed when the published view - // already matches. This also permits callers holding a read handle. - if std::fs::read_to_string(dot_dir.join("current_view")) - .is_ok_and(|view| view.trim() == session.view_name) - { - return Ok(()); - } let fail = |reason: String| { crate::error::AgentError::Internal(format!( "Cannot prepare view '{}' for session {}: {reason}", session.view_name, session.session_id, )) }; + let pending_path = dot_dir.join(crate::record::VIEW_PREPARATION_PENDING_FILE); + // A matching pointer is sufficient only when no transition is pending. + // A failed materialization may already have published that pointer. + if !pending_path.try_exists().map_err(|e| fail(e.to_string()))? + && std::fs::read_to_string(dot_dir.join("current_view")) + .is_ok_and(|view| view.trim() == session.view_name) + { + return Ok(()); + } let repo = Repository::open_readonly_wait(&self.repo_root, SESSION_DATABASE_WAIT) .map_err(|e| fail(e.to_string()))?; - // A sandbox's view is scoped to its working directory. It must never + // Sandbox files have their own view and must not alter this marker or // publish a switch to the canonical user's working copy. - if repo.is_sandbox() || repo.current_view() == session.view_name { + if repo.is_sandbox() { return Ok(()); } drop(repo); let mut repo = Repository::open_existing_wait(&self.repo_root, SESSION_DATABASE_WAIT) .map_err(|e| fail(e.to_string()))?; + let verify_restored = |repo: &Repository| -> AgentResult<()> { + let status = repo + .status(StatusOptions::default().with_untracked(true)) + .map_err(|e| fail(format!("view restoration is incomplete: {e}")))?; + if !status.is_clean() || status.has_untracked() || status.has_conflicts() { + return Err(fail( + "view restoration is incomplete; files do not match the selected view. Resolve filesystem obstructions, restore missing files, and preserve any other edits before retrying this session. Automatic recording is blocked".into(), + )); + } + Ok(()) + }; + let clear_pending = || -> AgentResult<()> { + std::fs::remove_file(&pending_path).map_err(|e| fail(e.to_string()))?; + sync_view_preparation_dir(&dot_dir).map_err(|e| fail(e.to_string())) + }; + // Re-read after opening the writer. A prior attempt (including another + // process) can publish the pointer and fail before finishing the files. + if pending_path.try_exists().map_err(|e| fail(e.to_string()))? { + let target = std::fs::read_to_string(&pending_path) + .map_err(|e| fail(format!("view restoration is incomplete: {e}")))?; + if target != session.view_name || repo.current_view() != target { + return Err(fail( + "a previous view restoration is incomplete; repair the working copy on its intended view and retry the original session".into(), + )); + } + // Do not blindly materialize again: an operator may have edited + // files while resolving the failure. Verify explicit recovery only. + verify_restored(&repo)?; + return clear_pending(); + } if repo.current_view() == session.view_name { return Ok(()); } @@ -59,9 +92,25 @@ impl TurnOrchestrator { repo.current_view(), ))); } - repo.switch_view(&session.view_name) + // Persist intent before switch_view can publish a pointer or touch + // files. Keep it on every error; recovery must verify the actual files. + let mut pending = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&pending_path) .map_err(|e| fail(e.to_string()))?; - Ok(()) + pending + .write_all(session.view_name.as_bytes()) + .map_err(|e| fail(e.to_string()))?; + pending.sync_all().map_err(|e| fail(e.to_string()))?; + drop(pending); + sync_view_preparation_dir(&dot_dir).map_err(|e| fail(e.to_string()))?; + repo.switch_view(&session.view_name) + .map_err(|e| fail(format!("view restoration is incomplete: {e}")))?; + // The current materializer may warn and skip a failed file while + // returning Ok. Success must be established from the resulting files. + verify_restored(&repo)?; + clear_pending() } /// Handle a SessionStart event. @@ -337,6 +386,7 @@ impl TurnOrchestrator { session.view_name = current; } Ok(mut repo) => { + crate::record::ensure_view_preparation_complete(&repo)?; let current = repo.current_view().to_string(); session.set_parent_view(¤t); @@ -506,6 +556,7 @@ impl TurnOrchestrator { &self.repo_root, SESSION_DATABASE_WAIT, ) { + crate::record::ensure_view_preparation_complete(&repo)?; let current = repo.current_view().to_string(); if repo.is_sandbox() { @@ -604,3 +655,13 @@ impl TurnOrchestrator { } } } + +// Persist creation/removal of the operational marker where directory fsync is +// supported. Its file contents are synced on all platforms before switching. +fn sync_view_preparation_dir(dot_dir: &std::path::Path) -> std::io::Result<()> { + #[cfg(unix)] + std::fs::File::open(dot_dir)?.sync_all()?; + #[cfg(not(unix))] + let _ = dot_dir; + Ok(()) +} diff --git a/atomic-agent/src/turn/orchestrator/tests.rs b/atomic-agent/src/turn/orchestrator/tests.rs index f98ce3af..f96d01ae 100644 --- a/atomic-agent/src/turn/orchestrator/tests.rs +++ b/atomic-agent/src/turn/orchestrator/tests.rs @@ -1529,3 +1529,157 @@ async fn resume_view_still_records_an_intentional_deletion() { "base\n" ); } + +#[tokio::test] +async fn resume_view_failed_write_blocks_retry_and_record_until_repaired() { + let (dir, mut orch, view, inode) = resume_view_fixture().await; + // Empty directories are not reported as untracked files. They can still + // obstruct a tracked file that must be restored from the target closure. + fs::create_dir(dir.path().join("session-only.txt")).unwrap(); + let status = Repository::open_readonly(dir.path()) + .unwrap() + .status(atomic_repository::status::StatusOptions::default()) + .unwrap(); + assert!(status.is_clean() && !status.has_untracked()); + let error = orch + .dispatch(session_start_event("resume-view")) + .await + .unwrap_err(); + assert!(error.to_string().contains("incomplete"), "{error}"); + assert_eq!( + Repository::open_readonly(dir.path()) + .unwrap() + .current_view(), + view + ); + assert!(dir.path().join("session-only.txt").is_dir()); + drop(orch); + + // A fresh process must not accept the now-matching view pointer as proof + // that the failed materialization completed. + let mut orch = make_orchestrator(&dir); + assert!(orch + .dispatch(session_start_event("resume-view")) + .await + .is_err()); + assert!(orch + .dispatch(turn_start_event("resume-view", "retry")) + .await + .is_err()); + for event in [ + session_start_event("new-session"), + turn_start_event("orphan-session", "retry"), + ] { + assert!(orch.dispatch(event).await.is_err()); + assert_eq!( + Repository::open_readonly(dir.path()) + .unwrap() + .current_view(), + view + ); + } + assert!(orch + .dispatch(TurnEvent::new("resume-view", HookType::PreToolUse).with_tool_name("bash")) + .await + .is_err()); + assert!(orch.dispatch(turn_end_event("resume-view")).await.is_err()); + fs::write(dir.path().join("base.txt"), "pending human edit\n").unwrap(); + let session = orch.session_store.load("resume-view").unwrap().unwrap(); + for scope in ["unscoped", "explicit", "empty"] { + let mut event = turn_end_event("resume-view"); + if scope == "empty" { + event = event.with_raw_json(serde_json::json!({"record_files":{}})); + } else if scope == "explicit" { + event = event.with_raw_json(serde_json::json!({"record_files":{ + "base.txt": crate::record::scope::fingerprint(dir.path(), "base.txt").unwrap() + }})); + } + let options = crate::record::TurnRecordOptions { + session: &session, + event: &event, + turn_number: 2, + turn_duration_ms: 0, + prompt: None, + }; + let error = crate::record::record_turn(dir.path(), &options).unwrap_err(); + assert!(error.to_string().contains("incomplete"), "{error}"); + } + assert_eq!( + fs::read_to_string(dir.path().join("base.txt")).unwrap(), + "pending human edit\n" + ); + + // Explicit recovery resolves the obstruction and restores the recorded + // file; it must not silently erase another edit made during recovery. + fs::remove_dir(dir.path().join("session-only.txt")).unwrap(); + fs::write(dir.path().join("session-only.txt"), "keep me\n").unwrap(); + assert!(orch + .dispatch(session_start_event("resume-view")) + .await + .is_err()); + let repo = Repository::open_existing(dir.path()).unwrap(); + repo.record( + atomic_core::change::ChangeHeader::new("preserve recovery edit"), + atomic_repository::RecordOptions::new() + .with_all(true) + .save_to_store(true) + .apply_after_record(true), + ) + .unwrap(); + drop(repo); + orch.dispatch(session_start_event("resume-view")) + .await + .unwrap(); + orch.dispatch(turn_start_event("resume-view", "continue after recovery")) + .await + .unwrap(); + fs::write( + dir.path().join("base.txt"), + "pending human edit\nagent continuation\n", + ) + .unwrap(); + assert!(orch + .dispatch(turn_end_event("resume-view")) + .await + .unwrap() + .was_recorded()); + assert_eq!(resume_file_inode(&dir), inode); + assert_eq!( + fs::read_to_string(dir.path().join("session-only.txt")).unwrap(), + "keep me\n" + ); +} + +#[tokio::test] +async fn resume_view_recovers_completed_materialization_after_interrupted_cleanup() { + let (dir, mut orch, view, inode) = resume_view_fixture().await; + Repository::open_existing(dir.path()) + .unwrap() + .switch_view(&view) + .unwrap(); + // Simulate a process exiting after rendering but before clearing its marker. + let pending = dir + .path() + .join(".atomic") + .join(crate::record::VIEW_PREPARATION_PENDING_FILE); + fs::write(&pending, &view).unwrap(); + assert!(orch + .dispatch(TurnEvent::new("resume-view", HookType::PreToolUse).with_tool_name("bash")) + .await + .is_err()); + orch.dispatch(session_start_event("resume-view")) + .await + .unwrap(); + assert!(!pending.exists()); + assert_eq!(resume_file_inode(&dir), inode); + orch.dispatch(turn_start_event("resume-view", "continue")) + .await + .unwrap(); + orch.dispatch(TurnEvent::new("resume-view", HookType::PreToolUse).with_tool_name("bash")) + .await + .unwrap(); + assert_eq!( + fs::read_to_string(dir.path().join("session-only.txt")).unwrap(), + "keep me\n" + ); +} diff --git a/atomic-agent/src/turn/orchestrator/turn.rs b/atomic-agent/src/turn/orchestrator/turn.rs index 0e80ab9e..7d6f69b7 100644 --- a/atomic-agent/src/turn/orchestrator/turn.rs +++ b/atomic-agent/src/turn/orchestrator/turn.rs @@ -132,6 +132,7 @@ impl TurnOrchestrator { ) -> AgentResult { // Clone so `event` stays mutable for enrichment below while the // id is borrowed throughout this function. + crate::record::ensure_view_preparation_complete_at(&self.repo_root)?; let session_id_owned = event.session_id.clone(); let session_id = session_id_owned.as_str(); let _turn_end_lock = match self.try_turn_end_lock(session_id) { @@ -458,6 +459,9 @@ impl TurnOrchestrator { ) -> AgentResult { let session_id = &event.session_id; + if event.event_type == crate::event::HookType::PreToolUse { + crate::record::ensure_view_preparation_complete_at(&self.repo_root)?; + } let session = self.load_or_create_session(session_id, &event)?; let turn_number = session.turn_count.saturating_add(1); self.commit_hook_event(&event, turn_number)?; From 159b37e9ac0a531acb13b875515b4883c94899aa Mon Sep 17 00:00:00 2001 From: Vincent Date: Sun, 20 Sep 2026 20:15:44 -0400 Subject: [PATCH 3/3] fix(materialize): report failed writes and keep conflicts resolvable --- atomic-agent/src/record/mod.rs | 4 +- .../src/turn/orchestrator/session_start.rs | 8 +- atomic-agent/src/turn/orchestrator/tests.rs | 93 +++++++++++++++++++ .../src/repository/materialize.rs | 12 ++- 4 files changed, 111 insertions(+), 6 deletions(-) diff --git a/atomic-agent/src/record/mod.rs b/atomic-agent/src/record/mod.rs index f9171dd0..b5dfbf8e 100644 --- a/atomic-agent/src/record/mod.rs +++ b/atomic-agent/src/record/mod.rs @@ -110,8 +110,8 @@ fn build_turn_header( .build() } -// Operational completion marker only: it names a target view, never paths, -// inode ownership, inverse changes, or file-history baselines. +// Marks a session view restore that has not completed. Contains the target +// view; removed only after the restored working-copy files are verified. pub(crate) const VIEW_PREPARATION_PENDING_FILE: &str = "agent-view-prepare.pending"; // Hooks that have not opened a repository yet only pay for a database read diff --git a/atomic-agent/src/turn/orchestrator/session_start.rs b/atomic-agent/src/turn/orchestrator/session_start.rs index c73cbf21..f59184ec 100644 --- a/atomic-agent/src/turn/orchestrator/session_start.rs +++ b/atomic-agent/src/turn/orchestrator/session_start.rs @@ -54,7 +54,9 @@ impl TurnOrchestrator { let status = repo .status(StatusOptions::default().with_untracked(true)) .map_err(|e| fail(format!("view restoration is incomplete: {e}")))?; - if !status.is_clean() || status.has_untracked() || status.has_conflicts() { + // A rendered conflict is valid view output. Allow tools to resolve it; + // the repository still refuses to record unresolved conflict markers. + if !status.is_clean() || status.has_untracked() { return Err(fail( "view restoration is incomplete; files do not match the selected view. Resolve filesystem obstructions, restore missing files, and preserve any other edits before retrying this session. Automatic recording is blocked".into(), )); @@ -107,8 +109,8 @@ impl TurnOrchestrator { sync_view_preparation_dir(&dot_dir).map_err(|e| fail(e.to_string()))?; repo.switch_view(&session.view_name) .map_err(|e| fail(format!("view restoration is incomplete: {e}")))?; - // The current materializer may warn and skip a failed file while - // returning Ok. Success must be established from the resulting files. + // Verify the resulting working copy before clearing the durable marker, + // including after a later retry of an interrupted transition. verify_restored(&repo)?; clear_pending() } diff --git a/atomic-agent/src/turn/orchestrator/tests.rs b/atomic-agent/src/turn/orchestrator/tests.rs index f96d01ae..0b0e9568 100644 --- a/atomic-agent/src/turn/orchestrator/tests.rs +++ b/atomic-agent/src/turn/orchestrator/tests.rs @@ -1683,3 +1683,96 @@ async fn resume_view_recovers_completed_materialization_after_interrupted_cleanu "keep me\n" ); } + +#[tokio::test] +async fn resume_view_allows_materialized_conflicts_to_be_resolved() { + let dir = TempDir::new().unwrap(); + let mut repo = Repository::init(dir.path()).unwrap(); + let path = dir.path().join("conflict.txt"); + fs::write(&path, "line1\nline2\nline3\nline4\nline5\n").unwrap(); + repo.add( + "conflict.txt", + atomic_repository::TrackingOptions::default(), + ) + .unwrap(); + let record = |repo: &Repository, message: &str| { + repo.record( + atomic_core::change::ChangeHeader::new(message), + atomic_repository::RecordOptions::new() + .with_all(true) + .save_to_store(true) + .apply_after_record(true), + ) + .unwrap(); + }; + record(&repo, "base"); + repo.create_view_from("feature-a", "dev").unwrap(); + repo.create_view_from("feature-b", "dev").unwrap(); + repo.switch_view("feature-a").unwrap(); + fs::write(&path, "line1\nAAA\nline2\nline3\nline4\nline5\n").unwrap(); + record(&repo, "edit A"); + repo.switch_view("feature-b").unwrap(); + fs::write(&path, "line1\nBBB\nline2\nline3\nline4\nline5\n").unwrap(); + record(&repo, "edit B"); + repo.insert_from_view(atomic_repository::apply::CrossViewInsertOptions::new( + "feature-a", + "feature-b", + )) + .unwrap(); + repo.materialize().unwrap(); + assert!(fs::read_to_string(&path).unwrap().contains(">>>>>>>")); + repo.switch_view("dev").unwrap(); + drop(repo); + + let mut orch = make_orchestrator(&dir); + let mut session = AgentSession::new("conflict-session", "opencode", "OpenCode"); + session.view_name = "feature-b".into(); + session.set_parent_view("dev"); + orch.session_store.save(&session).unwrap(); + orch.dispatch(session_start_event("conflict-session")) + .await + .unwrap(); + let rendered = fs::read_to_string(&path).unwrap(); + assert!(rendered.contains("AAA") && rendered.contains("BBB") && rendered.contains(">>>>>>>")); + assert!(Repository::open_readonly(dir.path()) + .unwrap() + .status(atomic_repository::status::StatusOptions::default()) + .unwrap() + .has_conflicts()); + assert!(!dir + .path() + .join(".atomic") + .join(crate::record::VIEW_PREPARATION_PENDING_FILE) + .exists()); + orch.dispatch(turn_start_event("conflict-session", "resolve the conflict")) + .await + .unwrap(); + orch.dispatch(TurnEvent::new("conflict-session", HookType::PreToolUse).with_tool_name("edit")) + .await + .unwrap(); + fs::write(&path, "line1\nAAA\nBBB\nline2\nline3\nline4\nline5\n").unwrap(); + assert!(orch + .dispatch(turn_end_event("conflict-session")) + .await + .unwrap() + .was_recorded()); + let status = Repository::open_readonly(dir.path()) + .unwrap() + .status(atomic_repository::status::StatusOptions::default()) + .unwrap(); + assert!(status.is_clean() && !status.has_conflicts()); +} + +#[tokio::test] +async fn resume_view_materializer_reports_a_failed_file_write() { + let (dir, _orch, view, _) = resume_view_fixture().await; + fs::create_dir(dir.path().join("session-only.txt")).unwrap(); + let mut repo = Repository::open_existing(dir.path()).unwrap(); + let error = repo.switch_view(&view).unwrap_err(); + assert!(error.to_string().contains("session-only.txt"), "{error}"); + assert!(dir.path().join("session-only.txt").is_dir()); + assert_eq!( + fs::read_to_string(dir.path().join("base.txt")).unwrap(), + "base\n" + ); +} diff --git a/atomic-repository/src/repository/materialize.rs b/atomic-repository/src/repository/materialize.rs index 03c87320..fc0aa83e 100644 --- a/atomic-repository/src/repository/materialize.rs +++ b/atomic-repository/src/repository/materialize.rs @@ -811,6 +811,8 @@ impl Repository { let mut conflicts_by_path: std::collections::HashMap = std::collections::HashMap::new(); + let mut failed_files = 0usize; + let mut first_file_error = None; for file_result in file_results { match file_result { Ok(Some((path, bytes, content_hash, was_written, marker_line))) => { @@ -849,7 +851,8 @@ impl Repository { } Err(e) => { log::warn!("Parallel materialize failed for file: {}", e); - result.files_skipped += 1; + failed_files += 1; + first_file_error.get_or_insert(e); } } } @@ -876,6 +879,13 @@ impl Repository { log::warn!("failed to persist conflict state: {}", e); } + // Preserve index/conflict information for files that did finish, but + // never report a partially restored working copy as a successful render. + if let Some(error) = first_file_error { + return Err(RepositoryError::Output(format!( + "Failed to materialize {failed_files} file(s): {error}" + ))); + } Ok(result) }