use super::*;
use crate::session::TranscriptRecord;
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 project_dir = tempfile::tempdir().expect("project tempdir");
let binding = crate::binding::ProjectBinding::resolve(Some(project_dir.path().to_path_buf()))
.expect("tempdir must bind");
let expected_label = binding.label().expect("a bound project has a label");
let session = registry.create("do the thing".to_string(), None, binding);
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 { ref project, .. } if *project == expected_label),
"SessionStarted.project must be the binding-derived label {expected_label:?}, got {:?}",
first.event
);
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, crate::binding::ProjectBinding::None);
registry.create("b".to_string(), None, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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]);
}
fn search_telemetry(lane: &str, hit_count: Option<usize>) -> crate::tools::SearchTelemetry {
crate::tools::SearchTelemetry {
lane: lane.to_string(),
query: "where is auth".to_string(),
hit_count,
hits: vec![],
latency_ms: 12,
}
}
fn search_telemetry_with_hits(hits: &[(&str, f64)]) -> crate::tools::SearchTelemetry {
crate::tools::SearchTelemetry {
lane: "semantic".to_string(),
query: "where is auth".to_string(),
hit_count: Some(hits.len()),
hits: hits
.iter()
.map(|(path, score)| crate::events::SearchHit {
path: (*path).to_string(),
score: *score,
})
.collect(),
latency_ms: 12,
}
}
fn recall_telemetry(results: &[(f64, bool)]) -> crate::tools::RecallTelemetry {
crate::tools::RecallTelemetry {
query: "pkce".to_string(),
results: results
.iter()
.map(|(score, injected)| crate::events::RecalledMemory {
score: *score,
injected: *injected,
text: String::new(),
run_id: None,
})
.collect(),
}
}
#[tokio::test]
async fn record_search_performed_publishes_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let mut events = crate::events::subscribe();
registry
.record_search_performed(
&session.id,
"python-engineer",
"eng-1",
&search_telemetry("grep", Some(7)),
)
.unwrap();
let envelope = next_event_for(&mut events, &session.id).await;
assert_eq!(envelope.kind, "search_performed");
assert!(matches!(
envelope.event,
Event::SearchPerformed { agent, agent_id, lane, query, hit_count, latency_ms, .. }
if agent == "python-engineer"
&& agent_id == "eng-1"
&& lane == "grep"
&& query == "where is auth"
&& hit_count == Some(7)
&& latency_ms == 12
));
}
#[tokio::test]
async fn record_search_performed_publishes_hits_with_path_and_score() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let mut events = crate::events::subscribe();
registry
.record_search_performed(
&session.id,
"python-engineer",
"eng-1",
&search_telemetry_with_hits(&[("src/auth.rs", 0.87), ("src/session/session.rs", 0.52)]),
)
.unwrap();
let envelope = next_event_for(&mut events, &session.id).await;
let Event::SearchPerformed {
hits, hit_count, ..
} = envelope.event
else {
panic!("expected SearchPerformed");
};
assert_eq!(hit_count, Some(2));
assert_eq!(
hits,
vec![
crate::events::SearchHit {
path: "src/auth.rs".to_string(),
score: 0.87
},
crate::events::SearchHit {
path: "src/session/session.rs".to_string(),
score: 0.52
},
],
"each hit's path AND score must survive record_search_performed"
);
}
#[tokio::test]
async fn record_memory_recalled_publishes_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let mut events = crate::events::subscribe();
registry
.record_memory_recalled(
&session.id,
"pm",
"pm-1",
&recall_telemetry(&[(0.9, true), (0.41, false)]),
)
.unwrap();
let envelope = next_event_for(&mut events, &session.id).await;
assert_eq!(envelope.kind, "memory_recalled");
let Event::MemoryRecalled {
agent,
agent_id,
query,
results,
..
} = envelope.event
else {
panic!("expected MemoryRecalled");
};
assert_eq!(agent, "pm");
assert_eq!(agent_id, "pm-1");
assert_eq!(query, "pkce");
assert_eq!(
results,
vec![
crate::events::RecalledMemory {
score: 0.9,
injected: true,
text: String::new(),
run_id: None,
},
crate::events::RecalledMemory {
score: 0.41,
injected: false,
text: String::new(),
run_id: None,
},
],
"both the scores and the injected/held-back split must survive emission"
);
}
#[tokio::test]
async fn record_search_performed_appends_to_search_audit() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
registry
.record_search_performed(
&session.id,
"python-engineer",
"eng-1",
&search_telemetry("grep", Some(7)),
)
.unwrap();
let audit = registry.get_search_audit(&session.id).unwrap();
assert_eq!(audit.len(), 1);
assert!(matches!(
&audit[0],
crate::events::SearchAuditRecord::Search {
agent,
agent_id,
lane,
query,
hit_count,
latency_ms,
..
} if agent == "python-engineer"
&& agent_id == "eng-1"
&& lane == "grep"
&& query == "where is auth"
&& *hit_count == Some(7)
&& *latency_ms == 12
));
}
#[tokio::test]
async fn record_memory_recalled_appends_to_search_audit() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
registry
.record_memory_recalled(
&session.id,
"pm",
"pm-1",
&recall_telemetry(&[(0.9, true), (0.41, false)]),
)
.unwrap();
let audit = registry.get_search_audit(&session.id).unwrap();
assert_eq!(audit.len(), 1);
assert!(matches!(
&audit[0],
crate::events::SearchAuditRecord::Recall {
agent,
agent_id,
query,
result_count,
injected_count,
..
} if agent == "pm"
&& agent_id == "pm-1"
&& query == "pkce"
&& *result_count == 2
&& *injected_count == 1
));
}
#[tokio::test]
async fn record_tool_started_publishes_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let mut events = crate::events::subscribe();
registry
.record_tool_started(&session.id, "pm", "pm-1", "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 { agent, agent_id, tool, call_id, args_preview, .. }
if agent == "pm"
&& agent_id == "pm-1"
&& 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, crate::binding::ProjectBinding::None);
let mut events = crate::events::subscribe();
registry
.record_tool_finished(&session.id, "pm", "pm-1", "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 { agent, agent_id, success, result_preview, .. }
if agent == "pm" && agent_id == "pm-1" && 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, crate::binding::ProjectBinding::None);
let mut events = crate::events::subscribe();
registry
.record_tool_error(&session.id, "pm", "pm-1", "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 { agent, agent_id, error, .. }
if agent == "pm" && agent_id == "pm-1" && error == "timed out"
));
}
#[tokio::test]
async fn record_log_publishes_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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_agent_message_delta_publishes_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let mut events = crate::events::subscribe();
registry
.record_agent_message_delta(&session.id, "pm", "pm-1", "turn-1", "hello", true)
.unwrap();
let envelope = next_event_for(&mut events, &session.id).await;
assert_eq!(envelope.kind, "agent_message_delta");
assert!(matches!(
envelope.event,
Event::AgentMessageDelta { agent, agent_id, turn_id, delta, done, .. }
if agent == "pm" && agent_id == "pm-1" && turn_id == "turn-1"
&& delta == "hello" && done
));
}
#[tokio::test]
async fn record_agent_spawned_publishes_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, ProjectBinding::None);
let mut events = crate::events::subscribe();
registry
.record_agent_spawned(&session.id, "engineer", "eng-1", "build the thing")
.unwrap();
let envelope = next_event_for(&mut events, &session.id).await;
assert_eq!(envelope.kind, "agent_spawned");
assert!(matches!(
envelope.event,
Event::AgentSpawned { agent, agent_id, task_preview, .. }
if agent == "engineer" && agent_id == "eng-1"
&& task_preview == "build the thing"
));
}
#[tokio::test]
async fn record_agent_done_publishes_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, ProjectBinding::None);
let mut events = crate::events::subscribe();
registry
.record_agent_done(&session.id, "engineer", "eng-1", "success")
.unwrap();
let envelope = next_event_for(&mut events, &session.id).await;
assert_eq!(envelope.kind, "agent_done");
assert!(matches!(
envelope.event,
Event::AgentDone { agent, agent_id, status, .. }
if agent == "engineer" && agent_id == "eng-1" && status == "success"
));
}
#[tokio::test]
async fn record_agent_failed_publishes_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, ProjectBinding::None);
let mut events = crate::events::subscribe();
registry
.record_agent_failed(&session.id, "engineer", "eng-1", "turn cap exceeded")
.unwrap();
let envelope = next_event_for(&mut events, &session.id).await;
assert_eq!(envelope.kind, "agent_failed");
assert!(matches!(
envelope.event,
Event::AgentFailed { agent, agent_id, error, .. }
if agent == "engineer" && agent_id == "eng-1"
&& error == "turn cap exceeded"
));
}
#[tokio::test]
async fn record_permission_requested_publishes_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, ProjectBinding::None);
let mut events = crate::events::subscribe();
registry
.record_permission_requested(
&session.id,
"req-1",
"engineer",
"eng-1",
"bash",
"GITHUB_TOKEN=<redacted> gh pr create",
"bash[*]",
)
.unwrap();
let envelope = next_event_for(&mut events, &session.id).await;
assert_eq!(envelope.kind, "permission_requested");
assert!(matches!(
envelope.event,
Event::PermissionRequested { request_id, agent, subject, rule, .. }
if request_id == "req-1" && agent == "engineer"
&& subject == "GITHUB_TOKEN=<redacted> gh pr create"
&& rule == "bash[*]"
));
}
#[tokio::test]
async fn prompter_attached_while_a_session_attachment_lives() {
use crate::permissions::PermissionEvents;
let registry = SessionRegistry::new();
let watched = registry.create("watched".to_string(), None, ProjectBinding::None);
let headless = registry.create("headless".to_string(), None, ProjectBinding::None);
let (tx, _rx) = notify_channel();
let consumer = crate::events::subscribe();
assert!(!registry.prompter_attached(&watched.id));
registry
.attach(&watched.id, Uuid::new_v4(), tx)
.expect("attach must succeed");
assert!(registry.prompter_attached(&watched.id));
assert!(
!registry.prompter_attached(&headless.id),
"a sibling session nobody attached to must stay headless"
);
drop(consumer);
}
#[tokio::test]
async fn prompter_claim_is_released_when_its_guard_drops() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, ProjectBinding::None);
let claim = registry.claim_prompter(&session.id);
assert!(claim.is_some(), "a live session must be claimable");
assert_eq!(registry.prompter_count(&session.id), 1);
let second = registry.claim_prompter(&session.id);
assert_eq!(registry.prompter_count(&session.id), 2);
drop(second);
assert_eq!(registry.prompter_count(&session.id), 1);
drop(claim);
assert_eq!(registry.prompter_count(&session.id), 0);
}
#[tokio::test]
async fn prompter_attached_for_an_unknown_session_is_false() {
use crate::permissions::PermissionEvents;
let registry = SessionRegistry::new();
assert_eq!(registry.prompter_count("no-such-session"), 0);
assert!(!registry.prompter_attached("no-such-session"));
assert!(
registry.claim_prompter("no-such-session").is_none(),
"nothing may be claimed on a session that does not exist"
);
}
#[tokio::test]
async fn prompter_count_survives_a_poisoned_registry_lock() {
let registry = Arc::new(SessionRegistry::new());
let session = registry.create("t".to_string(), None, ProjectBinding::None);
let claim = registry.claim_prompter(&session.id);
let poisoner = Arc::clone(®istry);
let panicked = std::thread::spawn(move || {
let _held = poisoner.sessions.lock();
panic!("poison the registry mutex");
})
.join();
assert!(panicked.is_err(), "the helper thread must have panicked");
assert!(
registry.sessions.is_poisoned(),
"the mutex must actually be poisoned for this test to mean anything"
);
assert_eq!(registry.prompter_count(&session.id), 1);
assert_eq!(registry.prompter_count("no-such-session"), 0);
drop(claim);
assert_eq!(registry.prompter_count(&session.id), 0);
}
#[tokio::test]
async fn record_permission_resolved_publishes_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, ProjectBinding::None);
let mut events = crate::events::subscribe();
registry
.record_permission_resolved(&session.id, "req-1", "engineer", "eng-1", "deny", "timeout")
.unwrap();
let envelope = next_event_for(&mut events, &session.id).await;
assert_eq!(envelope.kind, "permission_resolved");
assert!(matches!(
envelope.event,
Event::PermissionResolved { decision, source, .. }
if decision == "deny" && source == "timeout"
));
}
#[tokio::test]
async fn record_plumbing_methods_reject_unknown_session() {
let registry = SessionRegistry::new();
assert_eq!(
registry
.record_tool_started("nope", "pm", "pm-1", "t", "c", "a")
.unwrap_err()
.code,
-32007
);
assert_eq!(
registry
.record_tool_finished("nope", "pm", "pm-1", "t", "c", true, "r")
.unwrap_err()
.code,
-32007
);
assert_eq!(
registry
.record_tool_error("nope", "pm", "pm-1", "t", "c", "e")
.unwrap_err()
.code,
-32007
);
assert_eq!(
registry
.record_search_performed("nope", "pm", "pm-1", &search_telemetry("semantic", Some(1)))
.unwrap_err()
.code,
-32007
);
assert_eq!(
registry
.record_memory_recalled("nope", "pm", "pm-1", &recall_telemetry(&[(0.9, true)]))
.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
);
assert_eq!(
registry
.record_agent_message_delta("nope", "pm", "pm-1", "turn-1", "m", true)
.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);
}
fn begin_execution_must_refuse(status: SessionStatus) -> bool {
match status {
SessionStatus::Created | SessionStatus::Running => false,
SessionStatus::Finished | SessionStatus::TurnCapExceeded | SessionStatus::Cancelled => {
false
}
SessionStatus::Failed | SessionStatus::DeadlineExceeded => true,
}
}
#[tokio::test]
async fn begin_execution_rejects_terminal_session() {
let registry = SessionRegistry::new();
for status in [
SessionStatus::Finished,
SessionStatus::TurnCapExceeded,
SessionStatus::Cancelled,
SessionStatus::Failed,
SessionStatus::DeadlineExceeded,
] {
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
registry.finish(&session.id, status).unwrap();
assert_eq!(registry.status(&session.id).unwrap().status, status);
let outcome = registry.begin_execution(&session.id);
if begin_execution_must_refuse(status) {
let err = outcome.expect_err(&format!("{status:?} must stay terminal"));
assert_eq!(
err.code, -32003,
"{status:?} must be invalid_argument, not session_not_found"
);
assert!(
err.message.contains("already terminal"),
"{status:?} must be refused for its status, not for a held \
execution slot: {err:?}"
);
} else {
outcome.unwrap_or_else(|e| panic!("{status:?} must be resumable: {e:?}"));
}
}
}
#[tokio::test]
async fn begin_execution_rejects_second_overlapping_run() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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_resumes_a_turn_cap_exceeded_session() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let _first = registry.begin_execution(&session.id).unwrap();
registry.finish_execution(&session.id);
registry
.finish(&session.id, SessionStatus::TurnCapExceeded)
.unwrap();
assert_eq!(
registry.status(&session.id).unwrap().status,
SessionStatus::TurnCapExceeded,
"a session whose call exhausted its turn budget must land in TurnCapExceeded, not Failed"
);
let mut events = crate::events::subscribe();
assert!(
registry.begin_execution(&session.id).is_ok(),
"a TurnCapExceeded session must be resumable for its next task.run (#3888)"
);
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_resumes_a_cancelled_session() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
registry.cancel(&session.id).unwrap();
assert_eq!(
registry.status(&session.id).unwrap().status,
SessionStatus::Cancelled
);
let mut events = crate::events::subscribe();
registry
.begin_execution(&session.id)
.expect("a cancelled session must accept the next prompt");
assert_eq!(
registry.status(&session.id).unwrap().status,
SessionStatus::Running,
"resuming must transition 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_pm_transcript_seeds_on_first_call() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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);
}
fn durable_project_root() -> &'static std::path::Path {
std::path::Path::new("/nonexistent-durable-root/projects/tcode-fixture")
}
#[tokio::test]
async fn memory_sink_for_reuses_the_same_sink_across_calls() {
let registry = Arc::new(SessionRegistry::new());
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let first = registry
.memory_sink_for(&session.id, Some(durable_project_root()))
.expect("first call constructs a sink");
let second = registry
.memory_sink_for(&session.id, Some(durable_project_root()))
.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_unresolvable_palace_returns_no_sink() {
let tmp = tempfile::TempDir::new().unwrap();
let pin_dir = tmp.path().join(".trusty-tools");
std::fs::create_dir_all(&pin_dir).unwrap();
std::fs::write(
pin_dir.join("trusty-memory.yaml"),
"palace: [unclosed\n\t bad: :",
)
.unwrap();
let registry = Arc::new(SessionRegistry::new());
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
assert!(
registry
.memory_sink_for(&session.id, Some(tmp.path()))
.is_none(),
"a project whose pin cannot be parsed must get no sink — a shared \
placeholder palace would commingle two projects' turn content"
);
}
#[tokio::test]
async fn memory_sink_for_unknown_session_returns_none() {
let registry = Arc::new(SessionRegistry::new());
assert!(
registry
.memory_sink_for("nope", Some(durable_project_root()))
.is_none()
);
}
#[tokio::test]
async fn memory_sink_for_temp_rooted_session_forbids_palace_create() {
let registry = Arc::new(SessionRegistry::new());
let project_dir = tempfile::TempDir::new().unwrap();
let raw = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let sink = registry
.memory_sink_for(&raw.id, Some(project_dir.path()))
.expect("a temp-rooted session still gets a sink");
assert_eq!(
sink.palace_creation(),
crate::session::PalaceCreation::Forbidden,
"a temp-rooted session must never be entitled to mint a palace (#4638)"
);
let binding = crate::binding::ProjectBinding::resolve(Some(project_dir.path().to_path_buf()))
.expect("tempdir must bind");
let canonical = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let sink = registry
.memory_sink_for(&canonical.id, binding.root())
.expect("a temp-rooted session still gets a sink");
assert_eq!(
sink.palace_creation(),
crate::session::PalaceCreation::Forbidden,
"the CANONICALIZED temp root the real run_and_record path passes must \
be recognised too (#4638)"
);
}
#[tokio::test]
async fn memory_sink_for_many_sessions_mint_at_most_one_palace() {
let registry = Arc::new(SessionRegistry::new());
let mut creatable: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
let mut temp_rooted = 0usize;
for _ in 0..25 {
let durable = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let sink = registry
.memory_sink_for(&durable.id, Some(durable_project_root()))
.expect("a durable project root must still record turns");
if sink.palace_creation() == crate::session::PalaceCreation::Allowed {
creatable.insert(sink.palace().to_string());
}
let ephemeral =
registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let tmp = tempfile::TempDir::new().unwrap();
let sink = registry
.memory_sink_for(&ephemeral.id, Some(tmp.path()))
.expect("a temp-rooted session still gets a sink");
temp_rooted += 1;
if sink.palace_creation() == crate::session::PalaceCreation::Allowed {
creatable.insert(sink.palace().to_string());
}
}
assert_eq!(
temp_rooted, 25,
"sanity: every ephemeral session was exercised"
);
assert_eq!(
creatable.len(),
1,
"50 sessions may mint at most ONE palace — the shared durable \
project's; got {creatable:?}"
);
}
#[tokio::test]
async fn set_run_outcome_stores_transcript_and_usage() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::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_publishes_activity_update_when_workstream_bound() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
registry
.bind_workstream(&session.id, crate::workstreams::WorkstreamId::new())
.expect("bind");
registry.set_run_outcome(
&session.id,
vec![],
crate::perf::TokenUsage::default(),
None,
);
let events = registry.replay(&session.id).unwrap();
assert!(
events
.iter()
.any(|e| matches!(&e.event, Event::SessionActivityUpdate { has_running_task, .. } if !has_running_task)),
"expected a SessionActivityUpdate event: {events:?}"
);
}
#[tokio::test]
async fn set_run_outcome_stays_silent_for_unbound_session() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
registry.set_run_outcome(
&session.id,
vec![],
crate::perf::TokenUsage::default(),
None,
);
let events = registry.replay(&session.id).unwrap();
assert!(
!events
.iter()
.any(|e| matches!(&e.event, Event::SessionActivityUpdate { .. })),
"an unbound session must emit no SessionActivityUpdate (frozen M1 baseline): {events:?}"
);
}
#[tokio::test]
async fn set_run_outcome_accumulates_across_two_calls() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::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, crate::binding::ProjectBinding::None);
let record = registry.get_transcript(&session.id).unwrap();
assert!(record.goals.is_empty());
}
#[tokio::test]
async fn create_derives_project_label_from_binding() {
let registry = SessionRegistry::new();
let project_dir = tempfile::tempdir().expect("project tempdir");
let binding = crate::binding::ProjectBinding::resolve(Some(project_dir.path().to_path_buf()))
.expect("tempdir must bind");
let session = registry.create("t".to_string(), None, binding.clone());
assert_eq!(
session.project,
binding.label(),
"the label must be the binding's own label, not an independent string"
);
assert_eq!(session.binding, binding);
let projectless = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
assert_eq!(
projectless.project, None,
"projectless must derive no label"
);
assert_eq!(projectless.binding, crate::binding::ProjectBinding::None);
}
#[tokio::test]
async fn memory_sink_for_projectless_session_returns_none() {
let registry = Arc::new(SessionRegistry::new());
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
assert!(
registry.memory_sink_for(&session.id, None).is_none(),
"a projectless session must have no project-scoped memory palace"
);
}
fn durability_warnings(registry: &SessionRegistry, id: &str) -> Vec<String> {
registry
.replay(id)
.unwrap()
.into_iter()
.filter_map(|envelope| match envelope.event {
Event::Log { level, message, .. } if level == "warn" => Some(message),
_ => None,
})
.collect()
}
#[test]
fn memory_durability_retains_counts_resets_streak_and_warns_at_one_and_three() {
use crate::session::memory_sink::{MemoryFailureCategory, MemoryTurnOutcome};
let registry = SessionRegistry::new();
let session = registry.create("t".into(), None, crate::binding::ProjectBinding::None);
let mut next_sequence = 1;
let mut degraded = |category| {
let sequence = next_sequence;
next_sequence += 1;
MemoryTurnOutcome::Degraded {
sequence,
category,
at: Utc::now(),
}
};
for category in [
MemoryFailureCategory::ChatTurnAppend,
MemoryFailureCategory::MemoryRemember,
MemoryFailureCategory::MemoryRememberSkipped,
MemoryFailureCategory::QueueFull,
] {
registry
.record_memory_durability(&session.id, degraded(category))
.unwrap();
}
assert_eq!(
durability_warnings(®istry, &session.id).len(),
2,
"warn only at streaks one and three"
);
let status = registry
.get_transcript(&session.id)
.unwrap()
.memory_durability;
assert_eq!(status.total_failed_turns, 4);
assert_eq!(status.consecutive_failed_turns, 4);
assert_eq!(status.unrecorded_outcomes, 0);
assert_eq!(
status.latest_failure_category,
Some(MemoryFailureCategory::QueueFull)
);
assert!(status.latest_failure_at.is_some());
registry
.record_memory_durability(&session.id, MemoryTurnOutcome::Durable { sequence: 5 })
.unwrap();
let reset = registry
.get_transcript(&session.id)
.unwrap()
.memory_durability;
assert_eq!(reset.total_failed_turns, 4);
assert_eq!(reset.consecutive_failed_turns, 0);
}
#[test]
fn older_durable_completion_does_not_clear_newer_queue_failure() {
use crate::session::memory_sink::{MemoryFailureCategory, MemoryTurnOutcome};
let registry = SessionRegistry::new();
let session = registry.create("t".into(), None, crate::binding::ProjectBinding::None);
registry
.record_memory_durability(
&session.id,
MemoryTurnOutcome::Degraded {
sequence: 2,
category: MemoryFailureCategory::QueueFull,
at: Utc::now(),
},
)
.unwrap();
registry
.record_memory_durability(&session.id, MemoryTurnOutcome::Durable { sequence: 1 })
.unwrap();
let status = registry
.get_transcript(&session.id)
.unwrap()
.memory_durability;
assert_eq!(status.total_failed_turns, 1);
assert_eq!(
status.consecutive_failed_turns, 1,
"an older durable completion must not erase a newer dropped turn"
);
assert_eq!(
status.latest_failure_category,
Some(MemoryFailureCategory::QueueFull)
);
}
#[test]
fn two_out_of_order_degradations_fold_in_logical_sequence() {
use crate::session::memory_sink::{MemoryFailureCategory, MemoryTurnOutcome};
let registry = SessionRegistry::new();
let session = registry.create("t".into(), None, crate::binding::ProjectBinding::None);
let first_at = Utc::now();
let second_at = first_at + chrono::Duration::seconds(1);
for outcome in [
MemoryTurnOutcome::Degraded {
sequence: 2,
category: MemoryFailureCategory::QueueFull,
at: second_at,
},
MemoryTurnOutcome::Degraded {
sequence: 1,
category: MemoryFailureCategory::ChatTurnAppend,
at: first_at,
},
] {
registry
.record_memory_durability(&session.id, outcome)
.unwrap();
}
let status = registry
.get_transcript(&session.id)
.unwrap()
.memory_durability;
assert_eq!(status.total_failed_turns, 2);
assert_eq!(status.consecutive_failed_turns, 2);
assert_eq!(
status.latest_failure_category,
Some(MemoryFailureCategory::QueueFull)
);
assert_eq!(status.latest_failure_at, Some(second_at));
}
#[test]
fn three_out_of_order_degradations_emit_every_crossed_warning_threshold() {
use crate::session::memory_sink::{MemoryFailureCategory, MemoryTurnOutcome};
let registry = SessionRegistry::new();
let session = registry.create("t".into(), None, crate::binding::ProjectBinding::None);
let now = Utc::now();
for (sequence, category) in [
(2, MemoryFailureCategory::QueueFull),
(3, MemoryFailureCategory::QueueFull),
(1, MemoryFailureCategory::ChatTurnAppend),
] {
registry
.record_memory_durability(
&session.id,
MemoryTurnOutcome::Degraded {
sequence,
category,
at: now + chrono::Duration::seconds(sequence as i64),
},
)
.unwrap();
}
let status = registry
.get_transcript(&session.id)
.unwrap()
.memory_durability;
assert_eq!(status.total_failed_turns, 3);
assert_eq!(status.consecutive_failed_turns, 3);
assert_eq!(
status.latest_failure_category,
Some(MemoryFailureCategory::QueueFull)
);
let warnings = durability_warnings(®istry, &session.id);
assert_eq!(
warnings.len(),
2,
"streak thresholds one and three both warn"
);
assert!(warnings[0].contains("category=ChatTurnAppend"));
assert!(warnings[0].contains("consecutive_failed_turns=1"));
assert!(warnings[1].contains("category=QueueFull"));
assert!(warnings[1].contains("consecutive_failed_turns=3"));
}
#[test]
fn mixed_out_of_order_memory_outcomes_preserve_the_newest_logical_state() {
use crate::session::memory_sink::{MemoryFailureCategory, MemoryTurnOutcome};
let registry = SessionRegistry::new();
let session = registry.create("t".into(), None, crate::binding::ProjectBinding::None);
let now = Utc::now();
for outcome in [
MemoryTurnOutcome::Degraded {
sequence: 3,
category: MemoryFailureCategory::QueueFull,
at: now,
},
MemoryTurnOutcome::Degraded {
sequence: 1,
category: MemoryFailureCategory::DrainClosed,
at: now,
},
MemoryTurnOutcome::Durable { sequence: 2 },
] {
registry
.record_memory_durability(&session.id, outcome)
.unwrap();
}
let status = registry
.get_transcript(&session.id)
.unwrap()
.memory_durability;
assert_eq!(status.total_failed_turns, 2);
assert_eq!(
status.consecutive_failed_turns, 1,
"late outcomes must not move the logical streak behind turn 3"
);
assert_eq!(
status.latest_failure_category,
Some(MemoryFailureCategory::QueueFull)
);
assert_eq!(status.latest_failure_at, Some(now));
let warnings = durability_warnings(®istry, &session.id);
assert_eq!(
warnings.len(),
2,
"each streak warns at its own first failure"
);
assert!(warnings[0].contains("category=DrainClosed"));
assert!(warnings[0].contains("consecutive_failed_turns=1"));
assert!(warnings[1].contains("category=QueueFull"));
assert!(warnings[1].contains("consecutive_failed_turns=1"));
}
#[test]
fn outcome_beyond_the_reorder_bound_is_counted_as_unrecorded() {
use crate::session::memory_sink::{MemoryFailureCategory, MemoryTurnOutcome, QUEUE_CAPACITY};
let registry = SessionRegistry::new();
let session = registry.create("t".into(), None, crate::binding::ProjectBinding::None);
let bound = QUEUE_CAPACITY + 2;
let mut refusals = 0;
for sequence in (2..).step_by(2).take(bound + 1) {
let result = registry.record_memory_durability(
&session.id,
MemoryTurnOutcome::Degraded {
sequence,
category: MemoryFailureCategory::QueueFull,
at: Utc::now(),
},
);
if let Err(error) = result {
refusals += 1;
assert!(
error.message.contains("reorder bound exceeded"),
"unexpected error: {}",
error.message
);
}
}
assert_eq!(refusals, 1, "exactly the outcome past the bound is refused");
let status = registry
.get_transcript(&session.id)
.unwrap()
.memory_durability;
assert_eq!(
status.unrecorded_outcomes, 1,
"a refused outcome must leave a trace on the session's status"
);
assert_eq!(
status.total_failed_turns, bound as u64,
"the refused outcome is not counted as a failed turn — it was never applied"
);
}
#[test]
fn memory_degradation_event_is_redacted() {
use crate::session::memory_sink::{MemoryFailureCategory, MemoryTurnOutcome};
let registry = SessionRegistry::new();
let session = registry.create(
"secret prompt".into(),
None,
crate::binding::ProjectBinding::None,
);
registry
.record_memory_durability(
&session.id,
MemoryTurnOutcome::Degraded {
sequence: 1,
category: MemoryFailureCategory::MemoryRemember,
at: Utc::now(),
},
)
.unwrap();
let warnings = durability_warnings(®istry, &session.id);
let message = warnings.first().expect("warning event");
assert!(!message.contains("secret prompt"));
assert!(message.contains("MemoryRemember"));
assert!(message.contains("total_failed_turns=1"));
}
fn readiness(
lifecycle: &str,
chunks: u64,
lexical: bool,
semantic: bool,
) -> trusty_common::search_readiness::IndexReadiness {
trusty_common::search_readiness::IndexReadiness {
index_id: "repo".into(),
lifecycle_status: lifecycle.into(),
chunk_count: chunks,
lexical_ready: lexical,
semantic_ready: semantic,
graph_ready: false,
}
}
#[tokio::test]
async fn record_index_readiness_warming_publishes_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let mut events = crate::events::subscribe();
let r = readiness("indexed_lexical", 4096, true, false);
registry
.record_index_readiness(&session.id, Some(&r), &r.summary())
.unwrap();
let envelope = next_event_for(&mut events, &session.id).await;
assert_eq!(envelope.kind, "index_readiness");
assert!(matches!(
envelope.event,
Event::IndexReadiness { state, lexical_ready, semantic_ready, chunk_count, .. }
if state == "warming" && lexical_ready && !semantic_ready && chunk_count == Some(4096)
));
}
#[tokio::test]
async fn record_index_readiness_ready_publishes_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let mut events = crate::events::subscribe();
let r = readiness("ready", 50_000, true, true);
registry
.record_index_readiness(&session.id, Some(&r), &r.summary())
.unwrap();
let envelope = next_event_for(&mut events, &session.id).await;
assert!(matches!(
envelope.event,
Event::IndexReadiness { state, semantic_ready, .. }
if state == "ready" && semantic_ready
));
}
#[tokio::test]
async fn warming_index_is_distinguishable_from_ready_with_zero_hits() {
let registry = SessionRegistry::new();
let warming_session =
registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let ready_session =
registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let mut events = crate::events::subscribe();
let warming = readiness("walking", 0, false, false);
registry
.record_index_readiness(&warming_session.id, Some(&warming), &warming.summary())
.unwrap();
let warming_ev = next_event_for(&mut events, &warming_session.id).await;
let ready = readiness("ready", 0, true, true);
registry
.record_index_readiness(&ready_session.id, Some(&ready), &ready.summary())
.unwrap();
let ready_ev = next_event_for(&mut events, &ready_session.id).await;
let state_of = |ev: &Event| match ev {
Event::IndexReadiness { state, .. } => state.clone(),
other => panic!("expected index_readiness, got {other:?}"),
};
let warming_state = state_of(&warming_ev.event);
let ready_state = state_of(&ready_ev.event);
assert_eq!(warming_state, "warming");
assert_eq!(ready_state, "ready");
assert_ne!(
warming_state, ready_state,
"a cold/warming index MUST NOT look like a ready index with zero hits — \
they mean opposite things"
);
}
#[tokio::test]
async fn record_index_readiness_unavailable_publishes_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let mut events = crate::events::subscribe();
registry
.record_index_readiness(&session.id, None, "no daemon")
.unwrap();
let envelope = next_event_for(&mut events, &session.id).await;
assert_eq!(envelope.kind, "index_readiness");
assert!(matches!(
envelope.event,
Event::IndexReadiness { state, index_id, chunk_count, semantic_ready, .. }
if state == "unavailable"
&& index_id.is_none()
&& chunk_count.is_none()
&& !semantic_ready
));
}
#[tokio::test]
async fn record_index_readiness_unknown_session_errors() {
let registry = SessionRegistry::new();
assert!(registry.record_index_readiness("nope", None, "x").is_err());
}
#[tokio::test]
async fn record_index_readiness_caches_snapshot_for_late_query() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let r = readiness("ready", 128, true, true);
registry
.record_index_readiness(&session.id, Some(&r), &r.summary())
.unwrap();
let queried = registry.get_readiness(&session.id).unwrap();
match queried {
events::ReadinessQuery::Probed(snapshot) => {
assert_eq!(snapshot.state, "ready");
assert_eq!(snapshot.summary, r.summary());
assert!(snapshot.semantic_ready);
}
events::ReadinessQuery::NeverProbed => {
panic!("expected a cached snapshot after record_index_readiness, got NeverProbed")
}
}
}
#[tokio::test]
async fn get_readiness_unknown_session_errors() {
let registry = SessionRegistry::new();
let err = registry.get_readiness("nope").unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn record_context_budget_publishes_event() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let mut events = crate::events::subscribe();
let snapshot = crate::agent_loop::ContextBudgetSnapshot {
context_window: 200_000,
overhead_tokens: 50_000,
overhead_cap_tokens: 80_000,
working_context_pct: 75,
overhead_pct: 25,
within_budget: true,
fired: true,
rounds: 2,
};
registry
.record_context_budget(&session.id, &snapshot)
.unwrap();
let envelope = next_event_for(&mut events, &session.id).await;
assert_eq!(envelope.kind, "context_budget");
assert!(matches!(
envelope.event,
Event::ContextBudget {
context_window_tokens,
overhead_tokens,
working_context_pct,
within_budget,
compaction_fired,
compaction_rounds,
..
} if context_window_tokens == 200_000
&& overhead_tokens == 50_000
&& working_context_pct == 75
&& within_budget
&& compaction_fired
&& compaction_rounds == 2
));
}
#[tokio::test]
async fn record_context_budget_caches_snapshot_for_late_query() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let snapshot = crate::agent_loop::ContextBudgetSnapshot {
context_window: 200_000,
overhead_tokens: 50_000,
overhead_cap_tokens: 80_000,
working_context_pct: 75,
overhead_pct: 25,
within_budget: true,
fired: true,
rounds: 2,
};
registry
.record_context_budget(&session.id, &snapshot)
.unwrap();
let queried = registry.get_context_budget(&session.id).unwrap();
match queried {
events::ContextBudgetQuery::Recorded(cached) => {
assert_eq!(cached.context_window_tokens, 200_000);
assert_eq!(cached.working_context_pct, 75);
assert!(cached.within_budget);
assert!(cached.compaction_fired);
assert_eq!(cached.compaction_rounds, 2);
}
events::ContextBudgetQuery::NeverRecorded => {
panic!("expected a cached snapshot after record_context_budget, got NeverRecorded")
}
}
}
#[tokio::test]
async fn get_context_budget_never_recorded_returns_never_recorded() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let queried = registry.get_context_budget(&session.id).unwrap();
assert!(matches!(queried, events::ContextBudgetQuery::NeverRecorded));
}
#[tokio::test]
async fn get_context_budget_unknown_session_errors() {
let registry = SessionRegistry::new();
let err = registry.get_context_budget("nope").unwrap_err();
assert_eq!(err.code, -32007);
}
fn floor_measurement(working_context_pct: u8) -> crate::agent_loop::ContextBudgetSnapshot {
crate::agent_loop::ContextBudgetSnapshot {
context_window: 200_000,
overhead_tokens: 200_000 * usize::from(100 - working_context_pct) / 100,
overhead_cap_tokens: 80_000,
working_context_pct,
overhead_pct: 100 - working_context_pct,
within_budget: working_context_pct >= 60,
fired: false,
rounds: 0,
}
}
#[tokio::test]
async fn context_floor_tracks_every_measurement() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
for pct in [90, 48, 75] {
registry
.record_context_budget(&session.id, &floor_measurement(pct))
.unwrap();
}
let events::ContextBudgetQuery::Recorded(snapshot) =
registry.get_context_budget(&session.id).unwrap()
else {
panic!("expected a recorded context budget");
};
assert_eq!(snapshot.working_context_pct, 75, "latest turn still wins");
assert_eq!(snapshot.working_context_pct_low_water_mark, Some(48));
assert_eq!(snapshot.working_context_pct_sample_count, 3);
}
#[tokio::test]
async fn context_floor_is_session_scoped() {
let registry = SessionRegistry::new();
let first = registry.create(
"first".to_string(),
None,
crate::binding::ProjectBinding::None,
);
let second = registry.create(
"second".to_string(),
None,
crate::binding::ProjectBinding::None,
);
registry
.record_context_budget(&first.id, &floor_measurement(90))
.unwrap();
registry
.record_context_budget(&second.id, &floor_measurement(12))
.unwrap();
let events::ContextBudgetQuery::Recorded(snapshot) =
registry.get_context_budget(&first.id).unwrap()
else {
panic!("expected a recorded context budget");
};
assert_eq!(snapshot.working_context_pct_low_water_mark, Some(90));
assert_eq!(snapshot.working_context_pct_sample_count, 1);
}
#[test]
fn context_floor_saturates_sample_count() {
let mut floor = super::super::registry_context_floor::ContextFloorState {
low_water_mark: Some(60),
sample_count: usize::MAX,
};
floor.record(48);
assert_eq!(floor.low_water_mark, Some(48));
assert_eq!(floor.sample_count, usize::MAX);
}
#[cfg(unix)]
#[tokio::test]
async fn context_budget_query_does_not_open_compression_log() {
use std::ffi::CString;
use std::os::unix::ffi::OsStrExt;
use std::sync::mpsc;
let dir = crate::agent_loop::telemetry::test_temp_dir("context-floor-no-open");
let path = CString::new(dir.join("compression.jsonl").as_os_str().as_bytes()).unwrap();
let created = unsafe { libc::mkfifo(path.as_ptr(), 0o600) };
assert_eq!(
created,
0,
"mkfifo failed: {}",
std::io::Error::last_os_error()
);
let registry = Arc::new(SessionRegistry::new());
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
registry
.record_context_budget(&session.id, &floor_measurement(73))
.unwrap();
let query = crate::agent_loop::telemetry::with_data_dir_env(&dir, || {
let (tx, rx) = mpsc::sync_channel(1);
let worker_registry = Arc::clone(®istry);
let session_id = session.id.clone();
let worker = std::thread::spawn(move || {
let _ = tx.send(worker_registry.get_context_budget(&session_id));
});
match rx.recv_timeout(Duration::from_secs(5)) {
Ok(result) => {
worker.join().expect("budget query worker panicked");
result
}
Err(mpsc::RecvTimeoutError::Timeout) => {
let writer = unsafe {
libc::open(
path.as_ptr(),
libc::O_WRONLY | libc::O_NONBLOCK | libc::O_CLOEXEC,
)
};
if writer >= 0 {
let payload = b"{not-json}\n";
unsafe {
libc::write(writer, payload.as_ptr().cast(), payload.len());
libc::close(writer);
}
worker.join().expect("budget query worker panicked");
}
panic!("get_context_budget opened compression.jsonl");
}
Err(mpsc::RecvTimeoutError::Disconnected) => {
worker.join().expect("budget query worker panicked");
panic!("budget query worker disconnected without a result");
}
}
})
.await
.unwrap();
let events::ContextBudgetQuery::Recorded(snapshot) = query else {
panic!("expected a recorded context budget");
};
assert_eq!(snapshot.working_context_pct_low_water_mark, Some(73));
assert_eq!(snapshot.working_context_pct_sample_count, 1);
std::fs::remove_dir_all(&dir).ok();
}
#[tokio::test]
async fn context_floor_after_restart_is_absent_not_wrong() {
let dir = crate::agent_loop::telemetry::test_temp_dir("context-floor-restart");
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
registry
.record_context_budget(&session.id, &floor_measurement(48))
.unwrap();
crate::agent_loop::telemetry::record_cadence_event(
&dir,
Some(session.id.clone()),
100_000,
104_000,
200_000,
5,
4,
);
let restarted = SessionRegistry::new();
let err = restarted.get_context_budget(&session.id).unwrap_err();
assert_eq!(
err.code, -32007,
"the session itself is gone, not its floor"
);
assert_eq!(
crate::agent_loop::telemetry::session_working_context_floor(&dir, &session.id),
(Some(48), 1),
"the durable log remains the offline history source across a restart"
);
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn set_task_result_stores_the_result() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
assert!(
registry.status(&session.id).unwrap().result.is_none(),
"a session that has never run carries no result"
);
registry.set_task_result(
&session.id,
crate::session::TaskResult::new(crate::session::TaskResultStatus::Partial)
.with_diff_ref(Some("tree-sha".to_string()))
.with_branch(Some("feat/x".to_string()))
.with_summary(Some("partial: changes captured".to_string())),
);
let stored = registry
.status(&session.id)
.unwrap()
.result
.expect("result must be readable back through session.status");
assert_eq!(stored.status, crate::session::TaskResultStatus::Partial);
assert_eq!(stored.diff_ref.as_deref(), Some("tree-sha"));
assert_eq!(stored.branch.as_deref(), Some("feat/x"));
assert_eq!(stored.pr_ref, None);
}
#[test]
fn cancel_records_a_refless_cancelled_result() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let snapshot = registry.cancel(&session.id).expect("cancel succeeds");
assert_eq!(snapshot.status, SessionStatus::Cancelled);
let result = snapshot
.result
.clone()
.expect("#4351: a cancelled session must carry a TaskResult");
assert_eq!(result.status, crate::session::TaskResultStatus::Cancelled);
assert_eq!(result.diff_ref, None);
assert_eq!(result.branch, None);
assert_eq!(result.pr_ref, None);
assert!(
result.summary.is_some(),
"a cancelled result must still say what happened"
);
let reread = registry.status(&session.id).expect("session exists");
assert_eq!(reread.result, snapshot.result);
}
#[test]
fn set_task_result_on_unknown_session_is_a_no_op() {
let registry = SessionRegistry::new();
registry.set_task_result(
"no-such-session",
crate::session::TaskResult::new(crate::session::TaskResultStatus::Failed),
);
assert!(registry.status("no-such-session").is_err());
}