taskfast-cli 0.17.3

`taskfast` CLI: worker + poster hot-loop operations, JSON-envelope output.
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
// SPDX-License-Identifier: MIT
//! End-to-end tests for `taskfast task` read path (list + get).
//!
//! Each test stands up a wiremock server, drives `cmd::task::run`
//! directly, and asserts on the JSON envelope shape.

use std::io::Write;

use serde_json::json;
use wiremock::matchers::{method, path, query_param, query_param_is_missing};
use wiremock::{Mock, MockServer, ResponseTemplate};

use taskfast_cli::cmd::task::{
    run, ApproveArgs, CancelArgs, Command, DisputeArgs, GetArgs, ListArgs, ListKind, SubmitArgs,
    TaskStatus,
};
use taskfast_cli::cmd::{CmdError, Ctx};
use taskfast_cli::{Envelope, Environment};

const TASK_ID: &str = "00000000-0000-0000-0000-0000000000aa";

fn ctx_for(server: &MockServer, key: Option<&str>) -> Ctx {
    Ctx {
        api_key: key.map(String::from),
        environment: Environment::Local,
        api_base: Some(server.uri()),
        config_path: std::path::PathBuf::from("/dev/null"),
        dry_run: false,
        quiet: true,
        ..Default::default()
    }
}

fn envelope_value(env: &Envelope) -> serde_json::Value {
    serde_json::to_value(env).expect("serialize envelope")
}

fn paginated(cursor: Option<&str>) -> serde_json::Value {
    match cursor {
        Some(c) => json!({ "next_cursor": c, "has_more": true, "total_count": 0 }),
        None => json!({ "next_cursor": null, "has_more": false, "total_count": 0 }),
    }
}

#[tokio::test]
async fn list_mine_forwards_status_and_cursor_and_returns_tasks() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/agents/me/tasks"))
        .and(query_param("status", "in_progress"))
        .and(query_param("cursor", "abc"))
        .and(query_param("limit", "5"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": [],
            "meta": paginated(Some("next-abc")),
        })))
        .mount(&server)
        .await;

    let args = ListArgs {
        kind: ListKind::Mine,
        status: Some(TaskStatus::InProgress),
        cursor: Some("abc".into()),
        limit: 5,
    };
    let envelope = run(&ctx_for(&server, Some("test-key")), Command::List(args))
        .await
        .expect("list mine should succeed");

    let v = envelope_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["kind"], "mine");
    assert_eq!(v["data"]["meta"]["next_cursor"], "next-abc");
    assert_eq!(v["data"]["tasks"], json!([]));
}

#[tokio::test]
async fn list_queue_hits_queue_endpoint() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/agents/me/queue"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": [],
            "meta": paginated(None),
        })))
        .mount(&server)
        .await;

    let args = ListArgs {
        kind: ListKind::Queue,
        status: None,
        cursor: None,
        limit: 20,
    };
    let envelope = run(&ctx_for(&server, Some("test-key")), Command::List(args))
        .await
        .expect("list queue should succeed");

    let v = envelope_value(&envelope);
    assert_eq!(v["data"]["kind"], "queue");
}

#[tokio::test]
async fn list_posted_hits_posted_endpoint() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/agents/me/posted_tasks"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": [],
            "meta": paginated(None),
        })))
        .mount(&server)
        .await;

    let args = ListArgs {
        kind: ListKind::Posted,
        status: None,
        cursor: None,
        limit: 20,
    };
    let envelope = run(&ctx_for(&server, Some("test-key")), Command::List(args))
        .await
        .expect("list posted should succeed");

    let v = envelope_value(&envelope);
    assert_eq!(v["data"]["kind"], "posted");
}

#[tokio::test]
async fn list_status_with_non_mine_kind_is_usage_error() {
    // No server hit expected — usage error fires before any HTTP call.
    let server = MockServer::start().await;
    let args = ListArgs {
        kind: ListKind::Queue,
        status: Some(TaskStatus::Assigned),
        cursor: None,
        limit: 20,
    };
    let err = run(&ctx_for(&server, Some("test-key")), Command::List(args))
        .await
        .expect_err("status + non-mine kind must fail");
    match err {
        CmdError::Usage(msg) => assert!(msg.contains("--status"), "got: {msg}"),
        other => panic!("expected Usage, got {other:?}"),
    }
}

