cueloop 0.6.0

A Rust CLI for managing AI agent loops with a structured JSON task queue
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! Operator-facing resume decision model and session-resolution helpers.
//!
//! Purpose:
//! - Operator-facing resume decision model and session-resolution helpers.
//!
//! Responsibilities:
//! - Convert low-level session validation into explicit resume/fresh/refusal decisions.
//! - Preserve machine-readable decision state for CLI/app surfaces.
//! - Apply session-cache mutations only when the caller is executing a real run.
//!
//! Not handled here:
//! - Session persistence IO details.
//! - Queue/task execution.
//! - Continue-session runner resumption.
//!
//!
//! Usage:
//! - Used through the crate module tree or integration test harness.
//!
//! Invariants/assumptions:
//! - Timed-out sessions always require explicit confirmation.
//! - Non-interactive prompt-required cases refuse instead of guessing.
//! - Preview callers must not mutate session cache state.

use std::io::IsTerminal;
use std::path::Path;

use anyhow::Result;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::contracts::{BlockingState, QueueFile};

use super::{
    SessionCacheCorruption, SessionValidationResult, check_session, clear_session,
    prompt_session_recovery, prompt_session_recovery_timeout, quarantine_session_cache,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ResumeStatus {
    ResumingSameSession,
    FallingBackToFreshInvocation,
    RefusingToResume,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ResumeScope {
    RunSession,
    ContinueSession,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ResumeReason {
    NoSession,
    SessionValid,
    SessionTimedOutConfirmed,
    SessionStale,
    SessionDeclined,
    ResumeConfirmationRequired,
    SessionTimedOutRequiresConfirmation,
    ExplicitTaskSelectionOverridesSession,
    ResumeTargetMissing,
    ResumeTargetTerminal,
    RunnerSessionInvalid,
    MissingRunnerSessionId,
    SessionCacheCorrupt,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ResumeDecision {
    pub status: ResumeStatus,
    pub scope: ResumeScope,
    pub reason: ResumeReason,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub task_id: Option<String>,
    pub message: String,
    pub detail: String,
}

impl ResumeDecision {
    pub fn blocking_state(&self) -> Option<BlockingState> {
        if self.status != ResumeStatus::RefusingToResume {
            return None;
        }

        let reason = match self.reason {
            ResumeReason::RunnerSessionInvalid => "runner_session_invalid",
            ResumeReason::MissingRunnerSessionId => "missing_runner_session_id",
            ResumeReason::ResumeConfirmationRequired => "resume_confirmation_required",
            ResumeReason::SessionTimedOutRequiresConfirmation => {
                "session_timed_out_requires_confirmation"
            }
            ResumeReason::SessionCacheCorrupt => "session_cache_corrupt",
            _ => return None,
        };

        Some(
            BlockingState::runner_recovery(
                match self.scope {
                    ResumeScope::RunSession => "run_session",
                    ResumeScope::ContinueSession => "continue_session",
                },
                reason,
                self.task_id.clone(),
                self.message.clone(),
                self.detail.clone(),
            )
            .with_observed_at(crate::timeutil::now_utc_rfc3339_or_fallback()),
        )
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResumeBehavior {
    Prompt,
    AutoResume,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResumeDecisionMode {
    Preview,
    Execute,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResumeResolution {
    pub resume_task_id: Option<String>,
    pub completed_count: u32,
    pub decision: Option<ResumeDecision>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RunSessionDecisionOptions<'a> {
    pub timeout_hours: Option<u64>,
    pub behavior: ResumeBehavior,
    pub non_interactive: bool,
    pub explicit_task_id: Option<&'a str>,
    pub announce_missing_session: bool,
    pub mode: ResumeDecisionMode,
}

pub fn resolve_run_session_decision(
    cache_dir: &Path,
    queue_file: &QueueFile,
    options: RunSessionDecisionOptions<'_>,
) -> Result<ResumeResolution> {
    let validation = check_session(cache_dir, queue_file, options.timeout_hours)?;
    let can_prompt = !options.non_interactive && std::io::stdin().is_terminal();
    let timeout_threshold = options
        .timeout_hours
        .unwrap_or(crate::constants::timeouts::DEFAULT_SESSION_TIMEOUT_HOURS);

    let resolution = match validation {
        SessionValidationResult::NoSession => ResumeResolution {
            resume_task_id: None,
            completed_count: 0,
            decision: options.announce_missing_session.then(|| ResumeDecision {
                status: ResumeStatus::FallingBackToFreshInvocation,
                scope: ResumeScope::RunSession,
                reason: ResumeReason::NoSession,
                task_id: None,
                message: "Resume: no interrupted session was found; starting a fresh run."
                    .to_string(),
                detail: "No persisted session state exists under .cueloop/cache/session.jsonc."
                    .to_string(),
            }),
        },
        SessionValidationResult::Valid(session) => {
            if let Some(explicit_task_id) = options.explicit_task_id
                && explicit_task_id.trim() != session.task_id
            {
                ResumeResolution {
                    resume_task_id: None,
                    completed_count: 0,
                    decision: Some(ResumeDecision {
                        status: ResumeStatus::FallingBackToFreshInvocation,
                        scope: ResumeScope::RunSession,
                        reason: ResumeReason::ExplicitTaskSelectionOverridesSession,
                        task_id: Some(session.task_id.clone()),
                        message: format!(
                            "Resume: starting fresh because task {explicit_task_id} was explicitly selected instead of interrupted task {}.",
                            session.task_id
                        ),
                        detail: format!(
                            "Saved session belongs to {}, so CueLoop will honor the explicit task selection.",
                            session.task_id
                        ),
                    }),
                }
            } else {
                match options.behavior {
                    ResumeBehavior::AutoResume => ResumeResolution {
                        resume_task_id: Some(session.task_id.clone()),
                        completed_count: session.tasks_completed_in_loop,
                        decision: Some(ResumeDecision {
                            status: ResumeStatus::ResumingSameSession,
                            scope: ResumeScope::RunSession,
                            reason: ResumeReason::SessionValid,
                            task_id: Some(session.task_id.clone()),
                            message: format!(
                                "Resume: continuing the interrupted session for task {}.",
                                session.task_id
                            ),
                            detail: format!(
                                "Saved session is current and will resume from phase {} with {} completed loop task(s).",
                                session.current_phase, session.tasks_completed_in_loop
                            ),
                        }),
                    },
                    ResumeBehavior::Prompt if !can_prompt => ResumeResolution {
                        resume_task_id: None,
                        completed_count: 0,
                        decision: Some(ResumeDecision {
                            status: ResumeStatus::RefusingToResume,
                            scope: ResumeScope::RunSession,
                            reason: ResumeReason::ResumeConfirmationRequired,
                            task_id: Some(session.task_id.clone()),
                            message: format!(
                                "Resume: refusing to guess because task {} has an interrupted session and confirmation is unavailable.",
                                session.task_id
                            ),
                            detail: "Re-run interactively to choose resume vs fresh, or pass --resume to continue automatically when safe.".to_string(),
                        }),
                    },
                    ResumeBehavior::Prompt => {
                        if prompt_session_recovery(&session, options.non_interactive)? {
                            ResumeResolution {
                                resume_task_id: Some(session.task_id.clone()),
                                completed_count: session.tasks_completed_in_loop,
                                decision: Some(ResumeDecision {
                                    status: ResumeStatus::ResumingSameSession,
                                    scope: ResumeScope::RunSession,
                                    reason: ResumeReason::SessionValid,
                                    task_id: Some(session.task_id.clone()),
                                    message: format!(
                                        "Resume: continuing the interrupted session for task {}.",
                                        session.task_id
                                    ),
                                    detail: format!(
                                        "Saved session is current and will resume from phase {} with {} completed loop task(s).",
                                        session.current_phase, session.tasks_completed_in_loop
                                    ),
                                }),
                            }
                        } else {
                            maybe_clear_session(cache_dir, options.mode)?;
                            ResumeResolution {
                                resume_task_id: None,
                                completed_count: 0,
                                decision: Some(ResumeDecision {
                                    status: ResumeStatus::FallingBackToFreshInvocation,
                                    scope: ResumeScope::RunSession,
                                    reason: ResumeReason::SessionDeclined,
                                    task_id: Some(session.task_id.clone()),
                                    message: format!(
                                        "Resume: starting fresh after declining the interrupted session for task {}.",
                                        session.task_id
                                    ),
                                    detail: "The saved session remains readable, but CueLoop will begin a new invocation instead of reusing it.".to_string(),
                                }),
                            }
                        }
                    }
                }
            }
        }
        SessionValidationResult::CorruptCache(corruption) => corrupt_cache_resolution(
            cache_dir,
            options.mode,
            options.behavior,
            can_prompt,
            corruption,
        )?,
        SessionValidationResult::Stale { reason } => fresh_start_resolution(
            cache_dir,
            options.mode,
            ResumeReason::SessionStale,
            None,
            "Resume: starting fresh because the saved session is stale.".to_string(),
            reason,
        )?,
        SessionValidationResult::Timeout { hours, session } => {
            if !can_prompt {
                ResumeResolution {
                    resume_task_id: None,
                    completed_count: 0,
                    decision: Some(ResumeDecision {
                        status: ResumeStatus::RefusingToResume,
                        scope: ResumeScope::RunSession,
                        reason: ResumeReason::SessionTimedOutRequiresConfirmation,
                        task_id: Some(session.task_id.clone()),
                        message: format!(
                            "Resume: refusing to continue timed-out session {} without explicit confirmation.",
                            session.task_id
                        ),
                        detail: format!(
                            "The saved session is {hours} hour(s) old, exceeding the configured {timeout_threshold}-hour safety threshold."
                        ),
                    }),
                }
            } else if prompt_session_recovery_timeout(
                &session,
                hours,
                timeout_threshold,
                options.non_interactive,
            )? {
                ResumeResolution {
                    resume_task_id: Some(session.task_id.clone()),
                    completed_count: session.tasks_completed_in_loop,
                    decision: Some(ResumeDecision {
                        status: ResumeStatus::ResumingSameSession,
                        scope: ResumeScope::RunSession,
                        reason: ResumeReason::SessionTimedOutConfirmed,
                        task_id: Some(session.task_id.clone()),
                        message: format!(
                            "Resume: continuing timed-out session {} after explicit confirmation.",
                            session.task_id
                        ),
                        detail: format!(
                            "The saved session is {hours} hour(s) old, above the configured {timeout_threshold}-hour threshold."
                        ),
                    }),
                }
            } else {
                fresh_start_resolution(
                    cache_dir,
                    options.mode,
                    ResumeReason::SessionDeclined,
                    Some(session.task_id.clone()),
                    format!(
                        "Resume: starting fresh after declining timed-out session {}.",
                        session.task_id
                    ),
                    format!(
                        "The saved session is {hours} hour(s) old, above the configured {timeout_threshold}-hour threshold."
                    ),
                )?
            }
        }
    };

    Ok(resolution)
}

fn corrupt_cache_resolution(
    cache_dir: &Path,
    mode: ResumeDecisionMode,
    behavior: ResumeBehavior,
    can_prompt: bool,
    corruption: SessionCacheCorruption,
) -> Result<ResumeResolution> {
    let quarantine_detail = if matches!(mode, ResumeDecisionMode::Execute) {
        match quarantine_session_cache(cache_dir)? {
            Some(result) => format!(
                " The corrupt cache was quarantined from {} to {}.",
                result.original_path.display(),
                result.quarantine_path.display()
            ),
            None => " No cache file remained to quarantine.".to_string(),
        }
    } else {
        " Preview mode left the corrupt cache in place.".to_string()
    };

    if matches!(behavior, ResumeBehavior::AutoResume) && matches!(mode, ResumeDecisionMode::Execute)
    {
        return Ok(ResumeResolution {
            resume_task_id: None,
            completed_count: 0,
            decision: Some(ResumeDecision {
                status: ResumeStatus::FallingBackToFreshInvocation,
                scope: ResumeScope::RunSession,
                reason: ResumeReason::SessionCacheCorrupt,
                task_id: None,
                message: "Resume: starting fresh because the saved session cache is corrupt or unreadable."
                    .to_string(),
                detail: format!(
                    "CueLoop could not read {}: {}.{}",
                    corruption.path.display(),
                    corruption.diagnostic,
                    quarantine_detail
                ),
            }),
        });
    }

    let next_step = if can_prompt {
        "Re-run with --resume only after inspecting the quarantined cache, or remove the bad cache and start fresh."
    } else {
        "Remove or quarantine the bad session cache, then re-run; use an interactive terminal or --resume only when the saved session is known safe."
    };

    Ok(ResumeResolution {
        resume_task_id: None,
        completed_count: 0,
        decision: Some(ResumeDecision {
            status: ResumeStatus::RefusingToResume,
            scope: ResumeScope::RunSession,
            reason: ResumeReason::SessionCacheCorrupt,
            task_id: None,
            message: "Resume: refusing to guess because the saved session cache is corrupt or unreadable."
                .to_string(),
            detail: format!(
                "CueLoop could not read {}: {}.{} {next_step}",
                corruption.path.display(),
                corruption.diagnostic,
                quarantine_detail
            ),
        }),
    })
}

fn maybe_clear_session(cache_dir: &Path, mode: ResumeDecisionMode) -> Result<()> {
    if matches!(mode, ResumeDecisionMode::Execute) {
        clear_session(cache_dir)?;
    }
    Ok(())
}

fn fresh_start_resolution(
    cache_dir: &Path,
    mode: ResumeDecisionMode,
    reason: ResumeReason,
    task_id: Option<String>,
    message: String,
    detail: String,
) -> Result<ResumeResolution> {
    maybe_clear_session(cache_dir, mode)?;
    Ok(ResumeResolution {
        resume_task_id: None,
        completed_count: 0,
        decision: Some(ResumeDecision {
            status: ResumeStatus::FallingBackToFreshInvocation,
            scope: ResumeScope::RunSession,
            reason,
            task_id,
            message,
            detail,
        }),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::contracts::{QueueFile, SessionState, Task, TaskPriority, TaskStatus};
    use crate::session::{save_session, session_exists};

    fn test_task(id: &str, status: TaskStatus) -> Task {
        Task {
            id: id.to_string(),
            status,
            kind: Default::default(),
            title: "Test".to_string(),
            description: None,
            priority: TaskPriority::Medium,
            tags: vec![],
            scope: vec![],
            evidence: vec![],
            plan: vec![],
            notes: vec![],
            request: None,
            agent: None,
            created_at: None,
            updated_at: None,
            completed_at: None,
            started_at: None,
            scheduled_start: None,
            depends_on: vec![],
            blocks: vec![],
            relates_to: vec![],
            duplicates: None,
            custom_fields: Default::default(),
            parent_id: None,
            estimated_minutes: None,
            actual_minutes: None,
        }
    }

    fn test_session(task_id: &str) -> SessionState {
        SessionState::new(
            "test-session-id".to_string(),
            task_id.to_string(),
            crate::timeutil::now_utc_rfc3339_or_fallback(),
            1,
            crate::contracts::Runner::Claude,
            "sonnet".to_string(),
            0,
            None,
            None,
        )
    }

    #[test]
    fn fresh_start_resolution_preview_keeps_session_cache() {
        let temp_dir = tempfile::TempDir::new().expect("tempdir");
        let session = test_session("RQ-0001");
        save_session(temp_dir.path(), &session).expect("save session");

        let resolution = fresh_start_resolution(
            temp_dir.path(),
            ResumeDecisionMode::Preview,
            ResumeReason::SessionDeclined,
            Some("RQ-0001".to_string()),
            "preview".to_string(),
            "detail".to_string(),
        )
        .expect("resolution");

        assert!(session_exists(temp_dir.path()));
        assert_eq!(
            resolution.decision.expect("decision").reason,
            ResumeReason::SessionDeclined
        );
    }

    #[test]
    fn fresh_start_resolution_execute_clears_session_cache() {
        let temp_dir = tempfile::TempDir::new().expect("tempdir");
        let session = test_session("RQ-0001");
        save_session(temp_dir.path(), &session).expect("save session");

        fresh_start_resolution(
            temp_dir.path(),
            ResumeDecisionMode::Execute,
            ResumeReason::SessionDeclined,
            Some("RQ-0001".to_string()),
            "execute".to_string(),
            "detail".to_string(),
        )
        .expect("resolution");

        assert!(!session_exists(temp_dir.path()));
    }

    #[test]
    fn maybe_clear_session_preview_is_noop() {
        let temp_dir = tempfile::TempDir::new().expect("tempdir");
        let session = test_session("RQ-0001");
        save_session(temp_dir.path(), &session).expect("save session");

        maybe_clear_session(temp_dir.path(), ResumeDecisionMode::Preview).expect("clear preview");

        assert!(session_exists(temp_dir.path()));
    }

    #[test]
    fn resolve_run_session_decision_announces_missing_session_when_requested() {
        let temp_dir = tempfile::TempDir::new().expect("tempdir");
        let queue = QueueFile {
            version: 1,
            tasks: vec![test_task("RQ-0001", TaskStatus::Todo)],
        };

        let resolution = resolve_run_session_decision(
            temp_dir.path(),
            &queue,
            RunSessionDecisionOptions {
                timeout_hours: Some(24),
                behavior: ResumeBehavior::AutoResume,
                non_interactive: true,
                explicit_task_id: None,
                announce_missing_session: true,
                mode: ResumeDecisionMode::Execute,
            },
        )
        .expect("resolution");

        let decision = resolution.decision.expect("decision");
        assert_eq!(decision.status, ResumeStatus::FallingBackToFreshInvocation);
        assert_eq!(decision.reason, ResumeReason::NoSession);
    }
}