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
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
//! Migration CLI command for checking and applying config/file migrations.
//!
//! Purpose:
//! - Migration CLI command for checking and applying config/file migrations.
//!
//! Responsibilities:
//! - Provide CLI interface for migration operations (check, list, apply).
//! - Display migration status to users in a readable format.
//! - Handle user confirmation for destructive operations.
//!
//! Not handled here:
//! - Migration implementation logic (see `crate::migration`).
//! - Migration history persistence (see `crate::migration::history`).
//!
//!
//! Usage:
//! - Used through the crate module tree or integration test harness.
//!
//! Invariants/assumptions:
//! - Uses the current working tree for explicit migration commands.
//! - `--apply` requires explicit user action (not automatic).
//! - `migrate runtime-dir --apply` is explicit and is never part of normal `migrate --apply`.
//! - Exit code 1 from `--check` when migrations are pending for CI integration.

use crate::commands::init::gitignore;
use crate::migration::{self, MigrationCheckResult, MigrationContext};
use anyhow::{Context, Result};
use clap::{Args, Subcommand};
use colored::Colorize;

#[derive(Args)]
#[command(
    about = "Check and apply migrations for config and project files",
    after_long_help = "Examples:
  cueloop migrate              # Check for pending migrations
  cueloop migrate --check      # Exit with error code if migrations pending (CI)
  cueloop migrate --apply      # Apply all pending config/file migrations
  cueloop migrate --list       # List all migrations and their status
  cueloop migrate status       # Show detailed migration status
  cueloop migrate runtime-dir --check  # Check whether .ralph should be moved to .cueloop
  cueloop migrate runtime-dir --apply  # Explicitly move .ralph project state to .cueloop
"
)]
pub struct MigrateArgs {
    /// Check for pending migrations without applying them (exit 1 if any pending).
    #[arg(long, conflicts_with = "apply")]
    pub check: bool,

    /// Apply pending migrations.
    #[arg(long, conflicts_with = "check")]
    pub apply: bool,

    /// List all migrations and their status.
    #[arg(long, conflicts_with_all = ["check", "apply"])]
    pub list: bool,

    /// Force apply migrations even if already applied (dangerous).
    #[arg(long, requires = "apply")]
    pub force: bool,

    /// Subcommand for more detailed operations.
    #[command(subcommand)]
    pub command: Option<MigrateCommand>,
}

#[derive(Subcommand)]
pub enum MigrateCommand {
    /// Show detailed migration status.
    Status,
    /// Explicitly check or apply the `.ralph` -> `.cueloop` runtime directory migration.
    #[command(name = "runtime-dir")]
    RuntimeDir(RuntimeDirArgs),
}

#[derive(Args)]
pub struct RuntimeDirArgs {
    /// Check runtime-dir migration status without applying it (exit 1 if migration is needed).
    #[arg(long, conflicts_with = "apply")]
    pub check: bool,

    /// Move `.ralph` project runtime state to `.cueloop` when safe.
    #[arg(long, conflicts_with = "check")]
    pub apply: bool,
}

/// Handle the migrate command.
pub fn handle_migrate(args: MigrateArgs) -> Result<()> {
    // Handle subcommands first
    if let Some(command) = args.command {
        return match command {
            MigrateCommand::Status => show_migration_status(),
            MigrateCommand::RuntimeDir(runtime_args) => handle_runtime_dir_migration(runtime_args),
        };
    }

    // Handle flags
    if args.list {
        return list_migrations();
    }

    if args.apply {
        return apply_migrations(args.force);
    }

    if args.check {
        return check_migrations();
    }

    // Default: show pending migrations
    show_pending_migrations()
}

/// Check for pending migrations and exit with error code if any found.
fn check_migrations() -> Result<()> {
    let ctx = MigrationContext::discover_from_cwd().context("discover migration context")?;

    match migration::check_migrations(&ctx)? {
        MigrationCheckResult::Current => {
            println!("{}", "✓ No pending migrations".green());
            Ok(())
        }
        MigrationCheckResult::Pending(migrations) => {
            println!(
                "{}",
                format!("{} pending migration(s) found", migrations.len()).red()
            );
            for migration in &migrations {
                println!("  - {}: {}", migration.id.yellow(), migration.description);
            }
            println!("\nRun {} to apply them.", "cueloop migrate --apply".cyan());
            std::process::exit(1);
        }
    }
}

