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
//! Purpose: Apply discovery follow-up proposals into the active task queue.
//!
//! Responsibilities:
//! - Parse `followups@v1` proposal documents from `.cueloop/cache/followups`.
//! - Validate proposal-local keys, dependency references, and source-task binding.
//! - Materialize proposal entries as normal queue tasks with allocated IDs.
//! - Persist validated queue updates and remove applied proposal artifacts.
//!
//! Scope:
//! - Queue-growth handoff only; task building, runner prompting, and task completion live elsewhere.
//! - Follow-up proposals never edit existing tasks or the done archive.
//!
//! Usage:
//! - CLI: `cueloop task followups apply --task <TASK_ID>`.
//! - Parallel integration: apply a worker-local proposal after archiving the completed task.
//!
//! Invariants/Assumptions:
//! - Proposal keys are local to one proposal document and must be unique after trimming.
//! - All `depends_on_keys` references must point at proposal-local keys.
//! - Source-task provenance uses the existing `request` and `relates_to` task fields.

use std::fmt;
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, anyhow, bail};
use serde::de::{self, Visitor};
use serde::{Deserialize, Serialize};

use crate::config::Resolved;
use crate::contracts::{QueueFile, Task, TaskKind, TaskPriority, TaskStatus};
use crate::queue::operations::{
    MaterializeInsertion, MaterializeTaskGraphOptions, MaterializedTaskSpec,
    apply_materialized_task_graph,
};
use crate::{jsonc, queue};