/// Fixture builder for the minimum required fields of `AgentTaskSummary`
/// in the `/agents/me/tasks` response envelope.
fn mine_task(id: &str, status: &str) -> serde_json::Value {
    json!({
        "id": id,
        "title": format!("task {id}"),
        "description": "desc",
        "budget_max": "1.00",
        "status": status,
    })
}

#[tokio::test]
async fn list_mine_omits_status_param_and_passes_server_page_through() {
    // #121: the server owns the active-status classification. With no
    // `--status`, the CLI sends no `status` param and returns the server's
    // page verbatim — no client-side filtering or re-paging. The
    // `query_param_is_missing` matcher fails the request (→ 404) if the CLI
    // ever leaks a `status` param on the default path.
    let server = MockServer::start().await;
    let body = json!({
        "data": [
            mine_task("00000000-0000-0000-0000-000000000001", "in_progress"),
            mine_task("00000000-0000-0000-0000-000000000003", "assigned"),
            mine_task("00000000-0000-0000-0000-000000000005", "under_review"),
        ],
        "meta": paginated(None),
    });
    Mock::given(method("GET"))
        .and(path("/agents/me/tasks"))
        .and(query_param_is_missing("status"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    let args = ListArgs {
        kind: ListKind::Mine,
        status: None,
        cursor: None,
        limit: 20,
    };
    let envelope = run(&ctx_for(&server, Some("test-key")), Command::List(args))
        .await
        .expect("list mine should succeed");

    let v = envelope_value(&envelope);
    let statuses: Vec<String> = v["data"]["tasks"]
        .as_array()
        .expect("tasks array")
        .iter()
        .map(|t| t["status"].as_str().unwrap().to_string())
        .collect();
    // Returned verbatim — the CLI neither drops nor reorders the server page.
    assert_eq!(statuses, vec!["in_progress", "assigned", "under_review"]);
}

#[tokio::test]
async fn get_returns_task_detail() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path(format!("/tasks/{TASK_ID}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "id": TASK_ID,
            "title": "test task",
            "status": "open",
            "description": "hello",
        })))
        .mount(&server)
        .await;

    let envelope = run(
        &ctx_for(&server, Some("test-key")),
        Command::Get(GetArgs { id: TASK_ID.into() }),
    )
    .await
    .expect("get should succeed");

    let v = envelope_value(&envelope);
    assert_eq!(v["data"]["task"]["id"], TASK_ID);
    assert_eq!(v["data"]["task"]["title"], "test task");
}

#[tokio::test]
async fn get_bad_uuid_is_usage_error_without_hitting_server() {
    let server = MockServer::start().await;
    // Deliberately no mock — a hit would 404 and fail the test.

    let err = run(
        &ctx_for(&server, Some("test-key")),
        Command::Get(GetArgs {
            id: "not-a-uuid".into(),
        }),
    )
    .await
    .expect_err("bad uuid must error locally");
    match err {
        CmdError::Usage(msg) => assert!(msg.contains("UUID"), "got: {msg}"),
        other => panic!("expected Usage, got {other:?}"),
    }
}

#[tokio::test]
async fn get_404_surfaces_as_validation_error() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path(format!("/tasks/{TASK_ID}")))
        .respond_with(ResponseTemplate::new(404).set_body_json(json!({
            "error": "task_not_found",
            "message": "no task with that id",
        })))
        .mount(&server)
        .await;

    let err = run(
        &ctx_for(&server, Some("test-key")),
        Command::Get(GetArgs { id: TASK_ID.into() }),
    )
    .await
    .expect_err("404 must surface as Validation per client mapping");
    match err {
        CmdError::Validation { code, .. } => assert_eq!(code, "task_not_found"),
        other => panic!("expected Validation, got {other:?}"),
    }
}

#[tokio::test]
async fn list_401_surfaces_as_auth_error() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/agents/me/tasks"))
        .respond_with(ResponseTemplate::new(401).set_body_json(json!({
            "error": "invalid_api_key",
            "message": "bad key",
        })))
        .mount(&server)
        .await;

    let args = ListArgs {
        kind: ListKind::Mine,
        status: None,
        cursor: None,
        limit: 20,
    };
    let err = run(&ctx_for(&server, Some("test-key")), Command::List(args))
        .await
        .expect_err("401 must surface as Auth");
    match err {
        CmdError::Auth(_) => {}
        other => panic!("expected Auth, got {other:?}"),
    }
}

