1use std::collections::VecDeque;
27
28use hashbrown::HashSet;
29
30use crate::{
31 Diagnostic, DiagnosticSeverity, ItemCompletedEvent, ItemUpdatedEvent, ReasoningItem, ThreadEvent, ThreadItem,
32 ThreadItemDetails, ToolCallStatus, ToolOutcome, TurnStartedEvent,
33};
34
35pub const EXEC_SESSION_OUTPUT_ITEM_SUFFIX: &str = ":exec-session-output";
40
41const COMPLETED_ID_WINDOW: usize = 4096;
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum RepairPolicy {
49 Observe,
51 Repair,
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
59pub enum ViolationKind {
60 TurnReopened,
62 TerminalWithoutTurn,
64 DuplicateTerminal,
66 OpenItemAtTerminal,
68 DuplicateItemCompleted,
70 ItemAfterTurnEnd,
72 ItemReusedAfterCompleted,
75}
76
77impl ViolationKind {
78 pub const fn code(self) -> &'static str {
80 match self {
81 Self::TurnReopened => "lifecycle.turn_reopened",
82 Self::TerminalWithoutTurn => "lifecycle.terminal_without_turn",
83 Self::DuplicateTerminal => "lifecycle.duplicate_terminal",
84 Self::OpenItemAtTerminal => "lifecycle.open_item_at_terminal",
85 Self::DuplicateItemCompleted => "lifecycle.duplicate_item_completed",
86 Self::ItemAfterTurnEnd => "lifecycle.item_after_turn_end",
87 Self::ItemReusedAfterCompleted => "lifecycle.item_reused_after_completed",
88 }
89 }
90
91 const fn summary(self) -> &'static str {
92 match self {
93 Self::TurnReopened => "A turn started while another turn was still open.",
94 Self::TerminalWithoutTurn => "A turn ended without having started.",
95 Self::DuplicateTerminal => "A turn ended more than once.",
96 Self::OpenItemAtTerminal => "A turn ended while items it started were still open.",
97 Self::DuplicateItemCompleted => "An item completed more than once.",
98 Self::ItemAfterTurnEnd => "An item event arrived after its turn ended.",
99 Self::ItemReusedAfterCompleted => "An item id was reused after the item completed.",
100 }
101 }
102}
103
104#[derive(Debug, Clone, PartialEq, Eq)]
106pub struct Violation {
107 pub kind: ViolationKind,
108 pub item_id: Option<String>,
109}
110
111impl Violation {
112 pub fn diagnostic(&self) -> Diagnostic {
115 let code = self.kind.code();
116 let subject = self.item_id.as_deref().unwrap_or("turn");
117 Diagnostic {
118 severity: DiagnosticSeverity::Warning,
119 code: code.to_string(),
120 summary: self.kind.summary().to_string(),
121 agent_details: self.item_id.as_ref().map(|id| format!("item: {id}")).unwrap_or_default(),
122 correlation_id: format!("{code}:{subject}"),
123 actions: Vec::new(),
124 }
125 }
126}
127
128impl Violation {
129 pub fn event(&self) -> ThreadEvent {
134 let diagnostic = self.diagnostic();
135 ThreadEvent::ItemUpdated(ItemUpdatedEvent {
136 item: ThreadItem {
137 context: None,
138 id: diagnostic.correlation_id.clone(),
139 details: ThreadItemDetails::Reasoning(Box::new(ReasoningItem {
140 text: diagnostic.summary.clone(),
141 stage: Some("diagnosis".into()),
142 diagnostic: Some(Box::new(diagnostic)),
143 })),
144 },
145 })
146 }
147}
148
149#[derive(Debug, Default, PartialEq, Eq)]
151pub struct Admission {
152 pub before: Vec<ThreadEvent>,
154 pub event: Option<ThreadEvent>,
156 pub violations: Vec<Violation>,
158}
159
160impl Admission {
161 pub fn into_events(self) -> impl Iterator<Item = ThreadEvent> {
163 self.before.into_iter().chain(self.event)
164 }
165}
166
167#[derive(Debug, Clone, Copy, PartialEq, Eq)]
168enum Phase {
169 Idle,
171 Open,
172 Closed,
174}
175
176#[derive(Debug)]
178pub struct LifecycleGuard {
179 policy: RepairPolicy,
180 phase: Phase,
181 open: Vec<ThreadItem>,
183 completed: HashSet<String>,
184 completed_order: VecDeque<String>,
185}
186
187impl Default for LifecycleGuard {
188 fn default() -> Self {
191 Self::new(RepairPolicy::Repair)
192 }
193}
194
195impl LifecycleGuard {
196 pub fn new(policy: RepairPolicy) -> Self {
197 Self {
198 policy,
199 phase: Phase::Idle,
200 open: Vec::new(),
201 completed: HashSet::new(),
202 completed_order: VecDeque::new(),
203 }
204 }
205
206 pub fn turn_is_open(&self) -> bool {
208 self.phase == Phase::Open
209 }
210
211 pub fn admit(&mut self, event: ThreadEvent) -> Admission {
213 let mut admission = Admission::default();
214 match &event {
215 ThreadEvent::TurnStarted(_) => {
216 if self.phase == Phase::Open {
217 admission
218 .violations
219 .push(Violation { kind: ViolationKind::TurnReopened, item_id: None });
220 }
221 self.phase = Phase::Open;
222 }
223 ThreadEvent::TurnCompleted(_) | ThreadEvent::TurnFailed(_) => {
224 self.admit_terminal(&mut admission);
225 }
226 ThreadEvent::ItemStarted(started) => self.admit_item_started(&started.item, &mut admission),
227 ThreadEvent::ItemUpdated(updated) => self.admit_item_updated(&updated.item, &mut admission),
228 ThreadEvent::ItemCompleted(completed) => {
229 let keep = self.admit_item_completed(&completed.item, &mut admission);
230 if !keep {
231 return admission;
232 }
233 }
234 _ => {}
235 }
236 admission.event = Some(event);
237 admission
238 }
239
240 fn admit_terminal(&mut self, admission: &mut Admission) {
241 match self.phase {
242 Phase::Open => {
243 let open = std::mem::take(&mut self.open);
244 for item in open {
245 admission.violations.push(Violation {
246 kind: ViolationKind::OpenItemAtTerminal,
247 item_id: Some(item.id.clone()),
248 });
249 if self.policy == RepairPolicy::Repair {
250 let closed = close_item(item);
251 self.remember_completed(&closed.id);
252 admission
253 .before
254 .push(ThreadEvent::ItemCompleted(ItemCompletedEvent { item: closed }));
255 }
256 }
257 }
258 Phase::Idle => {
259 admission.violations.push(Violation {
260 kind: ViolationKind::TerminalWithoutTurn,
261 item_id: None,
262 });
263 if self.policy == RepairPolicy::Repair {
264 admission.before.push(ThreadEvent::TurnStarted(TurnStartedEvent::default()));
265 }
266 }
267 Phase::Closed => {
268 admission.violations.push(Violation {
269 kind: ViolationKind::DuplicateTerminal,
270 item_id: None,
271 });
272 }
273 }
274 self.phase = Phase::Closed;
275 }
276
277 fn admit_item_started(&mut self, item: &ThreadItem, admission: &mut Admission) {
278 if is_exempt(item) {
279 return;
280 }
281 if self.completed.contains(&item.id) {
282 admission.violations.push(Violation {
285 kind: ViolationKind::ItemReusedAfterCompleted,
286 item_id: Some(item.id.clone()),
287 });
288 return;
289 }
290 match self.phase {
291 Phase::Closed => admission.violations.push(Violation {
292 kind: ViolationKind::ItemAfterTurnEnd,
293 item_id: Some(item.id.clone()),
294 }),
295 Phase::Open => self.track_open(item),
296 Phase::Idle => {}
297 }
298 }
299
300 fn admit_item_updated(&mut self, item: &ThreadItem, admission: &mut Admission) {
301 if let Some(open) = self.open.iter_mut().find(|open| open.id == item.id) {
302 *open = item.clone();
303 } else if self.completed.contains(&item.id) && !is_exempt(item) {
304 admission.violations.push(Violation {
305 kind: ViolationKind::ItemReusedAfterCompleted,
306 item_id: Some(item.id.clone()),
307 });
308 }
309 }
310
311 fn admit_item_completed(&mut self, item: &ThreadItem, admission: &mut Admission) -> bool {
313 if self.completed.contains(&item.id) {
314 admission.violations.push(Violation {
315 kind: ViolationKind::DuplicateItemCompleted,
316 item_id: Some(item.id.clone()),
317 });
318 return self.policy != RepairPolicy::Repair;
319 }
320 let was_open = self.open.iter().any(|open| open.id == item.id);
321 self.open.retain(|open| open.id != item.id);
322 if !was_open && self.phase == Phase::Closed && !is_exempt(item) {
323 admission.violations.push(Violation {
324 kind: ViolationKind::ItemAfterTurnEnd,
325 item_id: Some(item.id.clone()),
326 });
327 }
328 self.remember_completed(&item.id);
329 true
330 }
331
332 fn track_open(&mut self, item: &ThreadItem) {
333 match self.open.iter_mut().find(|open| open.id == item.id) {
334 Some(open) => *open = item.clone(),
335 None => self.open.push(item.clone()),
336 }
337 }
338
339 fn remember_completed(&mut self, id: &str) {
340 if self.completed.insert(id.to_string()) {
341 self.completed_order.push_back(id.to_string());
342 if self.completed_order.len() > COMPLETED_ID_WINDOW
343 && let Some(oldest) = self.completed_order.pop_front()
344 {
345 let _forgotten = self.completed.remove(&oldest);
346 }
347 }
348 }
349}
350
351pub fn audit(events: &[ThreadEvent]) -> Vec<Violation> {
353 let mut guard = LifecycleGuard::new(RepairPolicy::Observe);
354 events.iter().flat_map(|event| guard.admit(event.clone()).violations).collect()
355}
356
357fn is_exempt(item: &ThreadItem) -> bool {
360 item.id.ends_with(EXEC_SESSION_OUTPUT_ITEM_SUFFIX)
361 || matches!(item.details, ThreadItemDetails::Harness(_) | ThreadItemDetails::Error(_))
362}
363
364fn close_item(mut item: ThreadItem) -> ThreadItem {
367 match &mut item.details {
368 ThreadItemDetails::ToolInvocation(invocation) => {
369 invocation.status = ToolCallStatus::Failed;
370 invocation.outcome = Some(ToolOutcome::Cancelled);
371 }
372 ThreadItemDetails::ToolOutput(output) => {
373 output.status = ToolCallStatus::Failed;
374 output.is_delta = None;
375 }
376 _ => {}
377 }
378 item
379}
380
381#[cfg(test)]
382mod tests;