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
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
//! Queue and workspace contract coverage for `cueloop machine`.
//!
//! Purpose:
//! - Verify machine queue and workspace JSON documents exposed to app clients.
//!
//! Responsibilities:
//! - Assert queue read success and failure document shapes.
//! - Assert workspace overview bundles queue and config payloads together.
//! - Keep queue/workspace contract regressions isolated from task and recovery flows.
//!
//! Non-scope:
//! - Task mutation behavior.
//! - Parallel runtime or system contract coverage.
//!
//! Usage:
//! - Used through the crate module tree or integration test harness.
//!
//! Invariants/assumptions callers must respect:
//! - Tests execute against disposable repos initialized through the public CLI.
//! - Contract assertions preserve the historical flat suite behavior exactly.

use super::machine_contract_test_support::{
    run_in_dir, setup_cueloop_repo, trust_project_commands,
};
use anyhow::{Context, Result};
use serde_json::Value;

const SENSITIVE_PROJECT_CONFIG: &str = r#"{
  "version": 2,
  "agent": {
    "runner": "codex",
    "model": "gpt-5.3-codex",
    "codex_bin": "codex"
  }
}"#;

#[test]
fn machine_queue_read_returns_versioned_snapshot() -> Result<()> {
    let dir = setup_cueloop_repo()?;

    let (status, stdout, stderr) = run_in_dir(dir.path(), &["machine", "queue", "read"]);
    assert!(
        status.success(),
        "machine queue read failed\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );

    let document: Value = serde_json::from_str(&stdout)?;
    assert_eq!(document["version"], 1);
    assert!(document["paths"]["queue_path"].is_string());
    assert!(document["active"]["tasks"].is_array());
    assert!(document["done"]["tasks"].is_array());
    Ok(())
}

#[test]
fn machine_queue_read_suppresses_invalid_dotenv_warning() -> Result<()> {
    let dir = setup_cueloop_repo()?;
    std::fs::write(
        dir.path().join(".env"),
        "INVALID LINE WITHOUT EQUALS SIGN\nVALID_KEY=valid\n",
    )?;

    let (status, stdout, stderr) = run_in_dir(dir.path(), &["machine", "queue", "read"]);
    assert!(
        status.success(),
        "machine queue read failed with malformed .env\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    assert!(
        stderr.trim().is_empty(),
        "machine command must not emit prose stderr for malformed .env; stderr was:\n{stderr}"
    );
    let document: Value = serde_json::from_str(&stdout)?;
    assert_eq!(document["version"], 1);
    Ok(())
}

#[test]
fn machine_queue_read_failure_returns_structured_error_document() -> Result<()> {
    let dir = tempfile::tempdir()?;

    let (status, stdout, stderr) = run_in_dir(dir.path(), &["machine", "queue", "read"]);
    assert!(
        !status.success(),
        "machine queue read should fail outside a CueLoop repo\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    assert!(
        stdout.trim().is_empty(),
        "failure stdout should stay empty: {stdout}"
    );

    let document: Value = serde_json::from_str(&stderr)?;
    assert_eq!(document["version"], 1);
    assert_eq!(document["code"], "queue_corrupted");
    assert_eq!(document["message"], "No CueLoop queue file found.");
    assert_eq!(document["retryable"], false);
    assert!(
        document["detail"]
            .as_str()
            .unwrap_or_default()
            .contains("queue.jsonc")
    );
    Ok(())
}

#[test]
fn machine_queue_read_gates_runnability_when_queue_validation_fails() -> Result<()> {
    let dir = setup_cueloop_repo()?;
    let queue_path = dir.path().join(".cueloop/queue.jsonc");
    std::fs::write(
        &queue_path,
        r#"{
  "version": 1,
  "tasks": [
    {
      "id": "RQ-0001",
      "status": "todo",
      "title": "Missing created_at should stall queue read",
      "priority": "medium",
      "updated_at": "2026-04-01T00:00:00Z"
    }
  ]
}
"#,
    )?;

    let (validate_status, validate_stdout, validate_stderr) =
        run_in_dir(dir.path(), &["queue", "validate"]);
    assert!(
        !validate_status.success(),
        "queue validate should reject missing created_at\nstdout:\n{validate_stdout}\nstderr:\n{validate_stderr}"
    );

    let (status, stdout, stderr) = run_in_dir(dir.path(), &["machine", "queue", "read"]);
    assert!(
        status.success(),
        "machine queue read should emit a validation-gated snapshot\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );

    let document: Value = serde_json::from_str(&stdout)?;
    assert!(
        document.get("next_runnable_task_id").is_none()
            || document["next_runnable_task_id"].is_null(),
        "invalid queue must not advertise a next runnable task: {stdout}"
    );
    assert!(document["runnability"]["selection"]["selected_task_id"].is_null());
    assert!(document["runnability"]["selection"]["selected_task_status"].is_null());
    assert_eq!(document["runnability"]["summary"]["runnable_candidates"], 0);
    let blocking = &document["runnability"]["summary"]["blocking"];
    assert_eq!(blocking["status"], "stalled");
    assert_eq!(blocking["reason"]["kind"], "operator_recovery");
    assert_eq!(blocking["reason"]["scope"], "queue_validate");
    assert_eq!(blocking["reason"]["reason"], "validation_failed");
    assert!(
        blocking["detail"]
            .as_str()
            .unwrap_or_default()
            .contains("Missing created_at"),
        "blocking detail should include validation failure: {stdout}"
    );
    Ok(())
}

#[test]
fn machine_workspace_overview_returns_queue_and_config_in_one_document() -> Result<()> {
    let dir = setup_cueloop_repo()?;

    let (status, stdout, stderr) = run_in_dir(dir.path(), &["machine", "workspace", "overview"]);
    assert!(
        status.success(),
        "machine workspace overview failed\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );

    let document: Value = serde_json::from_str(&stdout)?;
    assert_eq!(document["version"], 1);
    assert_eq!(document["queue"]["version"], 1);
    assert_eq!(document["config"]["version"], 5);
    assert!(document["queue"]["paths"]["queue_path"].is_string());
    assert!(document["queue"]["active"]["tasks"].is_array());
    assert!(document["config"]["paths"]["project_config_path"].is_string());
    assert!(document["config"]["config"].is_object());
    assert!(document["config"]["execution_controls"]["runners"].is_array());
    assert_eq!(
        document["config"]["execution_controls"]["parallel_workers"]["max"],
        255
    );
    Ok(())
}

#[test]
fn machine_config_resolve_succeeds_without_queue_file_and_omits_resume_preview() -> Result<()> {
    let dir = setup_cueloop_repo()?;
    let queue_path = dir.path().join(".cueloop/queue.jsonc");
    std::fs::remove_file(&queue_path)?;

    let (status, stdout, stderr) = run_in_dir(dir.path(), &["machine", "config", "resolve"]);
    assert!(
        status.success(),
        "machine config resolve should succeed without a queue file\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    assert!(
        stderr.trim().is_empty(),
        "machine config resolve should not emit stderr on success: {stderr}"
    );

    let document: Value = serde_json::from_str(&stdout)?;
    assert_eq!(document["version"], 5);
    assert!(document["paths"]["queue_path"].is_string());
    assert!(document["config"].is_object());
    assert!(document["execution_controls"]["runners"].is_array());
    assert!(
        document.get("resume_preview").is_none() || document["resume_preview"].is_null(),
        "resume_preview should be omitted or null when queue file is unavailable: {stdout}"
    );
    assert!(
        !queue_path.exists(),
        "machine config resolve must not recreate missing queue files"
    );
    Ok(())
}

#[test]
fn machine_config_resolve_docs_example_matches_execution_controls_contract() -> Result<()> {
    let dir = setup_cueloop_repo()?;

    let (status, stdout, stderr) = run_in_dir(dir.path(), &["machine", "config", "resolve"]);
    assert!(
        status.success(),
        "machine config resolve failed\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );

    let live: Value = serde_json::from_str(&stdout)?;
    let docs = std::fs::read_to_string(
        std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../..")
            .join("docs/features/session-management.md"),
    )?;
    let example = session_management_config_preview_example(&docs)
        .context("session-management config preview JSON example")?;

    assert_eq!(
        example["execution_controls"]["reasoning_efforts"],
        live["execution_controls"]["reasoning_efforts"],
        "session-management config preview reasoning efforts must match live machine config resolve output"
    );
    assert_eq!(
        example["execution_controls"]["parallel_workers"],
        live["execution_controls"]["parallel_workers"],
        "session-management config preview parallel worker bounds must match live machine config resolve output"
    );

    Ok(())
}

fn session_management_config_preview_example(docs: &str) -> Result<Value> {
    for block in docs.split("```json").skip(1) {
        let Some((json, _after)) = block.split_once("```") else {
            continue;
        };
        if json.contains("\"execution_controls\"") && json.contains("\"resume_preview\"") {
            return serde_json::from_str(json)
                .context("parse session-management config preview JSON");
        }
    }
    anyhow::bail!("session-management config preview JSON block not found")
}

#[test]
fn machine_config_resolve_reports_plugin_registry_load_failures_as_diagnostics() -> Result<()> {
    let dir = setup_cueloop_repo()?;
    trust_project_commands(dir.path())?;
    let plugin_dir = dir.path().join(".cueloop/plugins/broken.runner");
    std::fs::create_dir_all(&plugin_dir)?;
    std::fs::write(plugin_dir.join("plugin.json"), "{not valid json")?;

    let (status, stdout, stderr) = run_in_dir(dir.path(), &["machine", "config", "resolve"]);
    assert!(
        status.success(),
        "machine config resolve should degrade successfully for malformed plugins\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    assert!(
        stderr.trim().is_empty(),
        "successful plugin-registry degradation should be stdout-structured, not stderr text: {stderr}"
    );

    let document: Value = serde_json::from_str(&stdout)?;
    assert_eq!(document["version"], 5);
    assert!(
        document["execution_controls"]["runners"]
            .as_array()
            .is_some_and(|runners| runners.iter().any(|runner| runner["id"] == "codex"))
    );
    assert_eq!(
        document["execution_controls"]["diagnostics"][0]["severity"],
        "warning"
    );
    assert_eq!(
        document["execution_controls"]["diagnostics"][0]["code"],
        "plugin_registry_load_failed"
    );
    assert_eq!(
        document["execution_controls"]["diagnostics"][0]["fallback"],
        "built_in_runners_only"
    );
    assert!(
        document["execution_controls"]["diagnostics"][0]
            .get("plugin_id")
            .is_none(),
        "whole-registry failures should not name one plugin id: {stdout}"
    );
    assert!(
        document["execution_controls"]["diagnostics"][0]["detail"]
            .as_str()
            .unwrap_or_default()
            .contains("broken.runner"),
        "diagnostic detail should explain the malformed manifest path: {stdout}"
    );
    Ok(())
}

#[test]
fn machine_config_resolve_reports_plugin_runner_id_conflicts_as_diagnostics() -> Result<()> {
    let dir = setup_cueloop_repo()?;
    trust_project_commands(dir.path())?;
    let plugin_dir = dir.path().join(".cueloop/plugins/codex-shadow.runner");
    std::fs::create_dir_all(&plugin_dir)?;
    std::fs::write(
        plugin_dir.join("plugin.json"),
        r#"{
  "api_version": 1,
  "id": "CODEX",
  "version": "1.0.0",
  "name": "Codex Shadow Plugin",
  "runner": {
    "bin": "runner.sh"
  }
}"#,
    )?;
    std::fs::write(
        dir.path().join(".cueloop/config.jsonc"),
        r#"{
  "version": 2,
  "plugins": {
    "plugins": {
      "CODEX": {
        "enabled": true
      }
    }
  }
}"#,
    )?;

    let (status, stdout, stderr) = run_in_dir(dir.path(), &["machine", "config", "resolve"]);
    assert!(
        status.success(),
        "machine config resolve should skip conflicting plugin runners without failing\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    assert!(
        stderr.trim().is_empty(),
        "successful plugin-runner conflict degradation should be stdout-structured, not stderr text: {stderr}"
    );

    let document: Value = serde_json::from_str(&stdout)?;
    assert_eq!(
        document["execution_controls"]["diagnostics"][0]["code"],
        "plugin_runner_id_conflict"
    );
    assert_eq!(
        document["execution_controls"]["diagnostics"][0]["plugin_id"],
        "CODEX"
    );
    assert_eq!(
        document["execution_controls"]["diagnostics"][0]["fallback"],
        "skipped_plugin_runner"
    );
    assert!(
        document["execution_controls"]["runners"]
            .as_array()
            .is_some_and(|runners| runners
                .iter()
                .filter(|runner| runner["id"]
                    .as_str()
                    .is_some_and(|id| id.eq_ignore_ascii_case("codex")))
                .count()
                == 1)
    );
    Ok(())
}

#[test]
fn machine_config_resolve_reports_untrusted_execution_settings_as_config_error() -> Result<()> {
    let dir = setup_cueloop_repo()?;
    std::fs::remove_file(dir.path().join(".cueloop/trust.jsonc"))?;
    std::fs::write(
        dir.path().join(".cueloop/config.jsonc"),
        SENSITIVE_PROJECT_CONFIG,
    )?;

    let (status, stdout, stderr) = run_in_dir(dir.path(), &["machine", "config", "resolve"]);
    assert!(
        !status.success(),
        "machine config resolve should fail for untrusted execution-sensitive project config\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    assert!(
        stdout.trim().is_empty(),
        "failure stdout should stay empty: {stdout}"
    );

    let document: Value = serde_json::from_str(&stderr)?;
    assert_eq!(document["version"], 1);
    assert_eq!(document["code"], "config_incompatible");
    assert_eq!(
        document["message"],
        "Project config defines execution-sensitive settings, but this repo is not trusted."
    );
    assert_eq!(document["retryable"], false);
    let detail = document["detail"].as_str().unwrap_or_default();
    assert!(
        detail.contains("repo is not trusted")
            && detail.contains("cueloop init")
            && detail.contains("cueloop config trust init"),
        "detail should preserve trust remediation: {stderr}"
    );
    Ok(())
}

#[test]
fn machine_workspace_overview_still_fails_without_queue_file() -> Result<()> {
    let dir = setup_cueloop_repo()?;
    std::fs::remove_file(dir.path().join(".cueloop/queue.jsonc"))?;

    let (status, stdout, stderr) = run_in_dir(dir.path(), &["machine", "workspace", "overview"]);
    assert!(
        !status.success(),
        "machine workspace overview should still fail without a queue file\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    assert!(
        stdout.trim().is_empty(),
        "failure stdout should stay empty: {stdout}"
    );

    let document: Value = serde_json::from_str(&stderr)?;
    assert_eq!(document["version"], 1);
    assert_eq!(document["code"], "queue_corrupted");
    assert_eq!(document["message"], "No CueLoop queue file found.");
    Ok(())
}

#[cfg(unix)]
#[test]
fn machine_config_resolve_fails_when_queue_path_metadata_is_inaccessible() -> Result<()> {
    use std::os::unix::fs::PermissionsExt;

    let dir = setup_cueloop_repo()?;
    let restricted_dir = dir.path().join("restricted");
    let queue_path = restricted_dir.join("queue.jsonc");
    let config_path = dir.path().join(".cueloop/config.jsonc");
    let config_contents = format!(
        "{{\n  \"queue\": {{\n    \"file\": {}\n  }}\n}}\n",
        serde_json::to_string(&queue_path.display().to_string())?
    );

    std::fs::create_dir(&restricted_dir)?;
    std::fs::write(&config_path, config_contents)?;
    std::fs::set_permissions(&restricted_dir, std::fs::Permissions::from_mode(0o000))?;

    let (status, stdout, stderr) = run_in_dir(dir.path(), &["machine", "config", "resolve"]);

    std::fs::set_permissions(&restricted_dir, std::fs::Permissions::from_mode(0o755))?;

    assert!(
        !status.success(),
        "machine config resolve should fail when queue-path metadata cannot be inspected\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    assert!(
        stdout.trim().is_empty(),
        "failure stdout should stay empty: {stdout}"
    );

    let document: Value = serde_json::from_str(&stderr)?;
    assert_eq!(document["version"], 1);
    assert_eq!(document["code"], "permission_denied");
    assert_eq!(document["message"], "Permission denied.");
    assert!(
        document["detail"]
            .as_str()
            .unwrap_or_default()
            .contains("inspect queue file"),
        "structured detail should explain the failed queue-path inspection: {stderr}"
    );
    Ok(())
}

#[test]
fn machine_queue_read_preserves_group_kind_and_selects_work_item() -> Result<()> {
    let dir = setup_cueloop_repo()?;
    let queue_path = dir.path().join(".cueloop/queue.jsonc");
    std::fs::write(
        &queue_path,
        r#"{
  "version": 1,
  "tasks": [
    {
      "id": "RQ-0001",
      "status": "todo",
      "kind": "group",
      "title": "Umbrella",
      "priority": "high",
      "created_at": "2026-04-01T00:00:00Z",
      "updated_at": "2026-04-01T00:00:00Z"
    },
    {
      "id": "RQ-0002",
      "status": "todo",
      "kind": "work_item",
      "title": "Leaf",
      "priority": "high",
      "created_at": "2026-04-01T00:00:00Z",
      "updated_at": "2026-04-01T00:00:00Z"
    }
  ]
}
"#,
    )?;

    let (status, stdout, stderr) = run_in_dir(dir.path(), &["machine", "queue", "read"]);
    assert!(
        status.success(),
        "machine queue read failed\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );

    let document: Value = serde_json::from_str(&stdout)?;
    assert_eq!(document["active"]["tasks"][0]["kind"], "group");
    assert_eq!(document["runnability"]["tasks"][0]["kind"], "group");
    assert_eq!(document["next_runnable_task_id"], "RQ-0002");
    assert_eq!(
        document["runnability"]["selection"]["selected_task_id"],
        "RQ-0002"
    );
    Ok(())
}

#[test]
fn machine_queue_read_validation_failed_counts_only_executable_candidates() -> Result<()> {
    let dir = setup_cueloop_repo()?;
    let queue_path = dir.path().join(".cueloop/queue.jsonc");
    std::fs::write(
        &queue_path,
        r#"{
  "version": 1,
  "tasks": [
    {
      "id": "RQ-0001",
      "status": "todo",
      "kind": "group",
      "title": "Umbrella",
      "priority": "high",
      "created_at": "2026-04-01T00:00:00Z",
      "updated_at": "2026-04-01T00:00:00Z"
    },
    {
      "id": "RQ-0001",
      "status": "todo",
      "kind": "work_item",
      "title": "Duplicate work item",
      "priority": "high",
      "created_at": "2026-04-01T00:00:00Z",
      "updated_at": "2026-04-01T00:00:00Z"
    }
  ]
}
"#,
    )?;

    let (status, stdout, stderr) = run_in_dir(dir.path(), &["machine", "queue", "read"]);
    assert!(
        status.success(),
        "machine queue read should return recovery document for invalid queue\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );

    let document: Value = serde_json::from_str(&stdout)?;
    assert_eq!(document["next_runnable_task_id"], Value::Null);
    assert_eq!(document["runnability"]["summary"]["candidates_total"], 1);
    assert_eq!(
        document["runnability"]["summary"]["blocking"]["reason"]["kind"],
        "operator_recovery"
    );
    Ok(())
}