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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
//! Repository cleanliness validation.
//!
//! Purpose:
//! - Repository cleanliness validation.
//!
//! Responsibilities:
//! - Provide focused implementation or regression coverage for this file's owning feature.
//!
//! Scope:
//! - Limited to this file's owning feature boundary.
//!
//! This module provides functions for validating that a repository is in a clean
//! state, with support for allowing specific paths to be dirty (for example,
//! CueLoop/CueLoop runtime files).
//!
//! # Invariants
//! - Allowed paths must be normalized before comparison
//! - Directory prefixes work with or without trailing slashes
//! - Force flag bypasses all checks
//!
//! # What this does NOT handle
//! - Actual git operations (see git/commit.rs)
//! - Status parsing details (see git/status.rs)
//! - LFS validation (see git/lfs.rs)
//!
//! Usage:
//! - Used through the crate module tree or integration test harness.

use crate::git::error::GitError;
use crate::git::status::{
    PathSnapshot, changed_paths_from_snapshots, parse_porcelain_z_entries, snapshot_paths,
    status_paths, status_porcelain,
};
use std::collections::BTreeMap;
use std::path::Path;

/// Paths that are allowed to be dirty during CLI runs.
///
/// These are CueLoop runtime files that may change during normal operation.
pub const CUELOOP_RUN_CLEAN_ALLOWED_PATHS: &[&str] = &[
    ".cueloop/queue.jsonc",
    ".cueloop/done.jsonc",
    ".cueloop/config.jsonc",
    ".cueloop/cache/",
];

/// Narrower allowlist for queue-only runner workflows.
///
/// These commands may shape queue state and write CueLoop cache/checkpoint files,
/// but they must not silently edit source, docs, or repo config.
pub const CUELOOP_QUEUE_ONLY_ALLOWED_PATHS: &[&str] = &[
    ".cueloop/queue.jsonc",
    ".cueloop/done.jsonc",
    ".cueloop/cache/",
];

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirtyPathBaseline {
    snapshots: Vec<PathSnapshot>,
}

impl DirtyPathBaseline {
    pub(crate) fn has_revert_sensitive_disallowed_paths(&self) -> bool {
        self.snapshots
            .iter()
            .any(|snapshot| !snapshot.path.starts_with(".cueloop/lock/"))
    }
}

/// Require a clean repository, ignoring allowed paths.
///
/// Returns an error if the repository has uncommitted changes outside
/// the allowed paths. The force flag bypasses this check entirely.
///
/// # Arguments
/// * `repo_root` - Path to the repository root
/// * `force` - If true, bypass the check entirely
/// * `allowed_paths` - Paths that are allowed to be dirty
///
/// # Returns
/// * `Ok(())` - Repository is clean or force was true
/// * `Err(GitError::DirtyRepo)` - Repository has disallowed changes
pub fn require_clean_repo_ignoring_paths(
    repo_root: &Path,
    force: bool,
    allowed_paths: &[&str],
) -> Result<(), GitError> {
    let status = match status_porcelain(repo_root) {
        Ok(status) => status,
        Err(err) if is_not_git_worktree_error(&err) => return Ok(()),
        Err(err) => return Err(err),
    };
    if status.trim().is_empty() {
        return Ok(());
    }

    if force {
        return Ok(());
    }

    let mut tracked = Vec::new();
    let mut untracked = Vec::new();

    let entries = parse_porcelain_z_entries(&status)?;
    for entry in entries {
        let path = entry.path.as_str();
        if !path_is_allowed_for_dirty_check(repo_root, path, allowed_paths) {
            let display = format_porcelain_entry(&entry);
            if entry.xy == "??" {
                untracked.push(display);
            } else {
                tracked.push(display);
            }
        }
    }

    if tracked.is_empty() && untracked.is_empty() {
        return Ok(());
    }

    let mut details = String::new();

    if !tracked.is_empty() {
        details.push_str("\n\nTracked changes (suggest 'git stash' or 'git commit'):");
        for line in tracked.iter().take(10) {
            details.push_str("\n  ");
            details.push_str(line);
        }
        if tracked.len() > 10 {
            details.push_str(&format!("\n  ...and {} more", tracked.len() - 10));
        }
    }

    if !untracked.is_empty() {
        details.push_str("\n\nUntracked files (suggest 'git clean -fd' or 'git add'):");
        for line in untracked.iter().take(10) {
            details.push_str("\n  ");
            details.push_str(line);
        }
        if untracked.len() > 10 {
            details.push_str(&format!("\n  ...and {} more", untracked.len() - 10));
        }
    }

    details.push_str("\n\nUse --force to bypass this check if you are sure.");
    Err(GitError::DirtyRepo { details })
}

