use super::*;
use tokio::sync::broadcast;
use tokio::sync::mpsc;
use tokio::time::{Duration, timeout};
fn notify_channel() -> (NotifySender, mpsc::UnboundedReceiver<serde_json::Value>) {
mpsc::unbounded_channel()
}
async fn next_event_for(
rx: &mut broadcast::Receiver<SessionEventEnvelope>,
session_id: &str,
) -> SessionEventEnvelope {
timeout(Duration::from_secs(2), async {
loop {
let envelope = rx.recv().await.expect("event bus closed unexpectedly");
if envelope.session_id == session_id {
return envelope;
}
}
})
.await
.expect("timed out waiting for an event on this session")
}
#[tokio::test]
async fn create_publishes_started_and_status_events() {
let registry = SessionRegistry::new();
let mut events = crate::events::subscribe();
let session = registry.create("do the thing".to_string(), None, Some("proj".to_string()));
assert_eq!(session.status, SessionStatus::Running);
let first = next_event_for(&mut events, &session.id).await;
assert_eq!(first.seq, 1);
assert_eq!(first.kind, "session_started");
assert!(matches!(first.event, Event::SessionStarted { project, .. } if project == "proj"));
let second = next_event_for(&mut events, &session.id).await;
assert_eq!(second.seq, 2);
assert!(
matches!(second.event, Event::SessionStatusChanged { status, .. } if status == "running")
);
}
#[tokio::test]
async fn list_returns_every_created_session() {
let registry = SessionRegistry::new();
registry.create("a".to_string(), None, None);
registry.create("b".to_string(), None, None);
assert_eq!(registry.list().len(), 2);
}
#[tokio::test]
async fn status_returns_not_found_for_unknown_id() {
let registry = SessionRegistry::new();
let err = registry.status("does-not-exist").unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn send_publishes_input_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let mut events = crate::events::subscribe();
registry.send(&session.id, "hello").unwrap();
let envelope = next_event_for(&mut events, &session.id).await;
assert_eq!(envelope.seq, 3); assert!(matches!(envelope.event, Event::SessionInput { input, .. } if input == "hello"));
}
#[tokio::test]
async fn send_unknown_session_errors() {
let registry = SessionRegistry::new();
let err = registry.send("nope", "hi").unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn cancel_transitions_to_cancelled_and_publishes() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let mut events = crate::events::subscribe();
let cancelled = registry.cancel(&session.id).unwrap();
assert_eq!(cancelled.status, SessionStatus::Cancelled);
let status_changed = next_event_for(&mut events, &session.id).await;
assert!(
matches!(status_changed.event, Event::SessionStatusChanged { status, .. } if status == "cancelled")
);
let cancelled_event = next_event_for(&mut events, &session.id).await;
assert!(matches!(
cancelled_event.event,
Event::SessionCancelled { .. }
));
assert!(cancelled_event.seq > status_changed.seq);
let done = next_event_for(&mut events, &session.id).await;
assert!(matches!(done.event, Event::SessionDone { status, .. } if status == "cancelled"));
assert!(done.seq > cancelled_event.seq);
let again = registry.cancel(&session.id).unwrap();
assert_eq!(again.status, SessionStatus::Cancelled);
}
#[tokio::test]
async fn cancel_unknown_session_errors() {
let registry = SessionRegistry::new();
let err = registry.cancel("nope").unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn attach_returns_ring_buffer_replay() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
registry.send(&session.id, "one").unwrap();
let (tx, _rx) = notify_channel();
let replay = registry.attach(&session.id, Uuid::new_v4(), tx).unwrap();
assert_eq!(replay.len(), 3);
let seqs: Vec<u64> = replay.iter().map(|e| e.seq).collect();
assert_eq!(seqs, vec![1, 2, 3]);
assert!(
matches!(&replay.last().unwrap().event, Event::SessionInput { input, .. } if input == "one")
);
}
#[tokio::test]
async fn attach_forwards_live_events_until_detach() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let connection_id = Uuid::new_v4();
let (tx, mut rx) = notify_channel();
registry.attach(&session.id, connection_id, tx).unwrap();
registry.send(&session.id, "live").unwrap();
let notification = timeout(Duration::from_secs(2), rx.recv())
.await
.expect("forwarder must deliver the live event")
.expect("channel must still be open");
assert_eq!(notification["method"], "session.event");
assert_eq!(notification["params"]["session_id"], session.id);
assert_eq!(notification["params"]["seq"], 3);
assert_eq!(notification["params"]["kind"], "session_input");
assert_eq!(notification["params"]["event"]["type"], "session_input");
assert_eq!(notification["params"]["event"]["input"], "live");
assert!(notification["params"]["at"].is_string());
registry.detach(&session.id, connection_id).unwrap();
tokio::time::sleep(Duration::from_millis(50)).await;
registry.send(&session.id, "after-detach").unwrap();
match timeout(Duration::from_millis(300), rx.recv()).await {
Err(_) => {} Ok(None) => {} Ok(Some(v)) => panic!("no event should arrive after detach, got {v:?}"),
}
}
#[tokio::test]
async fn attach_replay_then_live_seq_is_contiguous() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
registry.send(&session.id, "before-attach").unwrap();
let (tx, mut rx) = notify_channel();
let replay = registry.attach(&session.id, Uuid::new_v4(), tx).unwrap();
let last_replay_seq = replay.last().unwrap().seq;
registry.send(&session.id, "after-attach").unwrap();
let notification = timeout(Duration::from_secs(2), rx.recv())
.await
.expect("forwarder must deliver the live event")
.expect("channel must still be open");
let live_seq = notification["params"]["seq"].as_u64().unwrap();
assert_eq!(
live_seq,
last_replay_seq + 1,
"no gap and no duplicate between replay and live"
);
for (i, envelope) in replay.iter().enumerate() {
assert_eq!(envelope.seq, (i as u64) + 1);
}
}
#[tokio::test]
async fn attach_unknown_session_errors() {
let registry = SessionRegistry::new();
let (tx, _rx) = notify_channel();
let err = registry.attach("nope", Uuid::new_v4(), tx).unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn detach_without_prior_attach_is_a_noop() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
registry.detach(&session.id, Uuid::new_v4()).unwrap();
}
#[tokio::test]
async fn detach_unknown_session_errors() {
let registry = SessionRegistry::new();
let err = registry.detach("nope", Uuid::new_v4()).unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn replay_returns_ring_buffer_without_attaching() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let replay = registry.replay(&session.id).unwrap();
assert_eq!(replay.len(), 2); }
#[tokio::test]
async fn ring_buffer_drops_oldest_when_full() {
let registry = SessionRegistry::with_capacity(2);
let session = registry.create("t".to_string(), None, None);
registry.send(&session.id, "evicts-started").unwrap();
let replay = registry.replay(&session.id).unwrap();
assert_eq!(replay.len(), 2);
assert!(matches!(
replay.first().unwrap().event,
Event::SessionStatusChanged { .. }
));
assert!(
matches!(&replay.last().unwrap().event, Event::SessionInput { input, .. } if input == "evicts-started")
);
let seqs: Vec<u64> = replay.iter().map(|e| e.seq).collect();
assert_eq!(seqs, vec![2, 3]);
}
#[tokio::test]
async fn record_tool_started_publishes_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let mut events = crate::events::subscribe();
registry
.record_tool_started(&session.id, "bash", "call-1", "ls -la")
.unwrap();
let envelope = next_event_for(&mut events, &session.id).await;
assert_eq!(envelope.kind, "tool_started");
assert!(matches!(
envelope.event,
Event::ToolStarted { tool, call_id, args_preview, .. }
if tool == "bash" && call_id == "call-1" && args_preview == "ls -la"
));
}
#[tokio::test]
async fn record_tool_finished_publishes_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let mut events = crate::events::subscribe();
registry
.record_tool_finished(&session.id, "bash", "call-1", true, "done")
.unwrap();
let envelope = next_event_for(&mut events, &session.id).await;
assert_eq!(envelope.kind, "tool_finished");
assert!(matches!(
envelope.event,
Event::ToolFinished { success, result_preview, .. } if success && result_preview == "done"
));
}
#[tokio::test]
async fn record_tool_error_publishes_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let mut events = crate::events::subscribe();
registry
.record_tool_error(&session.id, "bash", "call-1", "timed out")
.unwrap();
let envelope = next_event_for(&mut events, &session.id).await;
assert_eq!(envelope.kind, "tool_error");
assert!(matches!(envelope.event, Event::ToolError { error, .. } if error == "timed out"));
}
#[tokio::test]
async fn record_log_publishes_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let mut events = crate::events::subscribe();
registry
.record_log(&session.id, "warn", "disk almost full")
.unwrap();
let envelope = next_event_for(&mut events, &session.id).await;
assert_eq!(envelope.kind, "log");
assert!(
matches!(envelope.event, Event::Log { level, message, .. } if level == "warn" && message == "disk almost full")
);
}
#[tokio::test]
async fn record_progress_publishes_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let mut events = crate::events::subscribe();
registry
.record_progress(&session.id, "indexing", Some(0.5))
.unwrap();
let envelope = next_event_for(&mut events, &session.id).await;
assert_eq!(envelope.kind, "progress");
assert!(matches!(envelope.event, Event::Progress { percent: Some(p), .. } if p == 0.5));
}
#[tokio::test]
async fn record_message_publishes_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let mut events = crate::events::subscribe();
registry.record_message(&session.id, "hello world").unwrap();
let envelope = next_event_for(&mut events, &session.id).await;
assert_eq!(envelope.kind, "message");
assert!(matches!(envelope.event, Event::Message { text, .. } if text == "hello world"));
}
#[tokio::test]
async fn record_plumbing_methods_reject_unknown_session() {
let registry = SessionRegistry::new();
assert_eq!(
registry
.record_tool_started("nope", "t", "c", "a")
.unwrap_err()
.code,
-32007
);
assert_eq!(
registry
.record_tool_finished("nope", "t", "c", true, "r")
.unwrap_err()
.code,
-32007
);
assert_eq!(
registry
.record_tool_error("nope", "t", "c", "e")
.unwrap_err()
.code,
-32007
);
assert_eq!(
registry.record_log("nope", "info", "m").unwrap_err().code,
-32007
);
assert_eq!(
registry
.record_progress("nope", "m", None)
.unwrap_err()
.code,
-32007
);
assert_eq!(
registry.record_message("nope", "m").unwrap_err().code,
-32007
);
}
#[tokio::test]
async fn begin_execution_unknown_session_errors() {
let registry = SessionRegistry::new();
let err = registry.begin_execution("nope").unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn begin_execution_rejects_terminal_session() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
registry.cancel(&session.id).unwrap();
let err = registry.begin_execution(&session.id).unwrap_err();
assert_eq!(
err.code, -32003,
"must be invalid_argument, not session_not_found"
);
}
#[tokio::test]
async fn begin_execution_rejects_second_overlapping_run() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let _first = registry.begin_execution(&session.id).unwrap();
let err = registry.begin_execution(&session.id).unwrap_err();
assert_eq!(err.code, -32003);
registry.finish_execution(&session.id);
assert!(
registry.begin_execution(&session.id).is_ok(),
"a new execution must be startable once the prior one finished"
);
}
#[tokio::test]
async fn request_cancel_returns_false_when_idle() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
assert!(!registry.request_cancel(&session.id).unwrap());
}
#[tokio::test]
async fn request_cancel_sets_flag_when_executing() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
assert!(!registry.is_executing(&session.id));
let cancel = registry.begin_execution(&session.id).unwrap();
assert!(registry.is_executing(&session.id));
assert!(!cancel.load(std::sync::atomic::Ordering::Relaxed));
assert!(registry.request_cancel(&session.id).unwrap());
assert!(
cancel.load(std::sync::atomic::Ordering::Relaxed),
"the SAME flag must observe the request"
);
}
#[tokio::test]
async fn request_cancel_unknown_session_errors() {
let registry = SessionRegistry::new();
assert_eq!(registry.request_cancel("nope").unwrap_err().code, -32007);
}
#[tokio::test]
async fn begin_execution_resumes_a_finished_session() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let _first = registry.begin_execution(&session.id).unwrap();
registry.finish_execution(&session.id);
registry
.finish(&session.id, SessionStatus::Finished)
.unwrap();
assert_eq!(
registry.status(&session.id).unwrap().status,
SessionStatus::Finished
);
let mut events = crate::events::subscribe();
assert!(
registry.begin_execution(&session.id).is_ok(),
"a Finished session must be resumable for its next task.run"
);
assert_eq!(
registry.status(&session.id).unwrap().status,
SessionStatus::Running,
"resuming must transition the session back to Running"
);
let envelope = next_event_for(&mut events, &session.id).await;
assert!(
matches!(envelope.event, Event::SessionStatusChanged { status, .. } if status == "running"),
"resuming must publish the SAME SessionStatusChanged event other transitions do"
);
}
#[tokio::test]
async fn begin_execution_still_rejects_cancelled_failed_and_deadline_exceeded() {
let registry = SessionRegistry::new();
let cancelled = registry.create("t".to_string(), None, None);
registry.cancel(&cancelled.id).unwrap();
assert_eq!(
registry.begin_execution(&cancelled.id).unwrap_err().code,
-32003
);
let failed = registry.create("t".to_string(), None, None);
registry.finish(&failed.id, SessionStatus::Failed).unwrap();
assert_eq!(
registry.begin_execution(&failed.id).unwrap_err().code,
-32003
);
let deadline = registry.create("t".to_string(), None, None);
registry
.finish(&deadline.id, SessionStatus::DeadlineExceeded)
.unwrap();
assert_eq!(
registry.begin_execution(&deadline.id).unwrap_err().code,
-32003
);
}
#[tokio::test]
async fn begin_pm_transcript_seeds_on_first_call() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let transcript = registry
.begin_pm_transcript(&session.id, "you are the pm", "first task")
.unwrap();
let messages = transcript.messages();
assert_eq!(messages.len(), 2);
assert_eq!(messages[0].role, "system");
assert_eq!(messages[0].content.as_deref(), Some("you are the pm"));
assert_eq!(messages[1].role, "user");
assert_eq!(messages[1].content.as_deref(), Some("first task"));
}
#[tokio::test]
async fn begin_pm_transcript_appends_on_second_call() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let mut transcript = registry
.begin_pm_transcript(&session.id, "you are the pm", "first task")
.unwrap();
transcript.push_assistant(Some("first answer".into()), &[]);
registry.store_pm_transcript(&session.id, transcript);
let continued = registry
.begin_pm_transcript(&session.id, "a DIFFERENT system prompt", "second task")
.unwrap();
let messages = continued.messages();
assert_eq!(messages.len(), 4, "system, user, assistant, new user");
assert_eq!(messages[0].role, "system");
assert_eq!(
messages[0].content.as_deref(),
Some("you are the pm"),
"the ORIGINAL seed's system message must stay authoritative, not the second call's"
);
assert_eq!(messages[1].content.as_deref(), Some("first task"));
assert_eq!(messages[2].role, "assistant");
assert_eq!(messages[2].content.as_deref(), Some("first answer"));
assert_eq!(messages[3].role, "user");
assert_eq!(messages[3].content.as_deref(), Some("second task"));
assert_eq!(
messages.iter().filter(|m| m.role == "system").count(),
1,
"must never end up with two system messages across runs"
);
}
#[tokio::test]
async fn begin_pm_transcript_unknown_session_errors() {
let registry = SessionRegistry::new();
let err = registry
.begin_pm_transcript("nope", "sys", "task")
.unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn memory_sink_for_reuses_the_same_sink_across_calls() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let project_dir = tempfile::TempDir::new().unwrap();
let first = registry
.memory_sink_for(&session.id, project_dir.path())
.expect("first call constructs a sink");
let second = registry
.memory_sink_for(&session.id, project_dir.path())
.expect("second call reuses the sink");
assert!(
Arc::ptr_eq(&first, &second),
"memory_sink_for must return the SAME Arc across calls on one session"
);
}
#[tokio::test]
async fn memory_sink_for_unknown_session_returns_none() {
let registry = SessionRegistry::new();
let project_dir = tempfile::TempDir::new().unwrap();
assert!(
registry
.memory_sink_for("nope", project_dir.path())
.is_none()
);
}
#[tokio::test]
async fn set_run_outcome_stores_transcript_and_usage() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let turns = vec![crate::run_task::TurnRecord {
role: "pm".to_string(),
model: "openai/gpt-4o-mini".to_string(),
text: "done".to_string(),
tool_calls: vec![],
ran_test_command: false,
usage: crate::perf::TokenUsage::new(10, 5, 0, 0),
}];
registry.set_run_outcome(
&session.id,
turns.clone(),
crate::perf::TokenUsage::new(10, 5, 0, 0),
Some(0.01),
);
let stored = registry.get_transcript(&session.id).unwrap();
assert_eq!(stored.turns, turns);
assert_eq!(stored.usage, crate::perf::TokenUsage::new(10, 5, 0, 0));
assert_eq!(stored.cost_usd, Some(0.01));
registry.set_run_outcome("nope", turns, crate::perf::TokenUsage::default(), None);
}
#[tokio::test]
async fn set_run_outcome_accumulates_across_two_calls() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let run_one_turn = crate::run_task::TurnRecord {
role: "pm".to_string(),
model: "openai/gpt-4o-mini".to_string(),
text: "run one".to_string(),
tool_calls: vec![],
ran_test_command: false,
usage: crate::perf::TokenUsage::new(10, 5, 0, 0),
};
registry.set_run_outcome(
&session.id,
vec![run_one_turn.clone()],
crate::perf::TokenUsage::new(10, 5, 0, 0),
Some(0.01),
);
let run_two_turn = crate::run_task::TurnRecord {
role: "pm".to_string(),
model: "openai/gpt-4o-mini".to_string(),
text: "run two".to_string(),
tool_calls: vec![],
ran_test_command: false,
usage: crate::perf::TokenUsage::new(20, 8, 0, 0),
};
registry.set_run_outcome(
&session.id,
vec![run_two_turn.clone()],
crate::perf::TokenUsage::new(20, 8, 0, 0),
Some(0.02),
);
let stored = registry.get_transcript(&session.id).unwrap();
assert_eq!(
stored.turns,
vec![run_one_turn, run_two_turn],
"both runs' turns must be present, in order, not just the last run's"
);
assert_eq!(
stored.usage,
crate::perf::TokenUsage::new(30, 13, 0, 0),
"usage must be the SUM of both runs, not the last run's alone"
);
assert_eq!(
stored.cost_usd,
Some(0.03),
"cost must be the SUM of both runs' cost"
);
}
#[tokio::test]
async fn get_transcript_on_never_run_session_is_empty() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let transcript = registry.get_transcript(&session.id).unwrap();
assert_eq!(transcript.session_id, session.id);
assert!(transcript.turns.is_empty());
assert_eq!(transcript.usage, crate::perf::TokenUsage::default());
assert_eq!(transcript.cost_usd, None);
assert_eq!(transcript.mode, None);
}
#[tokio::test]
async fn get_transcript_unknown_session_errors() {
let registry = SessionRegistry::new();
let err = registry.get_transcript("nope").unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn get_transcript_reports_compaction_events() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let mut transcript = registry
.begin_pm_transcript(&session.id, "you are the pm", "first task")
.unwrap();
transcript.record_threshold_compaction();
transcript.record_threshold_compaction();
registry.store_pm_transcript(&session.id, transcript);
let stored = registry.get_transcript(&session.id).unwrap();
assert_eq!(stored.compaction_events, 2);
}
#[tokio::test]
async fn set_mode_stores_on_session() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
assert_eq!(session.mode, None, "a fresh session has no mode yet");
registry
.set_mode(&session.id, crate::mode::HarnessMode::Parity)
.unwrap();
let status = registry.status(&session.id).unwrap();
assert_eq!(status.mode, Some(crate::mode::HarnessMode::Parity));
let transcript = registry.get_transcript(&session.id).unwrap();
assert_eq!(transcript.mode, Some(crate::mode::HarnessMode::Parity));
}
#[tokio::test]
async fn set_mode_unknown_session_errors() {
let registry = SessionRegistry::new();
let err = registry
.set_mode("nope", crate::mode::HarnessMode::DailyDriver)
.unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn shutdown_executions_awaits_cancelled_tasks() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let cancel = registry.begin_execution(&session.id).unwrap();
let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
let done_clone = done.clone();
let handle = tokio::spawn(async move {
while !cancel.load(std::sync::atomic::Ordering::Relaxed) {
tokio::time::sleep(Duration::from_millis(5)).await;
}
done_clone.store(true, std::sync::atomic::Ordering::Relaxed);
});
registry.attach_execution_handle(&session.id, handle);
registry.shutdown_executions(Duration::from_secs(2)).await;
assert!(
done.load(std::sync::atomic::Ordering::Relaxed),
"the task must have observed cancellation and finished"
);
}
#[tokio::test]
async fn finish_transitions_and_publishes_session_done() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let mut events = crate::events::subscribe();
let finished = registry
.finish(&session.id, SessionStatus::Finished)
.unwrap();
assert_eq!(finished.status, SessionStatus::Finished);
let status_changed = next_event_for(&mut events, &session.id).await;
assert!(
matches!(status_changed.event, Event::SessionStatusChanged { status, .. } if status == "finished")
);
let done = next_event_for(&mut events, &session.id).await;
assert!(matches!(done.event, Event::SessionDone { status, .. } if status == "finished"));
assert!(done.seq > status_changed.seq);
}
#[tokio::test]
async fn finish_is_idempotent_on_terminal_session() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
registry
.finish(&session.id, SessionStatus::Finished)
.unwrap();
let again = registry.finish(&session.id, SessionStatus::Failed).unwrap();
assert_eq!(
again.status,
SessionStatus::Finished,
"must not overwrite an existing terminal status"
);
}
#[tokio::test]
async fn finish_unknown_session_errors() {
let registry = SessionRegistry::new();
let err = registry
.finish("nope", SessionStatus::Finished)
.unwrap_err();
assert_eq!(err.code, -32007);
}
fn seed_pm_transcript(registry: &SessionRegistry, id: &str) {
let transcript = registry
.begin_pm_transcript(id, "you are the pm", "first task")
.unwrap();
registry.store_pm_transcript(id, transcript);
}
#[tokio::test]
async fn set_goal_writes_operator_source() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
seed_pm_transcript(®istry, &session.id);
registry.set_goal(&session.id, 2, "ship it").unwrap();
let goals = registry.get_goals(&session.id).unwrap();
assert_eq!(goals.len(), 1);
assert_eq!(goals[0].slot, 2);
assert_eq!(goals[0].text, "ship it");
assert_eq!(goals[0].source, crate::agent_loop::GoalSource::Operator);
}
#[tokio::test]
async fn set_goal_no_transcript_yet_errors() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let err = registry.set_goal(&session.id, 1, "x").unwrap_err();
assert_eq!(err.code, -32003);
assert!(err.message.contains("no transcript yet"));
}
#[tokio::test]
async fn set_goal_out_of_range_slot_errors() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
seed_pm_transcript(®istry, &session.id);
assert_eq!(
registry.set_goal(&session.id, 0, "x").unwrap_err().code,
-32003
);
assert_eq!(
registry.set_goal(&session.id, 6, "x").unwrap_err().code,
-32003
);
}
#[tokio::test]
async fn set_goal_unknown_session_errors() {
let registry = SessionRegistry::new();
assert_eq!(registry.set_goal("nope", 1, "x").unwrap_err().code, -32007);
}
#[tokio::test]
async fn clear_goal_clears_slot() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
seed_pm_transcript(®istry, &session.id);
registry.set_goal(&session.id, 3, "temp").unwrap();
registry.clear_goal(&session.id, 3).unwrap();
assert!(registry.get_goals(&session.id).unwrap().is_empty());
}
#[tokio::test]
async fn clear_goal_no_transcript_yet_errors() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let err = registry.clear_goal(&session.id, 1).unwrap_err();
assert_eq!(err.code, -32003);
}
#[tokio::test]
async fn clear_goal_out_of_range_slot_errors() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
seed_pm_transcript(®istry, &session.id);
assert_eq!(
registry.clear_goal(&session.id, 0).unwrap_err().code,
-32003
);
}
#[tokio::test]
async fn get_goals_returns_operator_and_model_sources() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
seed_pm_transcript(®istry, &session.id);
registry.set_goal(&session.id, 2, "operator goal").unwrap();
{
let sessions = registry.lock();
let handle = sessions
.get(&session.id)
.unwrap()
.pm_transcript
.as_ref()
.unwrap()
.goals_handle();
handle
.lock()
.unwrap()
.set(1, "model goal", crate::agent_loop::GoalSource::Model)
.unwrap();
}
let goals = registry.get_goals(&session.id).unwrap();
assert_eq!(goals.len(), 2);
let slot1 = goals.iter().find(|g| g.slot == 1).expect("slot 1 present");
assert_eq!(slot1.source, crate::agent_loop::GoalSource::Model);
let slot2 = goals.iter().find(|g| g.slot == 2).expect("slot 2 present");
assert_eq!(slot2.source, crate::agent_loop::GoalSource::Operator);
registry
.set_goal(&session.id, 1, "operator overwrites model")
.unwrap();
let goals = registry.get_goals(&session.id).unwrap();
let slot1 = goals.iter().find(|g| g.slot == 1).expect("slot 1 present");
assert_eq!(slot1.text, "operator overwrites model");
assert_eq!(slot1.source, crate::agent_loop::GoalSource::Operator);
}
#[tokio::test]
async fn get_goals_on_never_run_session_is_empty() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
assert!(registry.get_goals(&session.id).unwrap().is_empty());
}
#[tokio::test]
async fn get_goals_unknown_session_errors() {
let registry = SessionRegistry::new();
assert_eq!(registry.get_goals("nope").unwrap_err().code, -32007);
}
#[tokio::test]
async fn get_transcript_round_trips_goal_state() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
seed_pm_transcript(®istry, &session.id);
registry
.set_goal(&session.id, 4, "finish the migration")
.unwrap();
let record = registry.get_transcript(&session.id).unwrap();
assert_eq!(record.goals.len(), 1);
assert_eq!(record.goals[0].slot, 4);
assert_eq!(record.goals[0].text, "finish the migration");
assert_eq!(
record.goals[0].source,
crate::agent_loop::GoalSource::Operator
);
let value = serde_json::to_value(&record).unwrap();
let back: TranscriptRecord = serde_json::from_value(value).unwrap();
assert_eq!(back.goals.len(), 1);
assert_eq!(back.goals[0].text, "finish the migration");
}
#[tokio::test]
async fn get_transcript_goals_empty_on_never_run_session() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let record = registry.get_transcript(&session.id).unwrap();
assert!(record.goals.is_empty());
}