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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions atomic-agent/src/record/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,14 +140,19 @@ pub fn record_turn(
// Step 1: Open the repository read-only for the initial status check.
// This avoids blocking on the redb write lock — we only need read access
// to decide whether there's work to do and which files are untracked.
let repo = atomic_repository::Repository::open_readonly(repo_root).map_err(|e| {
let mut repo = atomic_repository::Repository::open_readonly(repo_root).map_err(|e| {
AgentError::RecordFailed {
session_id: options.session.session_id.clone(),
turn_number: options.turn_number,
reason: format!("Failed to open repository (readonly): {}", e),
}
})?;

// `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.
repo.set_current_view_in_memory(&options.session.view_name);

// Step 2: Status — find out what the agent changed.
// Include untracked files because agent turns commonly create new source,
// config, and test files. Those must be auto-added before recording so the
Expand Down Expand Up @@ -194,14 +199,34 @@ pub fn record_turn(
// skips the table-init `begin_write()` that `open()` does — the tables
// already exist and that write lock is the primary cause of hook hangs
// when another process holds a transaction.
let repo = atomic_repository::Repository::open_existing(repo_root).map_err(|e| {
let mut repo = atomic_repository::Repository::open_existing(repo_root).map_err(|e| {
AgentError::RecordFailed {
session_id: options.session.session_id.clone(),
turn_number: options.turn_number,
reason: format!("Failed to open repository for recording: {}", e),
}
})?;

// 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.
match repo.set_current_view(&options.session.view_name) {
Ok(()) => {}
Err(atomic_repository::RepositoryError::ViewNotFound { .. }) => {
log::debug!(
"session view '{}' not yet created; first-turn apply will create it",
options.session.view_name
);
}
Err(e) => {
return Err(AgentError::RecordFailed {
session_id: options.session.session_id.clone(),
turn_number: options.turn_number,
reason: format!("Failed to align current view before record: {}", e),
});
}
}

if !untracked_paths.is_empty() {
log::info!(
"Adding {} untracked file{} created by agent",
Expand Down
114 changes: 114 additions & 0 deletions atomic-agent/tests/record_view_mismatch_regression.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
//! Regression test for the `record_turn` detection/apply view mismatch.
//!
//! `status()` reads the repository current view, while `record_turn` records to
//! `session.view_name`. These tests use the default random session view so
//! direct callers that skip session-start exercise the mismatch.

use atomic_agent::event::{HookType, TurnEvent};
use atomic_agent::record::{record_turn, TurnRecordOptions};
use atomic_agent::turn::AgentSession;

use atomic_core::types::Base32;
use atomic_repository::Repository;

/// Keep the default random view_name; do not pin it to `dev`.
fn default_session() -> AgentSession {
let mut s = AgentSession::new("regress-sess", "opencode", "OpenCode");
s.set_model_info("anthropic", "claude-opus-4");
s
}

fn options<'a>(
session: &'a AgentSession,
event: &'a TurnEvent,
turn_number: u32,
prompt: &str,
) -> TurnRecordOptions<'a> {
TurnRecordOptions {
session,
event,
turn_number,
turn_duration_ms: 1000,
prompt: Some(prompt.to_string()),
}
}

/// A direct caller must be able to record a create turn followed by a modify turn.
#[test]
fn two_turns_with_default_random_view_both_record() {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
Repository::init(root).expect("init disposable repo");

let session = default_session();
assert_ne!(
session.view_name, "dev",
"regression precondition: AgentSession::new must use a random (non-default) view_name"
);

std::fs::write(root.join("login.rs"), "fn attach_pdf() {}\n").expect("write new file");
let event1 = TurnEvent::new("regress-sess", HookType::TurnEnd);
let first = record_turn(root, &options(&session, &event1, 1, "create login.rs"))
.expect("turn 1 (new file) should record");
assert!(
!first.hash.to_base32().is_empty(),
"turn 1 must yield a hash"
);

// Keep the sizes different so this test does not depend on mtime granularity.
let turn1_body = "fn attach_pdf() {}\n";
let turn2_body = "fn attach_pdf() {\n // Firefox + Safari support\n}\n";
assert_ne!(
turn1_body.len(),
turn2_body.len(),
"turn 2 must change the file size so detection never relies on mtime granularity"
);
std::fs::write(root.join("login.rs"), turn2_body).expect("modify tracked file");
let event2 = TurnEvent::new("regress-sess", HookType::TurnEnd);
let second = record_turn(root, &options(&session, &event2, 2, "fix pdf upload"))
.expect("turn 2 (modified tracked file) should record — regression: was EmptyTurn");

assert!(
!second.hash.to_base32().is_empty(),
"turn 2 must yield a hash"
);
assert_ne!(
first.hash.to_base32(),
second.hash.to_base32(),
"the modification must produce a change distinct from the creation"
);
}

/// Deleting the last file on the session view must also produce a recorded turn.
#[test]
fn delete_last_session_file_records_instead_of_emptyturn() {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
Repository::init(root).expect("init disposable repo");

let session = default_session();
assert_ne!(
session.view_name, "dev",
"regression precondition: session must use a random (non-default) view_name"
);

std::fs::write(root.join("only.rs"), "fn only() {}\n").expect("write file");
let event1 = TurnEvent::new("regress-sess", HookType::TurnEnd);
let first = record_turn(root, &options(&session, &event1, 1, "create only.rs"))
.expect("turn 1 (new file) should record");

std::fs::remove_file(root.join("only.rs")).expect("delete the only file");
let event2 = TurnEvent::new("regress-sess", HookType::TurnEnd);
let second = record_turn(root, &options(&session, &event2, 2, "delete only.rs"))
.expect("turn 2 (delete last session file) should record — regression: was EmptyTurn");

assert!(
!second.hash.to_base32().is_empty(),
"the deletion must produce a change hash"
);
assert_ne!(
first.hash.to_base32(),
second.hash.to_base32(),
"the deletion must be a change distinct from the creation"
);
}
9 changes: 9 additions & 0 deletions atomic-repository/src/repository/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,15 @@ default = "{}"
Ok(())
}

/// Set the current view on this handle only.
///
/// This does not validate the view or persist `.atomic/current_view`. It is
/// intended for read-only handles that need `status()` to read another view.
#[inline]
pub fn set_current_view_in_memory(&mut self, view: &str) {
self.current_view = view.to_string();
}

// ── Internal helpers ────────────────────────────────────────────────

/// Get a reference to the pristine database.
Expand Down
Loading