/// Returns true when the repo has dirty paths and every dirty path is allowed.
///
/// This is useful for detecting if only CueLoop's own files have changed.
pub fn repo_dirty_only_allowed_paths(
    repo_root: &Path,
    allowed_paths: &[&str],
) -> Result<bool, GitError> {
    let status_paths = status_paths(repo_root)?;
    if status_paths.is_empty() {
        return Ok(false);
    }

    let has_disallowed = status_paths
        .iter()
        .any(|path| !path_is_allowed_for_dirty_check(repo_root, path, allowed_paths));
    Ok(!has_disallowed)
}

pub fn capture_dirty_path_baseline_ignoring_paths(
    repo_root: &Path,
    allowed_paths: &[&str],
) -> Result<DirtyPathBaseline, GitError> {
    let dirty_paths = match status_paths(repo_root) {
        Ok(paths) => paths,
        Err(err) if is_not_git_worktree_error(&err) => Vec::new(),
        Err(err) => return Err(err),
    };
    let disallowed_paths: Vec<String> = dirty_paths
        .into_iter()
        .filter(|path| !path_is_allowed_for_dirty_check(repo_root, path, allowed_paths))
        .collect();
    let snapshots = snapshot_paths(repo_root, &disallowed_paths).map_err(GitError::Other)?;
    Ok(DirtyPathBaseline { snapshots })
}

pub fn require_no_unexpected_dirty_paths_since_baseline(
    repo_root: &Path,
    allowed_paths: &[&str],
    baseline: &DirtyPathBaseline,
) -> Result<(), GitError> {
    let status = match status_porcelain(repo_root) {
        Ok(status) => status,
        Err(err) if is_not_git_worktree_error(&err) => return Ok(()),
        Err(err) => return Err(err),
    };
    if status.trim().is_empty() {
        return if baseline.snapshots.is_empty() {
            Ok(())
        } else {
            let changed_paths = changed_paths_from_snapshots(repo_root, &baseline.snapshots)
                .map_err(GitError::Other)?;
            if changed_paths.is_empty() {
                Ok(())
            } else {
                Err(queue_only_dirty_repo_error(
                    repo_root,
                    allowed_paths,
                    Vec::new(),
                    Vec::new(),
                    changed_paths,
                ))
            }
        };
    }

    let baseline_changed =
        changed_paths_from_snapshots(repo_root, &baseline.snapshots).map_err(GitError::Other)?;
    let baseline_paths: std::collections::HashSet<&str> = baseline
        .snapshots
        .iter()
        .map(|snapshot| snapshot.path.as_str())
        .collect();

    let mut tracked = Vec::new();
    let mut untracked = Vec::new();
    let entries = parse_porcelain_z_entries(&status)?;
    for entry in entries {
        let path = entry.path.as_str();
        if path_is_allowed_for_dirty_check(repo_root, path, allowed_paths)
            || baseline_paths.contains(path)
        {
            continue;
        }
        let display = format_porcelain_entry(&entry);
        if entry.xy == "??" {
            untracked.push(display);
        } else {
            tracked.push(display);
        }
    }

    if tracked.is_empty() && untracked.is_empty() && baseline_changed.is_empty() {
        return Ok(());
    }

    Err(queue_only_dirty_repo_error(
        repo_root,
        allowed_paths,
        tracked,
        untracked,
        baseline_changed,
    ))
}

