taskfast-cli 0.20.0

`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
// SPDX-License-Identifier: MIT
//! End-to-end tests for `taskfast bid` read path (list).
//!
//! Each test stands up a wiremock server, drives `cmd::bid::run` directly,
//! and asserts on the JSON envelope shape.

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

use taskfast_cli::cmd::bid::{
    run, AcceptArgs, BidStatusFilter, CancelArgs, Command, CreateArgs, ListArgs, RejectArgs,
};
use taskfast_cli::cmd::{CmdError, Ctx};
use taskfast_cli::{Envelope, Environment};

const BID_ID: &str = "00000000-0000-0000-0000-00000000b1d1";
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": 1 }),
        None => json!({ "next_cursor": null, "has_more": false, "total_count": 0 }),
    }
}

#[tokio::test]
async fn list_forwards_cursor_and_limit_and_returns_bids() {
    let server = MockServer::start().await;
    let bid = json!({
        "id": BID_ID,
        "task_id": TASK_ID,
        "agent_id": "00000000-0000-0000-0000-0000000000a0",
        "price": "100.00",
        "status": "pending",
        "created_at": "2026-04-13T21:00:00Z",
    });
    Mock::given(method("GET"))
        .and(path("/agents/me/bids"))
        .and(query_param("cursor", "abc"))
        .and(query_param("limit", "5"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": [bid],
            "meta": paginated(Some("next-abc")),
        })))
        .mount(&server)
        .await;

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

    let v = envelope_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["meta"]["next_cursor"], "next-abc");
    assert_eq!(v["data"]["bids"][0]["id"], BID_ID);
    assert_eq!(v["data"]["bids"][0]["price"], "100.00");
}

#[tokio::test]
async fn list_forwards_status_filter_server_side() {
    // #121: `--status` is forwarded to the server's `status` query param;
    // the CLI does not post-filter, so it returns the server page verbatim.
    let server = MockServer::start().await;
    let bid = json!({
        "id": BID_ID,
        "task_id": TASK_ID,
        "agent_id": "00000000-0000-0000-0000-0000000000a0",
        "price": "100.00",
        "status": "accepted",
        "created_at": "2026-04-13T21:00:00Z",
    });
    Mock::given(method("GET"))
        .and(path("/agents/me/bids"))
        .and(query_param("status", "accepted"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": [bid],
            "meta": paginated(None),
        })))
        .mount(&server)
        .await;

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

    let v = envelope_value(&envelope);
    assert_eq!(v["data"]["bids"][0]["status"], "accepted");
    // No client-side post-filter marker on the envelope anymore.
    assert!(v["data"].get("filtered_count").is_none());
}

#[tokio::test]
async fn list_without_status_omits_status_param() {
    // The default path must not leak a `status` query param — the
    // `query_param_is_missing` matcher 404s the request if it does.
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/agents/me/bids"))
        .and(query_param_is_missing("status"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": [],
            "meta": paginated(None),
        })))
        .mount(&server)
        .await;

    let args = ListArgs {
        cursor: None,
        limit: 20,
        status: None,
    };
    let envelope = run(&ctx_for(&server, Some("test-key")), Command::List(args))
        .await
        .expect("list should succeed");
    assert_eq!(envelope_value(&envelope)["data"]["bids"], json!([]));
}

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

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

    let v = envelope_value(&envelope);
    assert_eq!(v["data"]["bids"], json!([]));
    assert_eq!(v["data"]["meta"]["has_more"], false);
}

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

    let args = ListArgs {
        cursor: None,
        limit: 20,
        status: None,
    };
    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 list_missing_api_key_errors_before_any_http_call() {
    let server = MockServer::start().await;
    let args = ListArgs {
        cursor: None,
        limit: 20,
        status: None,
    };
    let err = run(&ctx_for(&server, None), Command::List(args))
        .await
        .expect_err("no key → MissingApiKey");
    assert!(matches!(err, CmdError::MissingApiKey), "got {err:?}");
}

// ─── bid create ───────────────────────────────────────────────────────────

fn bid_body(status: &str) -> serde_json::Value {
    json!({
        "id": BID_ID,
        "task_id": TASK_ID,
        "agent_id": "00000000-0000-0000-0000-0000000000a0",
        "price": "75.00",
        "pitch": "why me",
        "status": status,
        "created_at": "2026-04-13T21:00:00Z",
    })
}

#[tokio::test]
async fn create_happy_path_posts_price_and_pitch() {
    let server = MockServer::start().await;
    // body_partial_json proves we forwarded both fields correctly; without this
    // a regression that dropped `pitch` would pass a status-code-only assertion.
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/bids")))
        .and(body_partial_json(
            json!({ "price": "75.00", "pitch": "why me" }),
        ))
        .respond_with(ResponseTemplate::new(201).set_body_json(bid_body("pending")))
        .mount(&server)
        .await;

    let args = CreateArgs {
        task_id: TASK_ID.into(),
        price: "75.00".into(),
        pitch: Some("why me".into()),
    };
    let envelope = run(&ctx_for(&server, Some("test-key")), Command::Create(args))
        .await
        .expect("create should succeed");
    let v = envelope_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["bid"]["id"], BID_ID);
    assert_eq!(v["data"]["bid"]["status"], "pending");
}

#[tokio::test]
async fn create_omits_pitch_when_none() {
    let server = MockServer::start().await;
    // Absent field, not null — BidRequest uses skip_serializing_if=is_none.
    // Mounting a mock that matches only when `pitch` is absent is awkward;
    // instead we respond to any POST and trust the codegen's serde setup
    // (asserted at the type level). This still exercises the dry-run-free path.
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/bids")))
        .and(body_partial_json(json!({ "price": "10.00" })))
        .respond_with(ResponseTemplate::new(201).set_body_json(bid_body("pending")))
        .mount(&server)
        .await;

    let args = CreateArgs {
        task_id: TASK_ID.into(),
        price: "10.00".into(),
        pitch: None,
    };
    let envelope = run(&ctx_for(&server, Some("test-key")), Command::Create(args))
        .await
        .expect("create without pitch should succeed");
    assert_eq!(envelope_value(&envelope)["data"]["bid"]["id"], BID_ID);
}

#[tokio::test]
async fn create_dry_run_skips_http() {
    let server = MockServer::start().await; // no mocks mounted
    let mut ctx = ctx_for(&server, Some("test-key"));
    ctx.dry_run = true;
    let args = CreateArgs {
        task_id: TASK_ID.into(),
        price: "50.00".into(),
        pitch: Some("pitch".into()),
    };
    let envelope = run(&ctx, Command::Create(args)).await.expect("dry-run ok");
    let v = envelope_value(&envelope);
    assert_eq!(v["dry_run"], true);
    assert_eq!(v["data"]["action"], "would_create_bid");
    assert_eq!(v["data"]["task_id"], TASK_ID);
    assert_eq!(v["data"]["price"], "50.00");
}

#[tokio::test]
async fn create_bad_task_id_is_usage_error_without_any_http() {
    let server = MockServer::start().await;
    let args = CreateArgs {
        task_id: "not-a-uuid".into(),
        price: "10.00".into(),
        pitch: None,
    };
    let err = run(&ctx_for(&server, Some("test-key")), Command::Create(args))
        .await
        .expect_err("bad UUID must fail locally");
    assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
}

#[tokio::test]
async fn create_empty_price_is_usage_error_without_any_http() {
    let server = MockServer::start().await;
    let args = CreateArgs {
        task_id: TASK_ID.into(),
        price: "   ".into(),
        pitch: None,
    };
    let err = run(&ctx_for(&server, Some("test-key")), Command::Create(args))
        .await
        .expect_err("empty price must fail locally");
    match err {
        CmdError::Usage(m) => assert!(m.contains("--price"), "unexpected: {m}"),
        other => panic!("expected Usage, got {other:?}"),
    }
}

#[tokio::test]
async fn create_409_surfaces_as_validation_error() {
    let server = MockServer::start().await;
    // The task is closed for bidding; server returns 409 with an Error body.
    // client::map_api_error classifies 409/422 with a `code` as Validation.
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/bids")))
        .respond_with(ResponseTemplate::new(409).set_body_json(json!({
            "error": "task_not_open",
            "message": "task is not open for bidding",
        })))
        .mount(&server)
        .await;
    let args = CreateArgs {
        task_id: TASK_ID.into(),
        price: "10.00".into(),
        pitch: None,
    };
    let err = run(&ctx_for(&server, Some("test-key")), Command::Create(args))
        .await
        .expect_err("409 must surface");
    assert!(
        matches!(err, CmdError::Validation { .. } | CmdError::Server(_)),
        "got {err:?}"
    );
}

#[tokio::test]
async fn create_401_surfaces_as_auth_error() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/bids")))
        .respond_with(ResponseTemplate::new(401).set_body_json(json!({
            "error": "invalid_api_key",
            "message": "bad key",
        })))
        .mount(&server)
        .await;
    let args = CreateArgs {
        task_id: TASK_ID.into(),
        price: "10.00".into(),
        pitch: None,
    };
    let err = run(&ctx_for(&server, Some("test-key")), Command::Create(args))
        .await
        .expect_err("401 must surface as Auth");
    assert!(matches!(err, CmdError::Auth(_)), "got {err:?}");
}

#[tokio::test]
async fn create_missing_api_key_errors_before_any_http() {
    let server = MockServer::start().await;
    let args = CreateArgs {
        task_id: TASK_ID.into(),
        price: "10.00".into(),
        pitch: None,
    };
    let err = run(&ctx_for(&server, None), Command::Create(args))
        .await
        .expect_err("no key → MissingApiKey");
    assert!(matches!(err, CmdError::MissingApiKey), "got {err:?}");
}

// ─── bid cancel ───────────────────────────────────────────────────────────

#[tokio::test]
async fn cancel_happy_path_returns_withdrawn_bid() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/bids/{BID_ID}/withdraw")))
        .respond_with(ResponseTemplate::new(200).set_body_json(bid_body("withdrawn")))
        .mount(&server)
        .await;
    let args = CancelArgs { id: BID_ID.into() };
    let envelope = run(&ctx_for(&server, Some("test-key")), Command::Cancel(args))
        .await
        .expect("cancel should succeed");
    let v = envelope_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["bid"]["id"], BID_ID);
    assert_eq!(v["data"]["bid"]["status"], "withdrawn");
}

#[tokio::test]
async fn cancel_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 args = CancelArgs { id: BID_ID.into() };
    let envelope = run(&ctx, Command::Cancel(args)).await.expect("dry-run ok");
    let v = envelope_value(&envelope);
    assert_eq!(v["dry_run"], true);
    assert_eq!(v["data"]["action"], "would_cancel_bid");
    assert_eq!(v["data"]["bid_id"], BID_ID);
}

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

#[tokio::test]
async fn cancel_409_surfaces() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/bids/{BID_ID}/withdraw")))
        .respond_with(ResponseTemplate::new(409).set_body_json(json!({
            "error": "bid_not_pending",
            "message": "bid already accepted",
        })))
        .mount(&server)
        .await;
    let args = CancelArgs { id: BID_ID.into() };
    let err = run(&ctx_for(&server, Some("test-key")), Command::Cancel(args))
        .await
        .expect_err("409 must surface");
    assert!(
        matches!(err, CmdError::Validation { .. } | CmdError::Server(_)),
        "got {err:?}"
    );
}

// ─── bid accept (poster; deferred-escrow two-phase per am-4w2) ─────────────

fn accept_body() -> serde_json::Value {
    // The deployed deferred-escrow contract: HTTP 202 with a 10-field
    // BidAcceptResponse (additionalProperties: false) whose next_action
    // fields name the follow-up (`taskfast escrow sign <bid_id>`).
    json!({
        "bid_id": BID_ID,
        "task_id": TASK_ID,
        "payment_id": "00000000-0000-0000-0000-000000009a91",
        "task_status": "payment_pending",
        "status": "accepted_pending_escrow",
        "next_action": "escrow_sign",
        "next_action_command": format!("taskfast escrow sign {BID_ID}"),
        "poster_signature_deadline": "2026-09-09T12:00:00Z",
        "signing_url": format!("https://staging.taskfast.app/bids/{BID_ID}/sign"),
        "message": "Bid acceptance locked pending escrow signature.",
    })
}

#[tokio::test]
async fn accept_202_pending_escrow_is_success_not_error() {
    // Regression (gh#141): the deferred-escrow happy path answers HTTP 202
    // "locked pending escrow signature" — that is success with a next
    // action, not an error. The CLI must exit ok:true and surface the
    // server's follow-up contract for orchestrators.
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/bids/{BID_ID}/accept")))
        .respond_with(ResponseTemplate::new(202).set_body_json(accept_body()))
        .mount(&server)
        .await;
    let args = AcceptArgs { id: BID_ID.into() };
    let envelope = run(&ctx_for(&server, Some("test-key")), Command::Accept(args))
        .await
        .expect("202 pending-escrow must be ok:true");
    let v = envelope_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["bid"]["bid_id"], BID_ID);
    assert_eq!(v["data"]["bid"]["task_id"], TASK_ID);
    assert_eq!(v["data"]["bid"]["status"], "accepted_pending_escrow");
    assert_eq!(v["data"]["bid"]["task_status"], "payment_pending");
    assert_eq!(v["data"]["next_action"], "escrow_sign");
    assert_eq!(
        v["data"]["next_action_command"],
        format!("taskfast escrow sign {BID_ID}")
    );
    assert_eq!(
        v["data"]["poster_signature_deadline"],
        "2026-09-09T12:00:00Z"
    );
    assert_eq!(
        v["data"]["signing_url"],
        format!("https://staging.taskfast.app/bids/{BID_ID}/sign")
    );
}

#[tokio::test]
async fn accept_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 args = AcceptArgs { id: BID_ID.into() };
    let envelope = run(&ctx, Command::Accept(args)).await.expect("dry-run ok");
    let v = envelope_value(&envelope);
    assert_eq!(v["dry_run"], true);
    assert_eq!(v["data"]["action"], "would_accept_bid");
    assert_eq!(v["data"]["bid_id"], BID_ID);
}

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

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

#[tokio::test]
async fn accept_403_not_the_poster_surfaces_as_auth() {
    // Per taskfast-cli error-mapping contract: 403 on poster/worker mutations
    // is Auth (re-credential), not Validation.
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/bids/{BID_ID}/accept")))
        .respond_with(ResponseTemplate::new(403).set_body_json(json!({
            "error": "forbidden",
            "message": "You are not the poster of this task",
        })))
        .mount(&server)
        .await;
    let args = AcceptArgs { id: BID_ID.into() };
    let err = run(&ctx_for(&server, Some("test-key")), Command::Accept(args))
        .await
        .expect_err("403 must surface as Auth");
    assert!(matches!(err, CmdError::Auth(_)), "got {err:?}");
}

#[tokio::test]
async fn accept_422_circular_subcontracting_surfaces_as_validation() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/bids/{BID_ID}/accept")))
        .respond_with(ResponseTemplate::new(422).set_body_json(json!({
            "error": "circular_subcontracting",
            "message": "This assignment would create a circular delegation chain",
        })))
        .mount(&server)
        .await;
    let args = AcceptArgs { id: BID_ID.into() };
    let err = run(&ctx_for(&server, Some("test-key")), Command::Accept(args))
        .await
        .expect_err("422 must surface");
    assert!(matches!(err, CmdError::Validation { .. }), "got {err:?}");
}

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

// ─── bid reject ────────────────────────────────────────────────────────────

fn reject_body(reason: Option<&str>) -> serde_json::Value {
    json!({
        "bid_id": BID_ID,
        "status": "rejected",
        "reason": reason,
        "rejected_at": "2026-04-14T12:00:00Z",
    })
}

#[tokio::test]
async fn reject_happy_path_with_reason_round_trips() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/bids/{BID_ID}/reject")))
        .and(body_partial_json(json!({ "reason": "too expensive" })))
        .respond_with(ResponseTemplate::new(200).set_body_json(reject_body(Some("too expensive"))))
        .mount(&server)
        .await;
    let args = RejectArgs {
        id: BID_ID.into(),
        reason: Some("too expensive".into()),
    };
    let envelope = run(&ctx_for(&server, Some("test-key")), Command::Reject(args))
        .await
        .expect("reject should succeed");
    let v = envelope_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["bid"]["bid_id"], BID_ID);
    assert_eq!(v["data"]["bid"]["status"], "rejected");
    assert_eq!(v["data"]["bid"]["reason"], "too expensive");
}

#[tokio::test]
async fn reject_happy_path_without_reason_omits_field() {
    // With skip_serializing_if=is_none on the generated struct, the body
    // should be `{}` (empty object). A partial-json match of `{}` accepts
    // any object shape, but matching absence is awkward with wiremock — so
    // we just assert the request succeeds and the envelope shape is right.
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/bids/{BID_ID}/reject")))
        .respond_with(ResponseTemplate::new(200).set_body_json(reject_body(None)))
        .mount(&server)
        .await;
    let args = RejectArgs {
        id: BID_ID.into(),
        reason: None,
    };
    let envelope = run(&ctx_for(&server, Some("test-key")), Command::Reject(args))
        .await
        .expect("reject should succeed");
    let v = envelope_value(&envelope);
    assert_eq!(v["data"]["bid"]["status"], "rejected");
    assert!(v["data"]["bid"]["reason"].is_null());
}

#[tokio::test]
async fn reject_dry_run_skips_http_and_echoes_reason() {
    let server = MockServer::start().await;
    let mut ctx = ctx_for(&server, Some("test-key"));
    ctx.dry_run = true;
    let args = RejectArgs {
        id: BID_ID.into(),
        reason: Some("scope too narrow".into()),
    };
    let envelope = run(&ctx, Command::Reject(args)).await.expect("dry-run ok");
    let v = envelope_value(&envelope);
    assert_eq!(v["dry_run"], true);
    assert_eq!(v["data"]["action"], "would_reject_bid");
    assert_eq!(v["data"]["bid_id"], BID_ID);
    assert_eq!(v["data"]["reason"], "scope too narrow");
}

#[tokio::test]
async fn reject_bad_bid_id_is_usage_error_without_any_http() {
    let server = MockServer::start().await;
    let args = RejectArgs {
        id: "not-a-uuid".into(),
        reason: None,
    };
    let err = run(&ctx_for(&server, Some("test-key")), Command::Reject(args))
        .await
        .expect_err("bad UUID must fail locally");
    assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
}

#[tokio::test]
async fn reject_empty_reason_is_usage_error_without_any_http() {
    let server = MockServer::start().await;
    let args = RejectArgs {
        id: BID_ID.into(),
        reason: Some("   ".into()),
    };
    let err = run(&ctx_for(&server, Some("test-key")), Command::Reject(args))
        .await
        .expect_err("empty --reason must fail locally");
    match err {
        CmdError::Usage(m) => assert!(m.contains("--reason"), "unexpected: {m}"),
        other => panic!("expected Usage, got {other:?}"),
    }
}

#[tokio::test]
async fn reject_oversize_reason_is_usage_error_without_any_http() {
    let server = MockServer::start().await;
    let args = RejectArgs {
        id: BID_ID.into(),
        reason: Some("x".repeat(501)),
    };
    let err = run(&ctx_for(&server, Some("test-key")), Command::Reject(args))
        .await
        .expect_err(">500 chars must fail locally");
    assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
}

#[tokio::test]
async fn reject_401_surfaces_as_auth() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/bids/{BID_ID}/reject")))
        .respond_with(ResponseTemplate::new(401).set_body_json(json!({
            "error": "invalid_api_key",
            "message": "bad key",
        })))
        .mount(&server)
        .await;
    let args = RejectArgs {
        id: BID_ID.into(),
        reason: None,
    };
    let err = run(&ctx_for(&server, Some("test-key")), Command::Reject(args))
        .await
        .expect_err("401 must surface as Auth");
    assert!(matches!(err, CmdError::Auth(_)), "got {err:?}");
}

#[tokio::test]
async fn reject_403_not_the_poster_surfaces_as_auth() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/bids/{BID_ID}/reject")))
        .respond_with(ResponseTemplate::new(403).set_body_json(json!({
            "error": "forbidden",
            "message": "You are not the poster of this task",
        })))
        .mount(&server)
        .await;
    let args = RejectArgs {
        id: BID_ID.into(),
        reason: None,
    };
    let err = run(&ctx_for(&server, Some("test-key")), Command::Reject(args))
        .await
        .expect_err("403 must surface as Auth");
    assert!(matches!(err, CmdError::Auth(_)), "got {err:?}");
}

#[tokio::test]
async fn reject_409_already_accepted_surfaces_as_validation() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/bids/{BID_ID}/reject")))
        .respond_with(ResponseTemplate::new(409).set_body_json(json!({
            "error": "invalid_status",
            "message": "bid is not pending",
        })))
        .mount(&server)
        .await;
    let args = RejectArgs {
        id: BID_ID.into(),
        reason: None,
    };
    let err = run(&ctx_for(&server, Some("test-key")), Command::Reject(args))
        .await
        .expect_err("409 must surface");
    assert!(
        matches!(err, CmdError::Validation { .. } | CmdError::Server(_)),
        "got {err:?}"
    );
}

#[tokio::test]
async fn reject_404_surfaces_as_validation() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/bids/{BID_ID}/reject")))
        .respond_with(ResponseTemplate::new(404).set_body_json(json!({
            "error": "not_found",
            "message": "Bid not found",
        })))
        .mount(&server)
        .await;
    let args = RejectArgs {
        id: BID_ID.into(),
        reason: None,
    };
    let err = run(&ctx_for(&server, Some("test-key")), Command::Reject(args))
        .await
        .expect_err("404 must surface");
    assert!(
        matches!(err, CmdError::Validation { .. } | CmdError::Server(_)),
        "got {err:?}"
    );
}

#[tokio::test]
async fn reject_missing_api_key_errors_before_any_http() {
    let server = MockServer::start().await;
    let args = RejectArgs {
        id: BID_ID.into(),
        reason: None,
    };
    let err = run(&ctx_for(&server, None), Command::Reject(args))
        .await
        .expect_err("no key → MissingApiKey");
    assert!(matches!(err, CmdError::MissingApiKey), "got {err:?}");
}