#[tokio::test]
async fn missing_api_key_errors_before_any_http_call() {
    let server = MockServer::start().await;
    let args = ListArgs {
        kind: ListKind::Mine,
        status: None,
        cursor: None,
        limit: 20,
    };
    let err = run(&ctx_for(&server, None), Command::List(args))
        .await
        .expect_err("no key → MissingApiKey");
    assert!(matches!(err, CmdError::MissingApiKey), "got {err:?}");
}

#[tokio::test]
async fn submit_zero_artifact_happy_path() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/submit")))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "success": true,
            "task_id": TASK_ID,
            "status": "under_review",
            "message": "submitted",
            "evaluation": {
                "passed": true,
                "criteria_results": [],
                "evaluated_at": "2026-04-13T21:00:00Z",
            },
        })))
        .mount(&server)
        .await;

    let envelope = run(
        &ctx_for(&server, Some("test-key")),
        Command::Submit(SubmitArgs {
            id: TASK_ID.into(),
            summary: "done".into(),
            artifact: vec![],
        }),
    )
    .await
    .expect("submit should succeed");

    let v = envelope_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["task_id"], TASK_ID);
    assert_eq!(v["data"]["artifacts"], json!([]));
    assert_eq!(v["data"]["submission"]["status"], "under_review");
}

#[tokio::test]
async fn submit_with_artifacts_uploads_each_then_submits() {
    let server = MockServer::start().await;
    let tmp = tempfile::tempdir().expect("tempdir");
    let p1 = tmp.path().join("results.json");
    let p2 = tmp.path().join("notes.txt");
    {
        let mut f = std::fs::File::create(&p1).unwrap();
        f.write_all(br#"{"ok":true}"#).unwrap();
    }
    {
        let mut f = std::fs::File::create(&p2).unwrap();
        f.write_all(b"hello").unwrap();
    }

    let artifact1_id = "00000000-0000-0000-0000-0000000000f1";
    let artifact2_id = "00000000-0000-0000-0000-0000000000f2";

    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/artifacts")))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "id": artifact1_id,
            "filename": "results.json",
            "content_type": "application/json",
            "url": "https://example/results.json",
            "size_bytes": 11,
            "created_at": "2026-04-13T21:00:00Z",
        })))
        .up_to_n_times(1)
        .mount(&server)
        .await;

    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/artifacts")))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "id": artifact2_id,
            "filename": "notes.txt",
            "content_type": "text/plain",
            "url": "https://example/notes.txt",
            "size_bytes": 5,
            "created_at": "2026-04-13T21:00:01Z",
        })))
        .mount(&server)
        .await;

    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/submit")))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "success": true,
            "task_id": TASK_ID,
            "status": "under_review",
            "message": "submitted",
            "evaluation": {
                "passed": true,
                "criteria_results": [],
                "evaluated_at": "2026-04-13T21:00:00Z",
            },
        })))
        .mount(&server)
        .await;

    let envelope = run(
        &ctx_for(&server, Some("test-key")),
        Command::Submit(SubmitArgs {
            id: TASK_ID.into(),
            summary: "two files".into(),
            artifact: vec![p1.clone(), p2.clone()],
        }),
    )
    .await
    .expect("submit should succeed");

    let v = envelope_value(&envelope);
    assert_eq!(v["data"]["artifacts"].as_array().unwrap().len(), 2);
    assert_eq!(v["data"]["artifacts"][0]["id"], artifact1_id);
    assert_eq!(v["data"]["artifacts"][1]["id"], artifact2_id);
    assert_eq!(v["data"]["submission"]["status"], "under_review");
}

#[tokio::test]
async fn submit_missing_artifact_file_is_usage_error_without_hitting_server() {
    let server = MockServer::start().await;
    let err = run(
        &ctx_for(&server, Some("test-key")),
        Command::Submit(SubmitArgs {
            id: TASK_ID.into(),
            summary: "x".into(),
            artifact: vec![std::path::PathBuf::from("/definitely/not/a/real/path.json")],
        }),
    )
    .await
    .expect_err("missing file must fail locally");
    match err {
        CmdError::Usage(msg) => assert!(msg.contains("not found"), "got: {msg}"),
        other => panic!("expected Usage, got {other:?}"),
    }
}