/// Check if a path is allowed to be dirty.
///
/// Handles normalization of paths and directory prefix matching.
pub(crate) fn path_is_allowed_for_dirty_check(
    repo_root: &Path,
    path: &str,
    allowed_paths: &[&str],
) -> bool {
    let Some(normalized) = normalize_path_value(path) else {
        return false;
    };

    let normalized_dir = if normalized.ends_with('/') {
        normalized.to_string()
    } else {
        format!("{}/", normalized)
    };
    let normalized_is_dir = repo_root.join(normalized).is_dir();

    allowed_paths.iter().any(|allowed| {
        let Some(allowed_norm) = normalize_path_value(allowed) else {
            return false;
        };

        if normalized == allowed_norm {
            return true;
        }

        let is_dir_prefix = allowed_norm.ends_with('/') || repo_root.join(allowed_norm).is_dir();
        if !is_dir_prefix {
            return false;
        }

        let allowed_dir = allowed_norm.trim_end_matches('/');
        if allowed_dir.is_empty() {
            return false;
        }

        if normalized == allowed_dir {
            return true;
        }

        let prefix = format!("{}/", allowed_dir);
        if normalized.starts_with(&prefix) || normalized_dir.starts_with(&prefix) {
            return true;
        }

        let allowed_dir_slash = prefix;
        normalized_is_dir && allowed_dir_slash.starts_with(&normalized_dir)
    })
}

/// Normalize a path value for comparison.
fn normalize_path_value(value: &str) -> Option<&str> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return None;
    }
    Some(trimmed.strip_prefix("./").unwrap_or(trimmed))
}

/// Format a porcelain entry for display.
fn format_porcelain_entry(entry: &crate::git::status::PorcelainZEntry) -> String {
    if let Some(old) = entry.old_path.as_deref() {
        format!("{} {} -> {}", entry.xy, old, entry.path)
    } else {
        format!("{} {}", entry.xy, entry.path)
    }
}

fn is_not_git_worktree_error(err: &GitError) -> bool {
    match err {
        GitError::CommandFailed { stderr, .. } => stderr.contains("not a git repository"),
        GitError::Other(inner) => inner.to_string().contains("not a git repository"),
        _ => false,
    }
}

fn queue_only_dirty_repo_error(
    repo_root: &Path,
    allowed_paths: &[&str],
    tracked: Vec<String>,
    untracked: Vec<String>,
    changed_baseline_paths: Vec<String>,
) -> GitError {
    let mut details = String::new();
    details.push_str("\n\nQueue-only runner modified unexpected paths.");
    details.push_str("\nAllowed paths:");
    for allowed in allowed_paths {
        details.push_str("\n  - ");
        details.push_str(allowed);
    }

    if !changed_baseline_paths.is_empty() {
        details.push_str("\n\nPreviously dirty disallowed paths changed during the run:");
        for path in changed_baseline_paths.iter().take(10) {
            details.push_str("\n  ");
            details.push_str(path);
        }
        if changed_baseline_paths.len() > 10 {
            details.push_str(&format!(
                "\n  ...and {} more",
                changed_baseline_paths.len() - 10
            ));
        }
    }

    if !tracked.is_empty() {
        details.push_str("\n\nNew tracked changes outside allowed queue-only paths:");
        for line in tracked.iter().take(10) {
            details.push_str("\n  ");
            details.push_str(line);
        }
        if tracked.len() > 10 {
            details.push_str(&format!("\n  ...and {} more", tracked.len() - 10));
        }
    }

    if !untracked.is_empty() {
        details.push_str("\n\nNew untracked files outside allowed queue-only paths:");
        for line in untracked.iter().take(10) {
            details.push_str("\n  ");
            details.push_str(line);
        }
        if untracked.len() > 10 {
            details.push_str(&format!("\n  ...and {} more", untracked.len() - 10));
        }
    }

    let normalized_allowed: Vec<&str> = allowed_paths
        .iter()
        .filter_map(|path| normalize_path_value(path))
        .collect();
    let mut examples_by_kind: BTreeMap<&str, Vec<String>> = BTreeMap::new();
    for path in [
        ".cueloop/queue.jsonc",
        ".cueloop/done.jsonc",
        ".cueloop/cache/execution_history.json",
        ".cueloop/config.jsonc",
        "README.md",
    ] {
        let bucket = if path_is_allowed_for_dirty_check(repo_root, path, &normalized_allowed) {
            "allowed"
        } else {
            "blocked"
        };
        examples_by_kind
            .entry(bucket)
            .or_default()
            .push(path.to_string());
    }
    if let Some(allowed) = examples_by_kind.get("allowed") {
        details.push_str("\n\nExamples still allowed:");
        for path in allowed {
            details.push_str("\n  - ");
            details.push_str(path);
        }
    }
    if let Some(blocked) = examples_by_kind.get("blocked") {
        details.push_str("\n\nExamples blocked by this guard:");
        for path in blocked {
            details.push_str("\n  - ");
            details.push_str(path);
        }
    }

    GitError::DirtyRepo { details }
}

