cueloop 0.5.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
//! Automatic startup health checks with auto-fix and migration prompts.
//!
//! Purpose:
//! - Automatic startup health checks with auto-fix and migration prompts.
//!
//! Responsibilities:
//! - Run lightweight health checks on CueLoop startup for key commands.
//! - Auto-update README.md when embedded template is newer (no prompt).
//! - Detect and prompt for config migrations (deprecated keys, unknown keys).
//! - Support --auto-fix flag to auto-approve all migrations without prompting.
//! - Support --no-sanity-checks flag to skip sanity health checks.
//! - Support non-interactive mode to skip all prompts (for CI/piped runs).
//!
//! Not handled here:
//! - Deep validation (git, runners, queue structure) - that's `cueloop doctor`.
//! - GUI app flows.
//! - Network connectivity checks.
//!
//!
//! Usage:
//! - Used through the crate module tree or integration test harness.
//!
//! Invariants/assumptions:
//! - Sanity checks are fast and lightweight.
//! - README auto-update is automatic (users shouldn't edit this file manually).
//! - Config migrations require user confirmation unless --auto-fix is set.
//! - Unknown config keys prompt for remove/keep/rename action.
//! - Prompts require both stdin and stdout to be TTYs.
//! - If non_interactive is true, all prompts are skipped (use --auto-fix to apply changes).
//! - README sync may also be invoked directly by command routing for agent-facing commands.
//! - Read-only startup sanity mode preserves diagnostics while suppressing all writes/prompts.

mod migrations;
mod readme;
mod unknown_keys;

use crate::config::Resolved;
use crate::migration::MigrationContext;
use crate::outpututil;
use anyhow::{Context, Result};
use std::io::{self, IsTerminal, Write};

// Re-export submodule functions for internal use
pub(crate) use migrations::check_and_handle_migrations;
pub(crate) use readme::check_and_update_readme;
pub(crate) use unknown_keys::check_unknown_keys;

/// Whether a command should refresh `.cueloop/README.md` before execution.
///
/// This is intentionally broader than full sanity checks so agent-facing commands
/// always get current project guidance even when migration checks are not run.
pub fn should_refresh_readme_for_command(command: &crate::cli::Command) -> bool {
    use crate::cli;
    matches!(
        command,
        cli::Command::Run(_)
            | cli::Command::Task(_)
            | cli::Command::Scan(_)
            | cli::Command::Prompt(_)
            | cli::Command::Prd(_)
            | cli::Command::Tutorial(_)
    )
}

/// Refresh `.cueloop/README.md` if missing/outdated.
///
/// Returns a user-facing status message when a change was applied.
pub fn refresh_readme_if_needed(resolved: &Resolved) -> Result<Option<String>> {
    check_and_update_readme(resolved)
}

/// Startup sanity execution mode for a command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StartupSanityMode {
    /// Skip startup sanity checks.
    None,
    /// Run startup sanity checks in inspect-only mode (no writes or prompts).
    ReadOnly,
    /// Run startup sanity checks with writes/prompts allowed by CLI flags.
    Mutating,
}

/// Whether startup sanity writes are permitted.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum SanityWritePolicy {
    /// Sanity checks may apply writes based on other options.
    #[default]
    AllowWrites,
    /// Sanity checks must remain read-only.
    ReadOnly,
}

/// Options for controlling sanity check behavior.
#[derive(Debug, Clone, Default)]
pub struct SanityOptions {
    /// Auto-approve all fixes without prompting.
    pub auto_fix: bool,
    /// Skip all sanity checks.
    pub skip: bool,
    /// Skip interactive prompts even if running in a TTY.
    pub non_interactive: bool,
    /// Write policy for sanity checks.
    pub write_policy: SanityWritePolicy,
}

impl SanityOptions {
    /// Whether sanity checks may apply filesystem writes.
    pub fn allows_writes(&self) -> bool {
        matches!(self.write_policy, SanityWritePolicy::AllowWrites)
    }

    /// Check if we can prompt the user for input.
    pub fn can_prompt(&self) -> bool {
        self.allows_writes() && !self.non_interactive && is_tty()
    }
}

/// Result of running sanity checks.
#[derive(Debug, Clone, Default)]
pub struct SanityResult {
    /// Fixes that were automatically applied.
    pub auto_fixes: Vec<String>,
    /// Issues that need user attention (could not be auto-fixed).
    pub needs_attention: Vec<SanityIssue>,
}

