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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 108 additions & 0 deletions atomic-agent/src/record/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,107 @@ fn build_turn_header(
.build()
}

// 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
// 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.
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;
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
.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, &current)
.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.
Expand Down Expand Up @@ -139,6 +240,7 @@ pub fn record_turn(
repo_root: &Path,
options: &TurnRecordOptions<'_>,
) -> AgentResult<TurnRecordOutcome> {
ensure_view_preparation_complete_at(repo_root)?;
let manifest = scope::manifest(options)?;
if let Some(files) = &manifest {
scope::validate(repo_root, files, options)?;
Expand All @@ -162,6 +264,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.
Expand Down Expand Up @@ -225,6 +329,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.
Expand Down
36 changes: 24 additions & 12 deletions atomic-agent/src/record/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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");
Expand All @@ -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.
{
Expand Down
116 changes: 116 additions & 0 deletions atomic-agent/src/turn/orchestrator/session_start.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,109 @@ 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};
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(());
};
if !dot_dir.join("pristine.redb").is_file() {
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()))?;
// 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() {
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}")))?;
// 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(),
));
}
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(());
}
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(),
)));
}
// 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()))?;
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}")))?;
// Verify the resulting working copy before clearing the durable marker,
// including after a later retry of an interrupted transition.
verify_restored(&repo)?;
clear_pending()
}

/// Handle a SessionStart event.
///
/// Creates a new session or re-enters an ended session. Creates the
Expand Down Expand Up @@ -41,6 +144,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,
Expand Down Expand Up @@ -284,6 +388,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(&current);

Expand Down Expand Up @@ -453,6 +558,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() {
Expand Down Expand Up @@ -551,3 +657,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(())
}
Loading
Loading