const FOLLOWUPS_VERSION: u8 = 1;
const FOLLOWUPS_SCHEMA_ID: &str = "followups@v1";

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FollowupProposalDocument {
    #[serde(deserialize_with = "deserialize_followups_version")]
    pub version: u8,
    pub source_task_id: String,
    pub tasks: Vec<FollowupTaskProposal>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FollowupTaskProposal {
    pub key: String,
    pub title: String,
    pub description: String,
    pub priority: TaskPriority,
    #[serde(default)]
    pub tags: Vec<String>,
    #[serde(default)]
    pub scope: Vec<String>,
    #[serde(default)]
    pub evidence: Vec<String>,
    #[serde(default)]
    pub plan: Vec<String>,
    #[serde(default)]
    pub depends_on_keys: Vec<String>,
    pub independence_rationale: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct FollowupApplyReport {
    pub version: u8,
    pub dry_run: bool,
    pub source_task_id: String,
    pub proposal_path: String,
    pub created_tasks: Vec<FollowupCreatedTask>,
}

#[derive(Debug)]
pub enum FollowupDryRunOutcome {
    Valid(FollowupApplyReport),
    Invalid(anyhow::Error),
}

#[derive(Debug, Clone, Serialize)]
pub struct FollowupCreatedTask {
    pub key: String,
    pub task_id: String,
    pub title: String,
    pub depends_on: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct FollowupApplyOptions<'a> {
    pub task_id: &'a str,
    pub input_path: Option<&'a Path>,
    pub dry_run: bool,
    pub create_undo: bool,
    pub remove_proposal: bool,
}

pub fn default_followups_path(repo_root: &Path, task_id: &str) -> PathBuf {
    repo_root
        .join(".cueloop")
        .join("cache")
        .join("followups")
        .join(format!("{}.json", task_id.trim()))
}

pub fn apply_default_followups_if_present(
    resolved: &Resolved,
    task_id: &str,
) -> Result<Option<FollowupApplyReport>> {
    apply_default_followups_if_present_with_removal(resolved, task_id, true)
}

pub fn apply_default_followups_if_present_with_removal(
    resolved: &Resolved,
    task_id: &str,
    remove_proposal: bool,
) -> Result<Option<FollowupApplyReport>> {
    let path = default_followups_path(&resolved.repo_root, task_id);
    if !path.exists() {
        return Ok(None);
    }

    apply_followups_file(
        resolved,
        &FollowupApplyOptions {
            task_id,
            input_path: Some(path.as_path()),
            dry_run: false,
            create_undo: false,
            remove_proposal,
        },
    )
    .map(Some)
}

pub fn remove_default_followups_proposal_if_present(repo_root: &Path, task_id: &str) -> Result<()> {
    remove_applied_proposal(&default_followups_path(repo_root, task_id))
}

pub fn dry_run_default_followups_if_present(
    resolved: &Resolved,
    task_id: &str,
) -> Result<Option<FollowupDryRunOutcome>> {
    let source_task_id = normalize_required(task_id, "task id")?;
    let path = default_followups_path(&resolved.repo_root, source_task_id);
    let raw = match fs::read_to_string(&path) {
        Ok(raw) => raw,
        Err(err) if err.kind() == ErrorKind::NotFound => return Ok(None),
        Err(err) => {
            return Err(err).with_context(|| format!("read follow-up proposal {}", path.display()));
        }
    };
    let mut active = queue::load_queue(&resolved.queue_path)
        .with_context(|| format!("load queue {}", resolved.queue_path.display()))?;
    let done = queue::load_queue_or_default(&resolved.done_path)
        .with_context(|| format!("load done {}", resolved.done_path.display()))?;
    let done_ref = queue::optional_done_queue(&done, &resolved.done_path);
    let now = crate::timeutil::now_utc_rfc3339()?;

    let document = match jsonc::parse_jsonc::<FollowupProposalDocument>(
        &raw,
        &format!("follow-up proposal {}", path.display()),
    ) {
        Ok(document) => document,
        Err(err) => return Ok(Some(FollowupDryRunOutcome::Invalid(err))),
    };

    match apply_followups_in_memory(
        &mut active,
        done_ref,
        &document,
        source_task_id,
        &path,
        &now,
        &resolved.id_prefix,
        resolved.id_width,
        resolved.queue_max_dependency_depth(),
        true,
    ) {
        Ok(report) => Ok(Some(FollowupDryRunOutcome::Valid(report))),
        Err(err) => Ok(Some(FollowupDryRunOutcome::Invalid(err))),
    }
}

pub fn apply_followups_file(
    resolved: &Resolved,
    opts: &FollowupApplyOptions<'_>,
) -> Result<FollowupApplyReport> {
    let source_task_id = normalize_required(opts.task_id, "task id")?;
    let path = opts
        .input_path
        .map(Path::to_path_buf)
        .unwrap_or_else(|| default_followups_path(&resolved.repo_root, source_task_id));
    let document = read_followups_document(&path)?;

    let mut active = queue::load_queue(&resolved.queue_path)
        .with_context(|| format!("load queue {}", resolved.queue_path.display()))?;
    let done = queue::load_queue_or_default(&resolved.done_path)
        .with_context(|| format!("load done {}", resolved.done_path.display()))?;
    let done_ref = queue::optional_done_queue(&done, &resolved.done_path);
    let now = crate::timeutil::now_utc_rfc3339()?;

    let report = apply_followups_in_memory(
        &mut active,
        done_ref,
        &document,
        source_task_id,
        &path,
        &now,
        &resolved.id_prefix,
        resolved.id_width,
        resolved.queue_max_dependency_depth(),
        opts.dry_run,
    )?;

    if opts.dry_run {
        return Ok(report);
    }

    if opts.create_undo {
        crate::undo::create_undo_snapshot(
            resolved,
            &format!(
                "task followups apply [{} task(s)]",
                report.created_tasks.len()
            ),
        )?;
    }
    queue::save_queue(&resolved.queue_path, &active)
        .with_context(|| format!("save queue {}", resolved.queue_path.display()))?;

    if opts.remove_proposal {
        remove_applied_proposal(&path)?;
    }

    Ok(report)
}

#[allow(clippy::too_many_arguments)]
pub fn apply_followups_in_memory(
    active: &mut QueueFile,
    done: Option<&QueueFile>,
    document: &FollowupProposalDocument,
    expected_source_task_id: &str,
    proposal_path: &Path,
    now_rfc3339: &str,
    id_prefix: &str,
    id_width: usize,
    max_dependency_depth: u8,
    dry_run: bool,
) -> Result<FollowupApplyReport> {
    let source_task_id = validate_document_header(document, expected_source_task_id)?;
    let source_task = find_source_task(active, done, source_task_id)?;
    let source_request = source_task.request.clone();

    validate_proposal_tasks(document)?;
    let specs = materialized_followup_specs(document, source_task_id, source_request)?;
    let report = apply_materialized_task_graph(
        active,
        done,
        &specs,
        &MaterializeTaskGraphOptions {
            now_rfc3339,
            id_prefix,
            id_width,
            max_dependency_depth,
            insertion: MaterializeInsertion::QueueDefaultTop,
            dry_run,
        },
    )?;
    let mut created = Vec::with_capacity(report.created_tasks.len());
    for spec in &specs {
        let key = normalize_required(&spec.local_key, "follow-up key")?.to_string();
        let task = report
            .created_tasks
            .iter()
            .find(|task| task.id == report.local_key_to_id[&key])
            .ok_or_else(|| anyhow!("missing materialized follow-up task for key {key}"))?;
        created.push(FollowupCreatedTask {
            key: key.clone(),
            task_id: task.id.clone(),
            title: task.title.clone(),
            depends_on: task.depends_on.clone(),
        });
    }

    Ok(FollowupApplyReport {
        version: FOLLOWUPS_VERSION,
        dry_run,
        source_task_id: source_task_id.to_string(),
        proposal_path: proposal_path.display().to_string(),
        created_tasks: created,
    })
}

fn read_followups_document(path: &Path) -> Result<FollowupProposalDocument> {
    let raw = fs::read_to_string(path)
        .with_context(|| format!("read follow-up proposal {}", path.display()))?;
    jsonc::parse_jsonc::<FollowupProposalDocument>(
        &raw,
        &format!("follow-up proposal {}", path.display()),
    )
}

fn deserialize_followups_version<'de, D>(deserializer: D) -> std::result::Result<u8, D::Error>
where
    D: serde::Deserializer<'de>,
{
    struct FollowupsVersionVisitor;

    impl<'de> Visitor<'de> for FollowupsVersionVisitor {
        type Value = u8;

        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(
                formatter,
                "numeric version {FOLLOWUPS_VERSION} or schema id \"{FOLLOWUPS_SCHEMA_ID}\""
            )
        }

        fn visit_u64<E>(self, value: u64) -> std::result::Result<Self::Value, E>
        where
            E: de::Error,
        {
            u8::try_from(value).map_err(|_| unsupported_followups_version_error::<E>(&value))
        }

        fn visit_i64<E>(self, value: i64) -> std::result::Result<Self::Value, E>
        where
            E: de::Error,
        {
            u8::try_from(value).map_err(|_| unsupported_followups_version_error::<E>(&value))
        }

        fn visit_str<E>(self, value: &str) -> std::result::Result<Self::Value, E>
        where
            E: de::Error,
        {
            match value.trim() {
                FOLLOWUPS_SCHEMA_ID => Ok(FOLLOWUPS_VERSION),
                other => Err(unsupported_followups_version_error::<E>(&other)),
            }
        }
    }

    deserializer.deserialize_any(FollowupsVersionVisitor)
}

fn unsupported_followups_version_error<E>(version: &dyn fmt::Display) -> E
where
    E: de::Error,
{
    E::custom(format!(
        "unsupported followups proposal version {version}; expected {FOLLOWUPS_VERSION} or \"{FOLLOWUPS_SCHEMA_ID}\""
    ))
}

fn validate_document_header<'a>(
    document: &'a FollowupProposalDocument,
    expected_source_task_id: &str,
) -> Result<&'a str> {
    if document.version != FOLLOWUPS_VERSION {
        bail!(
            "Unsupported followups proposal version: {}. CueLoop requires version {}.",
            document.version,
            FOLLOWUPS_VERSION
        );
    }

    let source_task_id = normalize_required(&document.source_task_id, "source_task_id")?;
    let expected = normalize_required(expected_source_task_id, "task id")?;
    if source_task_id != expected {
        bail!(
            "follow-up proposal source_task_id {} does not match --task {}",
            source_task_id,
            expected
        );
    }

    Ok(source_task_id)
}