/// A single issue found during sanity checks.
#[derive(Debug, Clone)]
pub struct SanityIssue {
    /// Severity of the issue.
    pub severity: IssueSeverity,
    /// Human-readable description of the issue.
    pub message: String,
    /// Whether a fix is available for this issue.
    pub fix_available: bool,
}

/// Severity level for sanity issues.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IssueSeverity {
    /// Warning - operation can continue.
    Warning,
    /// Error - operation should not proceed.
    Error,
}

/// Run all sanity checks and apply fixes based on options.
pub fn run_sanity_checks(resolved: &Resolved, options: &SanityOptions) -> Result<SanityResult> {
    if options.skip {
        log::debug!("Sanity checks skipped via --no-sanity-checks");
        return Ok(SanityResult::default());
    }

    log::debug!("Running sanity checks...");
    let mut result = SanityResult::default();
    let effective_auto_fix = options.auto_fix && options.allows_writes();
    let effective_non_interactive = options.non_interactive || !options.allows_writes();

    // Check 1: README health
    if options.allows_writes() {
        match check_and_update_readme(resolved) {
            Ok(Some(fix_msg)) => {
                result.auto_fixes.push(fix_msg);
            }
            Ok(None) => {
                log::debug!("README is current");
            }
            Err(e) => {
                return Err(e).context("check/update .cueloop/README.md");
            }
        }
    } else {
        match readme::check_readme_without_update(resolved) {
            Ok(Some(message)) => {
                result.needs_attention.push(SanityIssue {
                    severity: IssueSeverity::Warning,
                    message,
                    fix_available: true,
                });
            }
            Ok(None) => {
                log::debug!("README is current");
            }
            Err(e) => {
                return Err(e).context("check/read-only .cueloop/README.md");
            }
        }
    }

    // Check 2: Config migrations (prompt unless auto_fix)
    let mut ctx = match MigrationContext::from_resolved(resolved) {
        Ok(ctx) => ctx,
        Err(e) => {
            log::warn!("Failed to create migration context: {}", e);
            result.needs_attention.push(SanityIssue {
                severity: IssueSeverity::Warning,
                message: format!("Config migration check failed: {}", e),
                fix_available: false,
            });
            return Ok(result);
        }
    };

    match check_and_handle_migrations(
        &mut ctx,
        effective_auto_fix,
        effective_non_interactive,
        is_tty,
        prompt_yes_no,
    ) {
        Ok(migration_fixes) => {
            result.auto_fixes.extend(migration_fixes);
        }
        Err(e) => {
            log::warn!("Migration handling failed: {}", e);
            result.needs_attention.push(SanityIssue {
                severity: IssueSeverity::Warning,
                message: format!("Migration handling failed: {}", e),
                fix_available: false,
            });
        }
    }

    // Check 3: Unknown config keys
    match check_unknown_keys(
        resolved,
        effective_auto_fix,
        effective_non_interactive,
        is_tty,
    ) {
        Ok(unknown_fixes) => {
            result.auto_fixes.extend(unknown_fixes);
        }
        Err(e) => {
            log::warn!("Unknown key check failed: {}", e);
            result.needs_attention.push(SanityIssue {
                severity: IssueSeverity::Warning,
                message: format!("Unknown key check failed: {}", e),
                fix_available: false,
            });
        }
    }

    // Report results
    if !result.auto_fixes.is_empty() {
        log::info!("Applied {} automatic fix(es):", result.auto_fixes.len());
        for fix in &result.auto_fixes {
            outpututil::log_success(&format!("  - {}", fix));
        }
    }

    if !result.needs_attention.is_empty() {
        log::warn!(
            "Found {} issue(s) needing attention:",
            result.needs_attention.len()
        );
        for issue in &result.needs_attention {
            match issue.severity {
                IssueSeverity::Warning => outpututil::log_warn(&format!("  - {}", issue.message)),
                IssueSeverity::Error => outpututil::log_error(&format!("  - {}", issue.message)),
            }
        }
    }

    log::debug!("Sanity checks complete");
    Ok(result)
}

/// Prompt user with Y/n question, returns true if yes.
fn prompt_yes_no(message: &str, default_yes: bool) -> Result<bool> {
    let prompt = if default_yes { "[Y/n]" } else { "[y/N]" };
    print!("{} {}: ", message, prompt);
    io::stdout().flush()?;

    let mut input = String::new();
    io::stdin().read_line(&mut input)?;

    let trimmed = input.trim().to_lowercase();
    if trimmed.is_empty() {
        Ok(default_yes)
    } else {
        Ok(trimmed == "y" || trimmed == "yes")
    }
}