/// Show pending migrations without exiting with error code.
fn show_pending_migrations() -> Result<()> {
    let ctx = MigrationContext::discover_from_cwd().context("discover migration context")?;

    match migration::check_migrations(&ctx)? {
        MigrationCheckResult::Current => {
            println!("{}", "✓ No pending migrations".green());
            println!("\nYour project is up to date!");
        }
        MigrationCheckResult::Pending(migrations) => {
            println!(
                "{}",
                format!("Found {} pending migration(s):", migrations.len()).yellow()
            );
            println!();
            for migration in &migrations {
                println!("  {} {}", "".cyan(), migration.id.bold());
                println!("    {}", migration.description);
                println!();
            }
            println!("Run {} to apply them.", "cueloop migrate --apply".cyan());
        }
    }

    Ok(())
}

/// List all migrations with their status.
fn list_migrations() -> Result<()> {
    let ctx = MigrationContext::discover_from_cwd().context("discover migration context")?;

    let migrations = migration::list_migrations(&ctx);

    if migrations.is_empty() {
        println!("No migrations defined.");
        return Ok(());
    }

    println!("{}", "Available migrations:".bold());
    println!();

    for status in &migrations {
        let status_icon = if status.applied {
            "".green()
        } else if status.applicable {
            "".yellow()
        } else {
            "-".dimmed()
        };

        let status_text = if status.applied {
            "applied".green()
        } else if status.applicable {
            "pending".yellow()
        } else {
            "not applicable".dimmed()
        };

        println!(
            "  {} {} ({})",
            status_icon,
            status.migration.id.bold(),
            status_text
        );
        println!("    {}", status.migration.description);
        println!();
    }

    let applied_count = migrations.iter().filter(|m| m.applied).count();
    let pending_count = migrations
        .iter()
        .filter(|m| !m.applied && m.applicable)
        .count();

    println!(
        "{} applied, {} pending, {} not applicable",
        applied_count.to_string().green(),
        pending_count.to_string().yellow(),
        (migrations.len() - applied_count - pending_count)
            .to_string()
            .dimmed()
    );

    Ok(())
}

/// Apply all pending migrations.
fn apply_migrations(force: bool) -> Result<()> {
    let mut ctx = MigrationContext::discover_from_cwd().context("discover migration context")?;

    // Check what migrations would be applied
    let pending = match migration::check_migrations(&ctx)? {
        MigrationCheckResult::Current => {
            println!("{}", "✓ No pending migrations to apply".green());
            return Ok(());
        }
        MigrationCheckResult::Pending(migrations) => migrations,
    };

    if force {
        println!(
            "{}",
            "⚠ Force mode enabled: Will re-apply already applied migrations".yellow()
        );
    }

    println!(
        "{}",
        format!("Will apply {} migration(s):", pending.len()).cyan()
    );
    println!();
    for migration in &pending {
        println!("  - {}: {}", migration.id.yellow(), migration.description);
    }
    println!();

    // Confirm with user
    if !force {
        print!("{} ", "Apply these migrations? [y/N]:".bold());
        use std::io::Write;
        std::io::stdout().flush()?;

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

        if !input.trim().eq_ignore_ascii_case("y") {
            println!("Cancelled.");
            return Ok(());
        }
    }

    println!();

    // Apply migrations
    let applied = migration::apply_all_migrations(&mut ctx).context("apply migrations")?;

    if applied.is_empty() {
        println!("{}", "No migrations were applied".yellow());
    } else {
        println!(
            "{}",
            format!("✓ Successfully applied {} migration(s)", applied.len()).green()
        );
        for id in applied {
            println!("  {} {}", "".green(), id);
        }
    }

    // Apply gitignore migration for JSON to JSONC patterns
    match gitignore::migrate_json_to_jsonc_gitignore(&ctx.repo_root) {
        Ok(true) => {
            println!("{}", "✓ Updated .gitignore for JSONC patterns".green());
        }
        Ok(false) => {
            log::debug!(".gitignore JSON to JSONC migration not needed or already up to date");
        }
        Err(e) => {
            eprintln!(
                "{}",
                format!("⚠ Warning: Failed to update .gitignore for JSONC: {}", e).yellow()
            );
        }
    }

    Ok(())
}

/// Handle the explicit runtime-dir migration command.
fn handle_runtime_dir_migration(args: RuntimeDirArgs) -> Result<()> {
    let ctx = MigrationContext::discover_from_cwd().context("discover migration context")?;

    if args.apply {
        return apply_runtime_dir_migration(&ctx.repo_root);
    }

    let state = migration::runtime_dir::check_runtime_dir_migration(&ctx.repo_root);
    print_runtime_dir_state(&state);

    if args.check && state.check_should_fail() {
        std::process::exit(1);
    }

    Ok(())
}