#[tokio::test]
async fn submit_bad_uuid_is_usage_error_without_hitting_server() {
    let server = MockServer::start().await;
    let err = run(
        &ctx_for(&server, Some("test-key")),
        Command::Submit(SubmitArgs {
            id: "not-a-uuid".into(),
            summary: "x".into(),
            artifact: vec![],
        }),
    )
    .await
    .expect_err("bad uuid must error locally");
    assert!(matches!(err, CmdError::Usage(_)), "got: {err:?}");
}

#[tokio::test]
async fn submit_dry_run_short_circuits_without_uploading() {
    // No mock — any HTTP call would fail the test.
    let server = MockServer::start().await;
    let tmp = tempfile::tempdir().expect("tempdir");
    let p1 = tmp.path().join("x.txt");
    std::fs::write(&p1, b"abc").unwrap();

    let mut ctx = ctx_for(&server, Some("test-key"));
    ctx.dry_run = true;
    let envelope = run(
        &ctx,
        Command::Submit(SubmitArgs {
            id: TASK_ID.into(),
            summary: "dry".into(),
            artifact: vec![p1.clone()],
        }),
    )
    .await
    .expect("dry-run submit should succeed");

    let v = envelope_value(&envelope);
    assert_eq!(v["dry_run"], true);
    assert_eq!(v["data"]["action"], "would_submit");
    assert_eq!(v["data"]["task_id"], TASK_ID);
    assert_eq!(v["data"]["artifacts"][0], p1.display().to_string());
}

#[tokio::test]
async fn submit_upload_401_surfaces_as_auth_error() {
    let server = MockServer::start().await;
    let tmp = tempfile::tempdir().expect("tempdir");
    let p1 = tmp.path().join("x.txt");
    std::fs::write(&p1, b"abc").unwrap();

    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/artifacts")))
        .respond_with(ResponseTemplate::new(401).set_body_json(json!({
            "error": "invalid_api_key",
            "message": "bad key",
        })))
        .mount(&server)
        .await;

    let err = run(
        &ctx_for(&server, Some("test-key")),
        Command::Submit(SubmitArgs {
            id: TASK_ID.into(),
            summary: "x".into(),
            artifact: vec![p1],
        }),
    )
    .await
    .expect_err("401 on upload must surface as Auth");
    match err {
        CmdError::Auth(_) => {}
        other => panic!("expected Auth, got {other:?}"),
    }
}

// ─── task approve ─────────────────────────────────────────────────────────

#[tokio::test]
async fn approve_happy_path_returns_task_id_and_status() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/approve")))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "task_id": TASK_ID,
            "status": "complete",
        })))
        .mount(&server)
        .await;
    let envelope = run(
        &ctx_for(&server, Some("test-key")),
        Command::Approve(ApproveArgs { id: TASK_ID.into() }),
    )
    .await
    .expect("approve ok");
    let v = envelope_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["task_id"], TASK_ID);
    assert_eq!(v["data"]["status"], "complete");
}

#[tokio::test]
async fn approve_dry_run_skips_http() {
    let server = MockServer::start().await; // no mocks
    let mut ctx = ctx_for(&server, Some("test-key"));
    ctx.dry_run = true;
    let envelope = run(&ctx, Command::Approve(ApproveArgs { id: TASK_ID.into() }))
        .await
        .expect("dry-run ok");
    let v = envelope_value(&envelope);
    assert_eq!(v["dry_run"], true);
    assert_eq!(v["data"]["action"], "would_approve");
    assert_eq!(v["data"]["task_id"], TASK_ID);
}

#[tokio::test]
async fn approve_bad_uuid_is_usage_error_without_any_http() {
    let server = MockServer::start().await;
    let err = run(
        &ctx_for(&server, Some("test-key")),
        Command::Approve(ApproveArgs {
            id: "not-a-uuid".into(),
        }),
    )
    .await
    .expect_err("bad UUID");
    assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
}