/// Check if both stdin and stdout are TTYs (interactive terminal).
fn is_tty() -> bool {
    io::stdin().is_terminal() && io::stdout().is_terminal()
}

/// Resolve startup sanity mode for a given command.
pub fn startup_sanity_mode(command: &crate::cli::Command) -> StartupSanityMode {
    use crate::cli;

    match command {
        cli::Command::Run(_) => StartupSanityMode::Mutating,
        cli::Command::Queue(_) => StartupSanityMode::None,
        cli::Command::Doctor(_) => StartupSanityMode::None,
        _ => StartupSanityMode::None,
    }
}

/// Check if sanity checks should run for a given command.
pub fn should_run_sanity_checks(command: &crate::cli::Command) -> bool {
    !matches!(startup_sanity_mode(command), StartupSanityMode::None)
}

/// Report sanity check results to the user.
pub fn report_sanity_results(result: &SanityResult, auto_fix: bool) -> bool {
    if !result.needs_attention.is_empty() && !auto_fix {
        let has_errors = result
            .needs_attention
            .iter()
            .any(|i| i.severity == IssueSeverity::Error);

        if has_errors {
            log::error!("Sanity checks found errors that need to be resolved.");
            log::info!(
                "Run with --auto-fix to automatically fix issues, or resolve them manually."
            );
            return false;
        }
    }

    true
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;

    #[test]
    fn sanity_options_can_prompt_non_interactive_disables_prompts() {
        let opts = SanityOptions {
            non_interactive: true,
            ..Default::default()
        };
        assert!(!opts.can_prompt());
    }

    #[test]
    fn sanity_options_default_matches_current_tty_state() {
        let opts = SanityOptions::default();
        assert_eq!(opts.can_prompt(), is_tty());
    }

    #[test]
    fn sanity_options_explicit_non_interactive_overrides() {
        let opts = SanityOptions {
            non_interactive: true,
            auto_fix: false,
            skip: false,
            write_policy: SanityWritePolicy::AllowWrites,
        };
        assert!(!opts.can_prompt());
    }

    #[test]
    fn sanity_options_read_only_disables_prompts() {
        let opts = SanityOptions {
            non_interactive: false,
            auto_fix: false,
            skip: false,
            write_policy: SanityWritePolicy::ReadOnly,
        };
        assert!(!opts.can_prompt());
        assert!(!opts.allows_writes());
    }

    #[test]
    fn should_refresh_readme_for_agent_facing_commands() {
        let cli = crate::cli::Cli::parse_from(["cueloop", "task", "build", "x"]);
        assert!(should_refresh_readme_for_command(&cli.command));

        let cli = crate::cli::Cli::parse_from(["cueloop", "scan", "--focus", "x"]);
        assert!(should_refresh_readme_for_command(&cli.command));

        let cli = crate::cli::Cli::parse_from(["cueloop", "run", "one", "--id", "RQ-0001"]);
        assert!(should_refresh_readme_for_command(&cli.command));

        let cli =
            crate::cli::Cli::parse_from(["cueloop", "prompt", "task-builder", "--request", "x"]);
        assert!(should_refresh_readme_for_command(&cli.command));
    }

    #[test]
    fn should_not_refresh_readme_for_non_agent_commands() {
        let cli = crate::cli::Cli::parse_from(["cueloop", "queue", "list"]);
        assert!(!should_refresh_readme_for_command(&cli.command));

        let cli = crate::cli::Cli::parse_from(["cueloop", "version"]);
        assert!(!should_refresh_readme_for_command(&cli.command));

        let cli = crate::cli::Cli::parse_from(["cueloop", "completions", "bash"]);
        assert!(!should_refresh_readme_for_command(&cli.command));
    }

    #[test]
    fn startup_sanity_mode_classifies_commands() {
        let cli = crate::cli::Cli::parse_from(["cueloop", "run", "one", "--id", "RQ-0001"]);
        assert_eq!(
            startup_sanity_mode(&cli.command),
            StartupSanityMode::Mutating
        );

        let cli = crate::cli::Cli::parse_from(["cueloop", "queue", "validate"]);
        assert_eq!(startup_sanity_mode(&cli.command), StartupSanityMode::None);

        let cli = crate::cli::Cli::parse_from(["cueloop", "queue", "list"]);
        assert_eq!(startup_sanity_mode(&cli.command), StartupSanityMode::None);
    }
}