cueloop 0.4.1

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
//! Explicit repo-local runtime directory migration.
//!
//! Purpose:
//! - Move an old `.ralph/` project runtime directory to the current `.cueloop/` path.
//!
//! Responsibilities:
//! - Classify runtime-dir migration state without mutating files.
//! - Apply the explicit directory rename when safe.
//! - Rewrite known config and `.gitignore` path references after the rename.
//! - Refresh the generated runtime README when one moved with the runtime dir.
//! - Record migration history under the active `.cueloop/cache/migrations.jsonc` path.
//!
//! Scope:
//! - Handles only the explicit `.ralph` -> `.cueloop` runtime directory cutover.
//! - Does not run as part of the registry-backed `cueloop migrate --apply` flow.
//! - Does not merge two populated runtime directories or rename binaries/packages/apps.
//!
//! Usage:
//! - Called by `cueloop migrate runtime-dir --check/--apply`.
//!
//! Invariants/Assumptions:
//! - If both runtime directories exist as directories, no mutation is attempted.
//! - The directory rename is the only required mutation; follow-up reference rewrites are best-effort
//!   and are reported as warnings if they fail.
//! - Migration history is written after the runtime dir has moved so the active history path is
//!   `.cueloop/cache/migrations.jsonc`.

use crate::commands::init::readme;
use crate::constants::identity::PROJECT_RUNTIME_DIR;
use crate::migration::history::{self, AppliedMigration};
use anyhow::{Context, Result, bail};
use chrono::Utc;
use std::fs;
use std::path::{Path, PathBuf};

/// Stable migration history ID for the explicit runtime-dir migration.
pub const RUNTIME_DIR_MIGRATION_ID: &str = "runtime_dir_rename_to_cueloop_2026_05";

const OLD_PROJECT_RUNTIME_DIR: &str = ".ralph";

const CONFIG_PATH_REWRITES: &[(&str, &str)] = &[
    (".ralph/queue.jsonc", ".cueloop/queue.jsonc"),
    (".ralph/done.jsonc", ".cueloop/done.jsonc"),
    (".ralph/config.jsonc", ".cueloop/config.jsonc"),
    (".ralph/queue.json", ".cueloop/queue.json"),
    (".ralph/done.json", ".cueloop/done.json"),
    (".ralph/config.json", ".cueloop/config.json"),
];

const KNOWN_GITIGNORE_RUNTIME_ENTRIES: &[&str] = &[
    ".ralph/queue.jsonc",
    ".ralph/done.jsonc",
    ".ralph/config.jsonc",
    ".ralph/queue.json",
    ".ralph/done.json",
    ".ralph/config.json",
    ".ralph/*.jsonc",
    ".ralph/*.json",
    ".ralph/logs/",
    ".ralph/logs",
    ".ralph/workspaces/",
    ".ralph/workspaces",
    ".ralph/trust.jsonc",
    ".ralph/trust.json",
    ".ralph/cache/",
    ".ralph/cache",
    ".ralph/undo/",
    ".ralph/undo",
    ".ralph/webhooks/",
    ".ralph/webhooks",
    ".ralph/lock/",
    ".ralph/lock",
];

/// Non-mutating state for the runtime-dir migration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RuntimeDirMigrationState {
    /// Neither runtime directory exists yet; there is nothing to migrate.
    Uninitialized {
        legacy_path: PathBuf,
        current_path: PathBuf,
    },
    /// Current `.cueloop/` is already present and old `.ralph/` is absent.
    AlreadyCurrent { current_path: PathBuf },
    /// Old `.ralph/` exists and can be renamed to `.cueloop/`.
    NeedsMigration {
        legacy_path: PathBuf,
        current_path: PathBuf,
    },
    /// Migration is blocked by a pre-existing destination or ambiguous filesystem state.
    Collision {
        legacy_path: PathBuf,
        current_path: PathBuf,
        reason: String,
    },
}

impl RuntimeDirMigrationState {
    /// Short machine-readable-ish label for CLI output.
    pub fn label(&self) -> &'static str {
        match self {
            Self::Uninitialized { .. } => "no-op/uninitialized",
            Self::AlreadyCurrent { .. } => "already-current",
            Self::NeedsMigration { .. } => "needs-migration",
            Self::Collision { .. } => "collision",
        }
    }

    /// Human guidance for the current state.
    pub fn guidance(&self) -> String {
        match self {
            Self::Uninitialized {
                legacy_path,
                current_path,
            } => format!(
                "No project runtime directory exists at {} or {}; nothing to migrate.",
                legacy_path.display(),
                current_path.display()
            ),
            Self::AlreadyCurrent { current_path } => format!(
                "Project runtime is already current at {}; no migration is needed.",
                current_path.display()
            ),
            Self::NeedsMigration {
                legacy_path,
                current_path,
            } => format!(
                "Old runtime directory {} can be moved to {}.",
                legacy_path.display(),
                current_path.display()
            ),
            Self::Collision {
                legacy_path,
                current_path,
                reason,
            } => format!(
                "Runtime-dir migration is blocked: {reason}. No changes were made. Manually inspect {} and {}, merge or remove one path, then rerun `cueloop migrate runtime-dir --apply`.",
                legacy_path.display(),
                current_path.display()
            ),
        }
    }

    /// True when `--check` should fail because action or intervention is required.
    pub fn check_should_fail(&self) -> bool {
        matches!(self, Self::NeedsMigration { .. } | Self::Collision { .. })
    }
}