fn print_runtime_dir_state(state: &migration::runtime_dir::RuntimeDirMigrationState) {
    let label = match state {
        migration::runtime_dir::RuntimeDirMigrationState::Uninitialized { .. } => {
            state.label().dimmed()
        }
        migration::runtime_dir::RuntimeDirMigrationState::AlreadyCurrent { .. } => {
            state.label().green()
        }
        migration::runtime_dir::RuntimeDirMigrationState::NeedsMigration { .. } => {
            state.label().yellow()
        }
        migration::runtime_dir::RuntimeDirMigrationState::Collision { .. } => state.label().red(),
    };

    println!("{} {}", "Runtime directory migration:".bold(), label);
    println!("{}", state.guidance());
    if matches!(
        state,
        migration::runtime_dir::RuntimeDirMigrationState::NeedsMigration { .. }
    ) {
        println!(
            "Run {} to move durable project state to .cueloop.",
            "cueloop migrate runtime-dir --apply".cyan()
        );
    }
}

fn apply_runtime_dir_migration(repo_root: &std::path::Path) -> Result<()> {
    let report = migration::runtime_dir::apply_runtime_dir_migration(repo_root)?;

    match &report.initial_state {
        migration::runtime_dir::RuntimeDirMigrationState::Uninitialized { .. }
        | migration::runtime_dir::RuntimeDirMigrationState::AlreadyCurrent { .. } => {
            print_runtime_dir_state(&report.initial_state);
            return Ok(());
        }
        migration::runtime_dir::RuntimeDirMigrationState::NeedsMigration { .. } => {}
        migration::runtime_dir::RuntimeDirMigrationState::Collision { .. } => unreachable!(
            "runtime-dir collision should be returned as an error before report construction"
        ),
    }

    println!(
        "{}",
        "✓ Moved project runtime directory from .ralph to .cueloop".green()
    );
    if report.gitignore_updated {
        println!("{}", "✓ Updated .gitignore runtime path references".green());
    }
    if report.config_files_updated > 0 {
        println!(
            "{}",
            format!(
                "✓ Updated runtime path references in {} config file(s)",
                report.config_files_updated
            )
            .green()
        );
    }
    if report.readme_refreshed {
        println!("{}", "✓ Refreshed generated runtime README".green());
    }
    if report.history_recorded {
        println!(
            "{}",
            format!(
                "✓ Recorded migration history at {}",
                migration::history::migration_history_path(repo_root).display()
            )
            .green()
        );
    }

    for warning in report.warnings {
        eprintln!("{}", format!("⚠ Warning: {warning}").yellow());
    }

    Ok(())
}

/// Show detailed migration status.
fn show_migration_status() -> Result<()> {
    let ctx = MigrationContext::discover_from_cwd().context("discover migration context")?;

    println!("{}", "Migration Status".bold());
    println!();

    // Show migration history info
    println!("{}", "History:".bold());
    println!(
        "  Location: {}",
        migration::history::migration_history_path(&ctx.repo_root).display()
    );
    println!(
        "  Applied migrations: {}",
        ctx.migration_history.applied_migrations.len()
    );
    println!();

    // Show pending migrations
    match migration::check_migrations(&ctx)? {
        MigrationCheckResult::Current => {
            println!("{}", "Pending migrations: None".green());
        }
        MigrationCheckResult::Pending(migrations) => {
            println!(
                "{} {}",
                "Pending migrations:".yellow(),
                format!("({})", migrations.len()).yellow()
            );
            for migration in migrations {
                println!("  - {}: {}", migration.id.yellow(), migration.description);
            }
        }
    }

    Ok(())
}

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

    #[test]
    fn migrate_args_default_values() {
        // Test that the struct can be created with default values
        let args = MigrateArgs {
            check: false,
            apply: false,
            list: false,
            force: false,
            command: None,
        };
        assert!(!args.check);
        assert!(!args.apply);
        assert!(!args.list);
        assert!(!args.force);
    }

    #[test]
    fn migrate_args_with_check_enabled() {
        let args = MigrateArgs {
            check: true,
            apply: false,
            list: false,
            force: false,
            command: None,
        };
        assert!(args.check);
    }

    #[test]
    fn migrate_args_with_apply_and_force() {
        let args = MigrateArgs {
            check: false,
            apply: true,
            list: false,
            force: true,
            command: None,
        };
        assert!(args.apply);
        assert!(args.force);
    }

    #[test]
    fn migrate_command_status_variant() {
        let cmd = MigrateCommand::Status;
        assert!(matches!(cmd, MigrateCommand::Status));
    }
}