#[cfg(test)]
mod clean_repo_tests {
    use super::*;
    use crate::testsupport::git as git_test;
    use tempfile::TempDir;

    #[test]
    fn run_clean_allowed_paths_include_current_jsonc_runtime_paths() {
        for required in [
            ".cueloop/queue.jsonc",
            ".cueloop/done.jsonc",
            ".cueloop/config.jsonc",
            ".cueloop/cache/",
        ] {
            assert!(
                CUELOOP_RUN_CLEAN_ALLOWED_PATHS.contains(&required),
                "missing required allowlisted path: {required}"
            );
        }
    }

    #[test]
    fn queue_only_allowed_paths_exclude_config() {
        for required in [
            ".cueloop/queue.jsonc",
            ".cueloop/done.jsonc",
            ".cueloop/cache/",
        ] {
            assert!(
                CUELOOP_QUEUE_ONLY_ALLOWED_PATHS.contains(&required),
                "missing required queue-only allowlisted path: {required}"
            );
        }
        assert!(
            !CUELOOP_QUEUE_ONLY_ALLOWED_PATHS.contains(&".cueloop/config.jsonc"),
            "queue-only guard should not allow config mutations"
        );
    }

    #[test]
    fn repo_dirty_only_allowed_paths_detects_config_only_changes() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        git_test::init_repo(temp.path())?;
        std::fs::create_dir_all(temp.path().join(".cueloop"))?;
        let config_path = temp.path().join(".cueloop/config.jsonc");
        std::fs::write(&config_path, "{ \"version\": 1 }")?;
        git_test::git_run(temp.path(), &["add", "-f", ".cueloop/config.jsonc"])?;
        git_test::git_run(temp.path(), &["commit", "-m", "init config"])?;

        std::fs::write(&config_path, "{ \"version\": 2 }")?;

