cueloop 0.8.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
//! Query helpers for queue tasks.
//!
//! Purpose:
//! - Query helpers for queue tasks.
//!
//! Responsibilities:
//! - Locate tasks in active/done queues and determine runnable indices.
//! - Enforce runnable status and dependency rules for selection.
//! - Emit typed `QueueQueryError` for stable test assertions.
//!
//! Non-scope:
//! - Persisting queue data or mutating task fields.
//! - Normalizing IDs beyond trimming whitespace.
//!
//!
//! Usage:
//! - Used through the crate module tree or integration test harness.
//!
//! Invariants:
//! - Queues are already loaded and represent the source of truth.
//! - Task IDs are matched after trimming and are case-sensitive.
//! - Query errors wrap typed `QueueQueryError` variants for downcasting in tests.

use super::QueueQueryError;
use crate::contracts::{QueueFile, Task, TaskStatus};
use crate::timeutil;
use anyhow::Result;

pub fn find_task<'a>(queue: &'a QueueFile, task_id: &str) -> Option<&'a Task> {
    let needle = task_id.trim();
    if needle.is_empty() {
        return None;
    }
    queue.tasks.iter().find(|task| task.id.trim() == needle)
}

pub fn find_task_across<'a>(
    active: &'a QueueFile,
    done: Option<&'a QueueFile>,
    task_id: &str,
) -> Option<&'a Task> {
    find_task(active, task_id).or_else(|| done.and_then(|d| find_task(d, task_id)))
}

#[derive(Clone, Copy, Debug)]
pub struct RunnableSelectionOptions {
    pub include_draft: bool,
    pub prefer_doing: bool,
}

impl RunnableSelectionOptions {
    pub fn new(include_draft: bool, prefer_doing: bool) -> Self {
        Self {
            include_draft,
            prefer_doing,
        }
    }
}

/// Return the first todo task by file order (top-of-file wins).
pub fn next_todo_task(queue: &QueueFile) -> Option<&Task> {
    queue
        .tasks
        .iter()
        .find(|task| task.status == TaskStatus::Todo)
}

/// Check if a task's direct `depends_on` references are met.
///
/// Dependencies are met if `depends_on` is empty OR all referenced tasks exist and have `status == TaskStatus::Done` or `TaskStatus::Rejected`.
pub fn are_dependencies_met(task: &Task, active: &QueueFile, done: Option<&QueueFile>) -> bool {
    task.depends_on.iter().all(|dep_id| {
        matches!(
            find_task_across(active, done, dep_id),
            Some(t) if t.status == TaskStatus::Done || t.status == TaskStatus::Rejected
        )
    })
}

/// Return true when `candidate` participates as an execution blocker for `blocked_task_id`.
///
/// Only executable, non-terminal, non-self tasks block execution. Group tasks can carry relationship
/// metadata, but do not prevent work items from running.
pub fn is_active_execution_blocker(candidate: &Task, blocked_task_id: &str) -> bool {
    let blocked_task_id = blocked_task_id.trim();
    !blocked_task_id.is_empty()
        && candidate.id.trim() != blocked_task_id
        && candidate.is_executable_work_item()
        && candidate.status != TaskStatus::Done
        && candidate.status != TaskStatus::Rejected
        && candidate
            .blocks
            .iter()
            .any(|blocked_id| blocked_id.trim() == blocked_task_id)
}

/// Check if active reverse `blocks` relationships allow this task to run.
///
/// A task is blocked when another active execution-blocking task lists this task in `blocks`.
pub fn are_reverse_blocks_cleared(task: &Task, active: &QueueFile) -> bool {
    let task_id = task.id.trim();
    active
        .tasks
        .iter()
        .all(|candidate| !is_active_execution_blocker(candidate, task_id))
}

/// Check whether every scheduling blocker for a task has cleared.
pub fn are_task_blockers_cleared(
    task: &Task,
    active: &QueueFile,
    done: Option<&QueueFile>,
) -> bool {
    are_dependencies_met(task, active, done) && are_reverse_blocks_cleared(task, active)
}

/// Check if a task's scheduled_start is in the future.
///
/// Returns true if the task has a scheduled_start timestamp that is
/// in the future relative to the current time.
pub fn is_task_scheduled_for_future(task: &Task) -> bool {
    if let Some(ref scheduled) = task.scheduled_start
        && let Ok(scheduled_dt) = timeutil::parse_rfc3339(scheduled)
        && let Ok(now) = timeutil::now_utc_rfc3339()
        && let Ok(now_dt) = timeutil::parse_rfc3339(&now)
    {
        return scheduled_dt > now_dt;
    }
    false
}