/// Result of applying the runtime-dir migration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeDirApplyReport {
    /// State observed before applying.
    pub initial_state: RuntimeDirMigrationState,
    /// Whether the directory rename was performed.
    pub moved: bool,
    /// Whether `.gitignore` changed.
    pub gitignore_updated: bool,
    /// Number of config files whose known runtime path references changed.
    pub config_files_updated: usize,
    /// Whether the moved runtime README was refreshed.
    pub readme_refreshed: bool,
    /// Whether migration history was written.
    pub history_recorded: bool,
    /// Best-effort follow-up failures after the safe directory rename.
    pub warnings: Vec<String>,
}

/// Inspect runtime-dir migration state without mutating the filesystem.
pub fn check_runtime_dir_migration(repo_root: &Path) -> RuntimeDirMigrationState {
    let legacy_path = repo_root.join(OLD_PROJECT_RUNTIME_DIR);
    let current_path = repo_root.join(PROJECT_RUNTIME_DIR);
    let legacy_is_dir = legacy_path.is_dir();
    let current_is_dir = current_path.is_dir();

    match (
        legacy_is_dir,
        current_is_dir,
        legacy_path.exists(),
        current_path.exists(),
    ) {
        (true, true, _, _) => RuntimeDirMigrationState::Collision {
            legacy_path,
            current_path,
            reason: "both .ralph and .cueloop exist as directories".to_string(),
        },
        (true, false, _, true) => RuntimeDirMigrationState::Collision {
            legacy_path,
            current_path,
            reason: ".cueloop exists and is not a directory".to_string(),
        },
        (true, false, _, false) => RuntimeDirMigrationState::NeedsMigration {
            legacy_path,
            current_path,
        },
        (false, true, true, _) => RuntimeDirMigrationState::Collision {
            legacy_path,
            current_path,
            reason: ".ralph exists and is not a directory while .cueloop is active".to_string(),
        },
        (false, true, false, _) => RuntimeDirMigrationState::AlreadyCurrent { current_path },
        (false, false, true, _) => RuntimeDirMigrationState::Collision {
            legacy_path,
            current_path,
            reason: ".ralph exists and is not a directory".to_string(),
        },
        (false, false, false, true) => RuntimeDirMigrationState::Collision {
            legacy_path,
            current_path,
            reason: ".cueloop exists and is not a directory".to_string(),
        },
        (false, false, false, false) => RuntimeDirMigrationState::Uninitialized {
            legacy_path,
            current_path,
        },
    }
}

/// Apply the explicit runtime-dir migration when safe.
pub fn apply_runtime_dir_migration(repo_root: &Path) -> Result<RuntimeDirApplyReport> {
    let initial_state = check_runtime_dir_migration(repo_root);
    match &initial_state {
        RuntimeDirMigrationState::Uninitialized { .. }
        | RuntimeDirMigrationState::AlreadyCurrent { .. } => {
            return Ok(RuntimeDirApplyReport {
                initial_state,
                moved: false,
                gitignore_updated: false,
                config_files_updated: 0,
                readme_refreshed: false,
                history_recorded: false,
                warnings: Vec::new(),
            });
        }
        RuntimeDirMigrationState::Collision { .. } => {
            bail!(initial_state.guidance());
        }
        RuntimeDirMigrationState::NeedsMigration {
            legacy_path,
            current_path,
        } => {
            fs::rename(legacy_path, current_path).with_context(|| {
                format!(
                    "move runtime directory {} to {}",
                    legacy_path.display(),
                    current_path.display()
                )
            })?;
        }
    }

    let mut warnings = Vec::new();

    let gitignore_updated = collect_warning(
        &mut warnings,
        "update .gitignore runtime-dir references",
        || update_gitignore_runtime_dir_references(repo_root),
    )
    .unwrap_or(false);

    let config_files_updated = collect_warning(
        &mut warnings,
        "update config runtime-dir references",
        || update_config_runtime_dir_references(repo_root),
    )
    .unwrap_or(0);

    let readme_refreshed = collect_warning(&mut warnings, "refresh runtime README", || {
        refresh_runtime_readme(repo_root)
    })
    .unwrap_or(false);

    let history_recorded = collect_warning(
        &mut warnings,
        "record runtime-dir migration history",
        || record_runtime_dir_migration_history(repo_root),
    )
    .unwrap_or(false);

    Ok(RuntimeDirApplyReport {
        initial_state,
        moved: true,
        gitignore_updated,
        config_files_updated,
        readme_refreshed,
        history_recorded,
        warnings,
    })
}