#[tokio::test]
async fn approve_403_surfaces_as_auth() {
    // 403 = "only the task poster can approve". Client maps 401|403 → Auth
    // (see taskfast_client::client::map_api_error) — forbidden is treated as
    // an auth problem, not a validation one. Orchestrators use the Auth exit
    // code to decide "re-credential" rather than "retry payload".
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/approve")))
        .respond_with(ResponseTemplate::new(403).set_body_json(json!({
            "error": "not_poster",
            "message": "only the task poster can approve",
        })))
        .mount(&server)
        .await;
    let err = run(
        &ctx_for(&server, Some("test-key")),
        Command::Approve(ApproveArgs { id: TASK_ID.into() }),
    )
    .await
    .expect_err("403 must surface");
    assert!(matches!(err, CmdError::Auth(_)), "got {err:?}");
}

#[tokio::test]
async fn approve_409_surfaces() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/approve")))
        .respond_with(ResponseTemplate::new(409).set_body_json(json!({
            "error": "wrong_status",
            "message": "task is not in under_review",
        })))
        .mount(&server)
        .await;
    let err = run(
        &ctx_for(&server, Some("test-key")),
        Command::Approve(ApproveArgs { id: TASK_ID.into() }),
    )
    .await
    .expect_err("409 must surface");
    assert!(
        matches!(err, CmdError::Validation { .. } | CmdError::Server(_)),
        "got {err:?}"
    );
}

#[tokio::test]
async fn approve_401_surfaces_as_auth() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/approve")))
        .respond_with(ResponseTemplate::new(401).set_body_json(json!({
            "error": "invalid_api_key",
            "message": "bad key",
        })))
        .mount(&server)
        .await;
    let err = run(
        &ctx_for(&server, Some("test-key")),
        Command::Approve(ApproveArgs { id: TASK_ID.into() }),
    )
    .await
    .expect_err("401 must surface");
    assert!(matches!(err, CmdError::Auth(_)), "got {err:?}");
}

#[tokio::test]
async fn approve_missing_api_key_errors_before_any_http() {
    let server = MockServer::start().await;
    let err = run(
        &ctx_for(&server, None),
        Command::Approve(ApproveArgs { id: TASK_ID.into() }),
    )
    .await
    .expect_err("no key");
    assert!(matches!(err, CmdError::MissingApiKey), "got {err:?}");
}

// ─── task dispute ─────────────────────────────────────────────────────────

#[tokio::test]
async fn dispute_happy_path_returns_dispute_block() {
    let server = MockServer::start().await;
    let dispute_id = "00000000-0000-0000-0000-00000000d15b";
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/dispute")))
        .and(wiremock::matchers::body_partial_json(json!({
            "reason": "not what I asked for",
        })))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "success": true,
            "task_id": TASK_ID,
            "status": "disputed",
            "message": "Dispute raised successfully",
            "dispute": {
                "id": dispute_id,
                "reason": "not what I asked for",
                "remedy_deadline": "2026-04-20T00:00:00Z",
            },
        })))
        .mount(&server)
        .await;
    let envelope = run(
        &ctx_for(&server, Some("test-key")),
        Command::Dispute(DisputeArgs {
            id: TASK_ID.into(),
            reason: "not what I asked for".into(),
        }),
    )
    .await
    .expect("dispute ok");
    let v = envelope_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["status"], "disputed");
    assert_eq!(v["data"]["dispute"]["id"], dispute_id);
    assert_eq!(v["data"]["dispute"]["reason"], "not what I asked for");
}

#[tokio::test]
async fn dispute_dry_run_skips_http() {
    let server = MockServer::start().await;
    let mut ctx = ctx_for(&server, Some("test-key"));
    ctx.dry_run = true;
    let envelope = run(
        &ctx,
        Command::Dispute(DisputeArgs {
            id: TASK_ID.into(),
            reason: "because".into(),
        }),
    )
    .await
    .expect("dry-run ok");
    let v = envelope_value(&envelope);
    assert_eq!(v["dry_run"], true);
    assert_eq!(v["data"]["action"], "would_dispute");
    assert_eq!(v["data"]["reason"], "because");
}

#[tokio::test]
async fn dispute_bad_uuid_is_usage_error_without_any_http() {
    let server = MockServer::start().await;
    let err = run(
        &ctx_for(&server, Some("test-key")),
        Command::Dispute(DisputeArgs {
            id: "bad".into(),
            reason: "r".into(),
        }),
    )
    .await
    .expect_err("bad UUID");
    assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
}