/// Check if a task is runnable (executable, dependencies/blockers met, and scheduling satisfied).
///
/// A task is runnable if:
/// - It is an executable work item
/// - All `depends_on` tasks are Done or Rejected
/// - No active non-terminal task blocks it through reverse `blocks`
/// - The scheduled_start time has passed (or is not set)
pub fn is_task_runnable(task: &Task, active: &QueueFile, done: Option<&QueueFile>) -> bool {
    task.is_executable_work_item()
        && are_task_blockers_cleared(task, active, done)
        && !is_task_scheduled_for_future(task)
}

/// Return the first runnable task (Todo and dependencies met).
pub fn next_runnable_task<'a>(
    active: &'a QueueFile,
    done: Option<&'a QueueFile>,
) -> Option<&'a Task> {
    select_runnable_task_index(active, done, RunnableSelectionOptions::new(false, false))
        .and_then(|idx| active.tasks.get(idx))
}

/// Select the next runnable task index according to the provided options.
///
/// Order:
/// - If `prefer_doing` is true, prefer the first `Doing` task.
/// - Otherwise, choose the first runnable `Todo`.
/// - If `include_draft` is true and no runnable `Todo` exists, choose the first runnable `Draft`.
pub fn select_runnable_task_index(
    active: &QueueFile,
    done: Option<&QueueFile>,
    options: RunnableSelectionOptions,
) -> Option<usize> {
    if options.prefer_doing
        && let Some(idx) = active.tasks.iter().position(|task| {
            task.status == TaskStatus::Doing && is_task_runnable(task, active, done)
        })
    {
        return Some(idx);
    }

    if let Some(idx) = active
        .tasks
        .iter()
        .position(|task| task.status == TaskStatus::Todo && is_task_runnable(task, active, done))
    {
        return Some(idx);
    }

    if options.include_draft {
        return active.tasks.iter().position(|task| {
            task.status == TaskStatus::Draft && is_task_runnable(task, active, done)
        });
    }

    None
}