fn collect_warning<T, F>(warnings: &mut Vec<String>, label: &str, f: F) -> Option<T>
where
    F: FnOnce() -> Result<T>,
{
    match f() {
        Ok(value) => Some(value),
        Err(err) => {
            warnings.push(format!("{label}: {err:#}"));
            None
        }
    }
}

fn update_gitignore_runtime_dir_references(repo_root: &Path) -> Result<bool> {
    let path = repo_root.join(".gitignore");
    if !path.exists() {
        return Ok(false);
    }

    let raw = fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
    let existing_lines = raw
        .lines()
        .map(|line| line.trim().to_string())
        .collect::<std::collections::HashSet<_>>();

    let mut changed = false;
    let mut updated_lines = Vec::new();
    for line in raw.lines() {
        if let Some(converted) = convert_gitignore_line(line) {
            if converted.trim() != line.trim() {
                changed = true;
            }
            if converted.trim() != line.trim() && existing_lines.contains(converted.trim()) {
                continue;
            }
            updated_lines.push(converted);
        } else {
            updated_lines.push(line.to_string());
        }
    }

    let mut updated = updated_lines.join("\n");
    if raw.ends_with('\n') {
        updated.push('\n');
    }

    if updated != raw {
        crate::fsutil::write_atomic(&path, updated.as_bytes())
            .with_context(|| format!("write {}", path.display()))?;
        changed = true;
    }

    Ok(changed)
}

fn convert_gitignore_line(line: &str) -> Option<String> {
    let trimmed = line.trim();
    let (negated, runtime_entry) = match trimmed.strip_prefix('!') {
        Some(entry) => (true, entry),
        None => (false, trimmed),
    };
    if !KNOWN_GITIGNORE_RUNTIME_ENTRIES.contains(&runtime_entry) {
        return None;
    }

    let leading_len = line.len() - line.trim_start().len();
    let trailing_len = line.len() - line.trim_end().len();
    let leading = &line[..leading_len];
    let trailing = &line[line.len() - trailing_len..];
    let converted = runtime_entry.replacen(OLD_PROJECT_RUNTIME_DIR, PROJECT_RUNTIME_DIR, 1);
    let negation = if negated { "!" } else { "" };
    Some(format!("{leading}{negation}{converted}{trailing}"))
}

fn update_config_runtime_dir_references(repo_root: &Path) -> Result<usize> {
    let mut candidates = vec![
        repo_root.join(PROJECT_RUNTIME_DIR).join("config.jsonc"),
        repo_root.join(PROJECT_RUNTIME_DIR).join("config.json"),
    ];

    let mut updated_count = 0;
    candidates.sort();
    candidates.dedup();

    for path in candidates {
        if !path.exists() {
            continue;
        }
        if update_config_file_runtime_dir_references(&path)? {
            updated_count += 1;
        }
    }

    Ok(updated_count)
}

fn update_config_file_runtime_dir_references(path: &Path) -> Result<bool> {
    let raw = fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
    let mut updated = raw.clone();
    for (old, new) in CONFIG_PATH_REWRITES {
        updated = updated.replace(old, new);
    }

    if updated == raw {
        return Ok(false);
    }

    crate::fsutil::write_atomic(path, updated.as_bytes())
        .with_context(|| format!("write {}", path.display()))?;
    Ok(true)
}

fn refresh_runtime_readme(repo_root: &Path) -> Result<bool> {
    let path = repo_root.join(PROJECT_RUNTIME_DIR).join("README.md");
    if !path.exists() {
        return Ok(false);
    }

    let (status, _) = readme::write_readme(&path, false)
        .with_context(|| format!("refresh {}", path.display()))?;
    Ok(matches!(
        status,
        crate::commands::init::FileInitStatus::Updated
    ))
}

fn record_runtime_dir_migration_history(repo_root: &Path) -> Result<bool> {
    let mut migration_history = history::load_migration_history(repo_root)?;
    let already_recorded = migration_history
        .applied_migrations
        .iter()
        .any(|migration| migration.id == RUNTIME_DIR_MIGRATION_ID);
    if !already_recorded {
        migration_history.applied_migrations.push(AppliedMigration {
            id: RUNTIME_DIR_MIGRATION_ID.to_string(),
            applied_at: Utc::now(),
            migration_type: "RuntimeDirRename".to_string(),
        });
    }
    history::save_migration_history(repo_root, &migration_history)?;
    Ok(!already_recorded)
}

#[cfg(test)]
mod tests;