        let dirty_allowed =
            repo_dirty_only_allowed_paths(temp.path(), CUELOOP_RUN_CLEAN_ALLOWED_PATHS)?;
        assert!(dirty_allowed, "expected config-only changes to be allowed");
        require_clean_repo_ignoring_paths(temp.path(), false, CUELOOP_RUN_CLEAN_ALLOWED_PATHS)?;
        Ok(())
    }

    #[test]
    fn repo_dirty_only_allowed_paths_detects_current_config_jsonc_only_changes()
    -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        git_test::init_repo(temp.path())?;
        std::fs::create_dir_all(temp.path().join(".cueloop"))?;
        let config_path = temp.path().join(".cueloop/config.jsonc");
        std::fs::write(&config_path, "{ \"version\": 1 }")?;
        git_test::git_run(temp.path(), &["add", "-f", ".cueloop/config.jsonc"])?;
        git_test::git_run(temp.path(), &["commit", "-m", "init config jsonc"])?;

        std::fs::write(&config_path, "{ \"version\": 2 }")?;

        let dirty_allowed =
            repo_dirty_only_allowed_paths(temp.path(), CUELOOP_RUN_CLEAN_ALLOWED_PATHS)?;
        assert!(
            dirty_allowed,
            "expected config.jsonc-only changes to be allowed"
        );
        require_clean_repo_ignoring_paths(temp.path(), false, CUELOOP_RUN_CLEAN_ALLOWED_PATHS)?;
        Ok(())
    }

    #[test]
    fn repo_dirty_only_allowed_paths_rejects_other_changes() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        git_test::init_repo(temp.path())?;
        std::fs::write(temp.path().join("notes.txt"), "hello")?;

        let dirty_allowed =
            repo_dirty_only_allowed_paths(temp.path(), CUELOOP_RUN_CLEAN_ALLOWED_PATHS)?;
        assert!(!dirty_allowed, "expected untracked change to be disallowed");
        Ok(())
    }

    #[test]
    fn repo_dirty_only_allowed_paths_accepts_directory_prefix_with_trailing_slash()
    -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        git_test::init_repo(temp.path())?;
        std::fs::create_dir_all(temp.path().join("cache/plans"))?;
        std::fs::write(temp.path().join("cache/plans/plan.md"), "plan")?;

        let dirty_allowed = repo_dirty_only_allowed_paths(temp.path(), &["cache/plans/"])?;
        assert!(dirty_allowed, "expected directory prefix to be allowed");
        require_clean_repo_ignoring_paths(temp.path(), false, &["cache/plans/"])?;
        Ok(())
    }

    #[test]
    fn repo_dirty_only_allowed_paths_accepts_existing_directory_prefix_without_slash()
    -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        git_test::init_repo(temp.path())?;
        std::fs::create_dir_all(temp.path().join("cache"))?;
        std::fs::write(temp.path().join("cache/notes.txt"), "notes")?;

        let dirty_allowed = repo_dirty_only_allowed_paths(temp.path(), &["cache"])?;
        assert!(dirty_allowed, "expected existing directory to be allowed");
        require_clean_repo_ignoring_paths(temp.path(), false, &["cache"])?;
        Ok(())
    }

    #[test]
    fn repo_dirty_only_allowed_paths_rejects_paths_outside_allowed_directory() -> anyhow::Result<()>
    {
        let temp = TempDir::new()?;
        git_test::init_repo(temp.path())?;
        std::fs::create_dir_all(temp.path().join("cache"))?;
        std::fs::write(temp.path().join("cache/notes.txt"), "notes")?;
        std::fs::write(temp.path().join("other.txt"), "nope")?;

        let dirty_allowed = repo_dirty_only_allowed_paths(temp.path(), &["cache/"])?;
        assert!(!dirty_allowed, "expected other paths to be disallowed");
        assert!(
            require_clean_repo_ignoring_paths(temp.path(), false, &["cache/"]).is_err(),
            "expected clean-repo enforcement to fail"
        );
        Ok(())
    }

    #[test]
    fn require_no_unexpected_dirty_paths_since_baseline_allows_queue_changes() -> anyhow::Result<()>
    {
        let temp = TempDir::new()?;
        git_test::init_repo(temp.path())?;
        std::fs::create_dir_all(temp.path().join(".cueloop/cache"))?;
        std::fs::write(temp.path().join("README.md"), "baseline\n")?;
        std::fs::write(temp.path().join(".cueloop/queue.jsonc"), "{}")?;
        std::fs::write(
            temp.path().join(".cueloop/cache/execution_history.json"),
            "{}",
        )?;
        git_test::commit_all(temp.path(), "init")?;

        let baseline = capture_dirty_path_baseline_ignoring_paths(
            temp.path(),
            CUELOOP_QUEUE_ONLY_ALLOWED_PATHS,
        )?;
        std::fs::write(
            temp.path().join(".cueloop/queue.jsonc"),
            "{\n  \"version\": 1\n}",
        )?;
        std::fs::write(
            temp.path().join(".cueloop/cache/execution_history.json"),
            "{\n  \"ok\": true\n}",
        )?;

        require_no_unexpected_dirty_paths_since_baseline(
            temp.path(),
            CUELOOP_QUEUE_ONLY_ALLOWED_PATHS,
            &baseline,
        )?;
        Ok(())
    }

    #[test]
    fn require_no_unexpected_dirty_paths_since_baseline_rejects_new_source_and_config_changes()
    -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        git_test::init_repo(temp.path())?;
        std::fs::create_dir_all(temp.path().join(".cueloop"))?;
        std::fs::write(temp.path().join("README.md"), "baseline\n")?;
        std::fs::write(temp.path().join(".cueloop/config.jsonc"), "{}")?;
        git_test::commit_all(temp.path(), "init")?;

        let baseline = capture_dirty_path_baseline_ignoring_paths(
            temp.path(),
            CUELOOP_QUEUE_ONLY_ALLOWED_PATHS,
        )?;
        std::fs::write(temp.path().join("README.md"), "changed\n")?;
        std::fs::write(
            temp.path().join(".cueloop/config.jsonc"),
            "{\n  \"v\": 2\n}",
        )?;

        let err = require_no_unexpected_dirty_paths_since_baseline(
            temp.path(),
            CUELOOP_QUEUE_ONLY_ALLOWED_PATHS,
            &baseline,
        )
        .expect_err("expected queue-only guard to reject README/config changes");
        let message = err.to_string();
        assert!(message.contains("Queue-only runner modified unexpected paths"));
        assert!(message.contains("README.md"));
        assert!(message.contains(".cueloop/config.jsonc"));
        Ok(())
    }

    #[test]
    fn require_no_unexpected_dirty_paths_since_baseline_rejects_changed_forced_baseline_path()
    -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        git_test::init_repo(temp.path())?;
        std::fs::write(temp.path().join("README.md"), "baseline\n")?;
        git_test::commit_all(temp.path(), "init")?;

        std::fs::write(temp.path().join("README.md"), "pre-existing dirt\n")?;
        let baseline = capture_dirty_path_baseline_ignoring_paths(
            temp.path(),
            CUELOOP_QUEUE_ONLY_ALLOWED_PATHS,
        )?;
        std::fs::write(temp.path().join("README.md"), "runner changed dirt\n")?;

        let err = require_no_unexpected_dirty_paths_since_baseline(
            temp.path(),
            CUELOOP_QUEUE_ONLY_ALLOWED_PATHS,
            &baseline,
        )
        .expect_err("expected changed baseline path to be rejected");
        let message = err.to_string();
        assert!(message.contains("Previously dirty disallowed paths changed during the run"));
        assert!(message.contains("README.md"));
        Ok(())
    }

    #[test]
    fn execution_history_json_is_in_allowed_paths() -> anyhow::Result<()> {
        // Verify that execution_history.json is covered by CUELOOP_RUN_CLEAN_ALLOWED_PATHS
        // via the .cueloop/cache/ directory prefix
        let temp = TempDir::new()?;
        git_test::init_repo(temp.path())?;
        std::fs::create_dir_all(temp.path().join(".cueloop/cache"))?;
        std::fs::write(
            temp.path().join(".cueloop/cache/execution_history.json"),
            "{}",
        )?;

        let dirty_allowed =
            repo_dirty_only_allowed_paths(temp.path(), CUELOOP_RUN_CLEAN_ALLOWED_PATHS)?;
        assert!(
            dirty_allowed,
            "execution_history.json should be covered by CUELOOP_RUN_CLEAN_ALLOWED_PATHS"
        );
        Ok(())
    }
}