fn materialized_followup_specs(
    document: &FollowupProposalDocument,
    source_task_id: &str,
    source_request: Option<String>,
) -> Result<Vec<MaterializedTaskSpec>> {
    document
        .tasks
        .iter()
        .map(|proposal| {
            let key = normalize_required(&proposal.key, "follow-up key")?.to_string();
            Ok(MaterializedTaskSpec {
                local_key: key.clone(),
                title: normalize_required(&proposal.title, "follow-up title")?.to_string(),
                description: Some(
                    normalize_required(&proposal.description, "follow-up description")?.to_string(),
                ),
                priority: proposal.priority,
                status: TaskStatus::Todo,
                kind: TaskKind::WorkItem,
                tags: proposal.tags.clone(),
                scope: proposal.scope.clone(),
                evidence: proposal.evidence.clone(),
                plan: proposal.plan.clone(),
                notes: vec![format!("Generated from follow-up proposal key {key}")],
                request: source_request.clone(),
                relates_to: vec![source_task_id.to_string()],
                blocks: vec![],
                duplicates: None,
                custom_fields: std::collections::HashMap::new(),
                agent: None,
                parent_local_key: None,
                parent_task_id: None,
                depends_on_local_keys: proposal.depends_on_keys.clone(),
                depends_on_task_ids: vec![],
                estimated_minutes: None,
            })
        })
        .collect()
}

fn validate_proposal_tasks(document: &FollowupProposalDocument) -> Result<()> {
    let mut keys = std::collections::HashSet::with_capacity(document.tasks.len());
    for proposal in &document.tasks {
        let key = normalize_required(&proposal.key, "follow-up key")?;
        if !keys.insert(key.to_string()) {
            bail!("duplicate follow-up proposal key: {key}");
        }
        normalize_required(&proposal.title, "follow-up title")?;
        normalize_required(&proposal.description, "follow-up description")?;
        normalize_required(
            &proposal.independence_rationale,
            "follow-up independence_rationale",
        )?;
    }
    Ok(())
}

fn find_source_task<'a>(
    active: &'a QueueFile,
    done: Option<&'a QueueFile>,
    source_task_id: &str,
) -> Result<&'a Task> {
    active
        .tasks
        .iter()
        .find(|task| task.id.trim() == source_task_id)
        .or_else(|| {
            done.and_then(|done| {
                done.tasks
                    .iter()
                    .find(|task| task.id.trim() == source_task_id)
            })
        })
        .ok_or_else(|| {
            anyhow!(
                "{}",
                crate::error_messages::task_not_found_in_queue_or_done(source_task_id)
            )
        })
}

fn normalize_required<'a>(value: &'a str, label: &str) -> Result<&'a str> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        bail!("{label} must be non-empty");
    }
    Ok(trimmed)
}

fn remove_applied_proposal(path: &Path) -> Result<()> {
    match fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
        Err(err) => Err(err).with_context(|| format!("remove applied proposal {}", path.display())),
    }
}