/// Select a runnable task index by target task id, with validation.
pub fn select_runnable_task_index_with_target(
    active: &QueueFile,
    done: Option<&QueueFile>,
    target_task_id: &str,
    operation: &str,
    options: RunnableSelectionOptions,
) -> Result<usize> {
    let needle = target_task_id.trim();
    if needle.is_empty() {
        return Err(QueueQueryError::MissingTargetTaskId {
            operation: operation.to_string(),
        }
        .into());
    }
    let idx = active
        .tasks
        .iter()
        .position(|task| task.id.trim() == needle)
        .ok_or_else(|| QueueQueryError::TargetTaskNotFound {
            operation: operation.to_string(),
            task_id: needle.to_string(),
        })?;
    let task = &active.tasks[idx];
    if !task.is_executable_work_item() {
        return Err(QueueQueryError::TargetTaskNotExecutable {
            operation: operation.to_string(),
            task_id: needle.to_string(),
            kind: task.kind,
        }
        .into());
    }

    match task.status {
        TaskStatus::Done | TaskStatus::Rejected => {
            return Err(QueueQueryError::TargetTaskNotRunnable {
                operation: operation.to_string(),
                task_id: needle.to_string(),
                status: task.status,
            }
            .into());
        }
        TaskStatus::Draft => {
            if !options.include_draft {
                return Err(QueueQueryError::TargetTaskDraftExcluded {
                    operation: operation.to_string(),
                    task_id: needle.to_string(),
                }
                .into());
            }
            if !are_task_blockers_cleared(task, active, done) {
                return Err(QueueQueryError::TargetTaskBlockedByUnmetDependencies {
                    operation: operation.to_string(),
                    task_id: needle.to_string(),
                }
                .into());
            }
            if is_task_scheduled_for_future(task) {
                return Err(QueueQueryError::TargetTaskScheduledForFuture {
                    operation: operation.to_string(),
                    task_id: needle.to_string(),
                    scheduled_start: task
                        .scheduled_start
                        .as_deref()
                        .unwrap_or("unknown")
                        .to_string(),
                }
                .into());
            }
        }
        TaskStatus::Todo => {
            if !are_task_blockers_cleared(task, active, done) {
                return Err(QueueQueryError::TargetTaskBlockedByUnmetDependencies {
                    operation: operation.to_string(),
                    task_id: needle.to_string(),
                }
                .into());
            }
            if is_task_scheduled_for_future(task) {
                return Err(QueueQueryError::TargetTaskScheduledForFuture {
                    operation: operation.to_string(),
                    task_id: needle.to_string(),
                    scheduled_start: task
                        .scheduled_start
                        .as_deref()
                        .unwrap_or("unknown")
                        .to_string(),
                }
                .into());
            }
        }
        TaskStatus::Doing => {
            if !are_task_blockers_cleared(task, active, done) {
                return Err(QueueQueryError::TargetTaskBlockedByUnmetDependencies {
                    operation: operation.to_string(),
                    task_id: needle.to_string(),
                }
                .into());
            }
            if is_task_scheduled_for_future(task) {
                return Err(QueueQueryError::TargetTaskScheduledForFuture {
                    operation: operation.to_string(),
                    task_id: needle.to_string(),
                    scheduled_start: task
                        .scheduled_start
                        .as_deref()
                        .unwrap_or("unknown")
                        .to_string(),
                }
                .into());
            }
        }
    }

    Ok(idx)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::contracts::{QueueFile, Task, TaskStatus};
    use std::collections::HashMap;
    use time::OffsetDateTime;

    fn make_task(id: &str, status: TaskStatus, scheduled_start: Option<&str>) -> Task {
        Task {
            id: id.to_string(),
            status,
            kind: Default::default(),
            title: format!("Task {}", id),
            description: None,
            priority: Default::default(),
            tags: vec![],
            scope: vec![],
            evidence: vec![],
            plan: vec![],
            notes: vec![],
            request: None,
            agent: None,
            created_at: Some("2026-01-18T00:00:00Z".to_string()),
            updated_at: Some("2026-01-18T00:00:00Z".to_string()),
            completed_at: None,
            started_at: None,
            scheduled_start: scheduled_start.map(|s| s.to_string()),
            estimated_minutes: None,
            actual_minutes: None,
            depends_on: vec![],
            blocks: vec![],
            relates_to: vec![],
            duplicates: None,
            custom_fields: HashMap::new(),
            parent_id: None,
        }
    }

    #[test]
    fn test_is_task_scheduled_for_future_with_future_date() {
        let future = (OffsetDateTime::now_utc() + time::Duration::hours(24))
            .format(&time::format_description::well_known::Rfc3339)
            .unwrap();
        let task = make_task("CL-0001", TaskStatus::Todo, Some(&future));
        assert!(is_task_scheduled_for_future(&task));
    }

    #[test]
    fn test_is_task_scheduled_for_future_with_past_date() {
        let past = (OffsetDateTime::now_utc() - time::Duration::hours(24))
            .format(&time::format_description::well_known::Rfc3339)
            .unwrap();
        let task = make_task("CL-0001", TaskStatus::Todo, Some(&past));
        assert!(!is_task_scheduled_for_future(&task));
    }

    #[test]
    fn test_is_task_scheduled_for_future_with_no_schedule() {
        let task = make_task("CL-0001", TaskStatus::Todo, None);
        assert!(!is_task_scheduled_for_future(&task));
    }

    #[test]
    fn test_is_task_runnable_with_schedule_and_dependencies() {
        let past = (OffsetDateTime::now_utc() - time::Duration::hours(24))
            .format(&time::format_description::well_known::Rfc3339)
            .unwrap();
        let task = make_task("CL-0001", TaskStatus::Todo, Some(&past));
        let active = QueueFile {
            version: 1,
            tasks: vec![task.clone()],
        };
        assert!(is_task_runnable(&task, &active, None));
    }

    #[test]
    fn test_is_task_not_runnable_with_future_schedule() {
        let future = (OffsetDateTime::now_utc() + time::Duration::hours(24))
            .format(&time::format_description::well_known::Rfc3339)
            .unwrap();
        let task = make_task("CL-0001", TaskStatus::Todo, Some(&future));
        let active = QueueFile {
            version: 1,
            tasks: vec![task.clone()],
        };
        assert!(!is_task_runnable(&task, &active, None));
    }

    #[test]
    fn test_select_runnable_task_index_skips_future_scheduled() {
        let future = (OffsetDateTime::now_utc() + time::Duration::hours(24))
            .format(&time::format_description::well_known::Rfc3339)
            .unwrap();
        let past = (OffsetDateTime::now_utc() - time::Duration::hours(24))
            .format(&time::format_description::well_known::Rfc3339)
            .unwrap();

        let tasks = vec![
            make_task("CL-0001", TaskStatus::Todo, Some(&future)), // scheduled future
            make_task("CL-0002", TaskStatus::Todo, Some(&past)),   // scheduled past (runnable)
        ];
        let active = QueueFile { version: 1, tasks };

        // Should select CL-0002 (index 1) since CL-0001 is scheduled for future
        let idx =
            select_runnable_task_index(&active, None, RunnableSelectionOptions::new(false, false));
        assert_eq!(idx, Some(1));
    }

    #[test]
    fn test_select_runnable_task_index_all_future_scheduled() {
        let future = (OffsetDateTime::now_utc() + time::Duration::hours(24))
            .format(&time::format_description::well_known::Rfc3339)
            .unwrap();

        let tasks = vec![
            make_task("CL-0001", TaskStatus::Todo, Some(&future)),
            make_task("CL-0002", TaskStatus::Todo, Some(&future)),
        ];
        let active = QueueFile { version: 1, tasks };

        // No runnable tasks
        let idx =
            select_runnable_task_index(&active, None, RunnableSelectionOptions::new(false, false));
        assert_eq!(idx, None);
    }
}