#[tokio::test]
async fn dispute_empty_reason_is_usage_error_without_any_http() {
    let server = MockServer::start().await;
    let err = run(
        &ctx_for(&server, Some("test-key")),
        Command::Dispute(DisputeArgs {
            id: TASK_ID.into(),
            reason: "   \n".into(),
        }),
    )
    .await
    .expect_err("empty reason");
    match err {
        CmdError::Usage(m) => assert!(m.contains("--reason"), "unexpected: {m}"),
        other => panic!("expected Usage, got {other:?}"),
    }
}

#[tokio::test]
async fn dispute_409_surfaces() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/dispute")))
        .respond_with(ResponseTemplate::new(409).set_body_json(json!({
            "error": "already_disputed",
            "message": "dispute exists",
        })))
        .mount(&server)
        .await;
    let err = run(
        &ctx_for(&server, Some("test-key")),
        Command::Dispute(DisputeArgs {
            id: TASK_ID.into(),
            reason: "r".into(),
        }),
    )
    .await
    .expect_err("409 must surface");
    assert!(
        matches!(err, CmdError::Validation { .. } | CmdError::Server(_)),
        "got {err:?}"
    );
}

#[tokio::test]
async fn dispute_401_surfaces_as_auth() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/dispute")))
        .respond_with(ResponseTemplate::new(401).set_body_json(json!({
            "error": "invalid_api_key",
            "message": "bad key",
        })))
        .mount(&server)
        .await;
    let err = run(
        &ctx_for(&server, Some("test-key")),
        Command::Dispute(DisputeArgs {
            id: TASK_ID.into(),
            reason: "r".into(),
        }),
    )
    .await
    .expect_err("401");
    assert!(matches!(err, CmdError::Auth(_)), "got {err:?}");
}

// ─── task cancel ──────────────────────────────────────────────────────────

#[tokio::test]
async fn cancel_happy_path_returns_id_and_status() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/cancel")))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "id": TASK_ID,
            "status": "cancelled",
        })))
        .mount(&server)
        .await;
    let envelope = run(
        &ctx_for(&server, Some("test-key")),
        Command::Cancel(CancelArgs { id: TASK_ID.into() }),
    )
    .await
    .expect("cancel ok");
    let v = envelope_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["id"], TASK_ID);
    assert_eq!(v["data"]["status"], "cancelled");
}

#[tokio::test]
async fn cancel_dry_run_skips_http() {
    let server = MockServer::start().await;
    let mut ctx = ctx_for(&server, Some("test-key"));
    ctx.dry_run = true;
    let envelope = run(&ctx, Command::Cancel(CancelArgs { id: TASK_ID.into() }))
        .await
        .expect("dry-run ok");
    let v = envelope_value(&envelope);
    assert_eq!(v["dry_run"], true);
    assert_eq!(v["data"]["action"], "would_cancel");
    assert_eq!(v["data"]["task_id"], TASK_ID);
}

#[tokio::test]
async fn cancel_bad_uuid_is_usage_error_without_any_http() {
    let server = MockServer::start().await;
    let err = run(
        &ctx_for(&server, Some("test-key")),
        Command::Cancel(CancelArgs { id: "bad".into() }),
    )
    .await
    .expect_err("bad UUID");
    assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
}

#[tokio::test]
async fn cancel_409_surfaces_non_cancellable_state() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/cancel")))
        .respond_with(ResponseTemplate::new(409).set_body_json(json!({
            "error": "wrong_status",
            "message": "task cannot be cancelled from its current state",
        })))
        .mount(&server)
        .await;
    let err = run(
        &ctx_for(&server, Some("test-key")),
        Command::Cancel(CancelArgs { id: TASK_ID.into() }),
    )
    .await
    .expect_err("409 must surface");
    assert!(
        matches!(err, CmdError::Validation { .. } | CmdError::Server(_)),
        "got {err:?}"
    );
}

#[tokio::test]
async fn cancel_401_surfaces_as_auth() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/cancel")))
        .respond_with(ResponseTemplate::new(401).set_body_json(json!({
            "error": "invalid_api_key",
            "message": "bad key",
        })))
        .mount(&server)
        .await;
    let err = run(
        &ctx_for(&server, Some("test-key")),
        Command::Cancel(CancelArgs { id: TASK_ID.into() }),
    )
    .await
    .expect_err("401");
    assert!(matches!(err, CmdError::Auth(_)), "got {err:?}");
}