taskfast-cli 0.19.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
// SPDX-License-Identifier: MIT
//! End-to-end tests for `taskfast post`.
//!
//! Two wiremock servers: one for the TaskFast API (draft prepare + submit),
//! one for the Tempo JSON-RPC. The happy path wires them together through
//! the real `sign_and_broadcast_erc20_transfer` path so any regression in
//! tempo_rpc (nonce tag, RLP encoding) surfaces here too.

use alloy_signer_local::PrivateKeySigner;
use serde_json::{json, Value};
use wiremock::matchers::{body_partial_json, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

use taskfast_cli::cmd::post::{run, Args, AssignmentType};
use taskfast_cli::cmd::{CmdError, Ctx};
use taskfast_cli::{Envelope, Environment};

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,
        // Mock RPC server runs on an ephemeral 127.0.0.1 port — not
        // well-known. Tests exercise the real post pipeline, so flip the
        // F2 opt-in (same as `--allow-custom-endpoints` from main).
        allow_custom_endpoints: true,
        ..Default::default()
    }
}

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

/// Build a minimal Args with sensible defaults for the happy path. Callers
/// override just the fields they care about.
fn base_args(wallet_address: Option<String>, keystore: Option<String>) -> Args {
    Args {
        title: "test task".into(),
        description: "a test".into(),
        budget: Some("1.00".into()),
        capabilities: vec!["testing".into()],
        criteria: vec![],
        criteria_file: None,
        pickup_deadline_hours: 24,
        execution_deadline: None,
        venue: None,
        assignment_type: AssignmentType::Open,
        direct_agent_id: None,
        wallet_address,
        keystore,
        wallet_password_file: None,
        rpc_url: None,
        yes: false,
    }
}

/// Mount `GET /config/network` so the runtime path's fetch of the
/// deployment's proxy URL succeeds. Returns the testnet rpc_url that will
/// be picked (i.e. `<api_base>/rpc/testnet`) so callers can point the
/// RPC proxy mocks at it if they need to.
async fn mount_network_config_mock(server: &MockServer) -> String {
    let uri = server.uri();
    let payload = json!({
        "networks": {
            "testnet": {
                "chain_id": 42431,
                "rpc_url": format!("{uri}/rpc/testnet"),
                "wss_url": "wss://testnet.example.invalid",
                "explorer_url": "https://explorer-testnet.example.invalid",
                "default_stablecoin": "PathUSD"
            },
            "mainnet": {
                "chain_id": 4217,
                "rpc_url": format!("{uri}/rpc/mainnet"),
                "wss_url": "wss://mainnet.example.invalid",
                "explorer_url": "https://explorer.example.invalid",
                "default_stablecoin": null
            }
        }
    });
    Mock::given(method("GET"))
        .and(path("/config/network"))
        .respond_with(ResponseTemplate::new(200).set_body_json(payload))
        .mount(server)
        .await;
    format!("{uri}/rpc/testnet")
}

/// Mount all four JSON-RPC methods the sign-and-broadcast path needs.
async fn mount_rpc_mocks(server: &MockServer, tx_hash_hex: &str) {
    let rpc_ok = |result: Value| {
        ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0",
            "id": 1,
            "result": result,
        }))
    };
    Mock::given(method("POST"))
        .and(body_partial_json(json!({"method": "eth_chainId"})))
        .respond_with(rpc_ok(json!("0xa5bf"))) // 42431 (testnet)
        .mount(server)
        .await;
    Mock::given(method("POST"))
        .and(body_partial_json(
            json!({"method": "eth_getTransactionCount"}),
        ))
        .respond_with(rpc_ok(json!("0x0")))
        .mount(server)
        .await;
    Mock::given(method("POST"))
        .and(body_partial_json(json!({"method": "eth_gasPrice"})))
        .respond_with(rpc_ok(json!("0x3b9aca00"))) // 1 gwei
        .mount(server)
        .await;
    Mock::given(method("POST"))
        .and(body_partial_json(json!({"method": "eth_estimateGas"})))
        .respond_with(rpc_ok(json!("0x4b094"))) // 307_348 — canonical testnet USDC transfer
        .mount(server)
        .await;
    Mock::given(method("POST"))
        .and(body_partial_json(
            json!({"method": "eth_sendRawTransaction"}),
        ))
        .respond_with(rpc_ok(json!(tx_hash_hex)))
        .mount(server)
        .await;
}

#[tokio::test]
async fn post_happy_path_end_to_end() {
    let api_server = MockServer::start().await;
    let rpc_server = MockServer::start().await;

    // Real keystore so the full prepare→sign→submit path exercises I/O.
    let signer = PrivateKeySigner::random();
    let wallet_addr = format!("{:#x}", signer.address());
    let tmp = tempfile::tempdir().expect("tempdir");
    let keystore_path = tmp.path().join("wallet.json");
    taskfast_agent::keystore::save_signer(&signer, &keystore_path, "pw").expect("keystore");
    let password_path = tmp.path().join("pw");
    std::fs::write(&password_path, b"pw").unwrap();

    let _ = mount_network_config_mock(&api_server).await;

    let draft_id = uuid::Uuid::new_v4();
    let task_id = uuid::Uuid::new_v4();
    // Real-looking ERC-20 `transfer(address,uint256)` calldata: 4b selector + 32b addr + 32b amount.
    let calldata_hex = {
        let mut buf = vec![0xa9u8, 0x05, 0x9c, 0xbb];
        buf.extend([0u8; 32]);
        buf.extend([0u8; 32]);
        format!("0x{}", hex::encode(buf))
    };
    let token_addr = "0x20c0000000000000000000000000000000000000";
    let tx_hash_hex = format!("0x{}", "aa".repeat(32));

    Mock::given(method("POST"))
        .and(path("/task_drafts"))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "draft_id": draft_id,
            "payload_to_sign": calldata_hex,
            "token_address": token_addr,
        })))
        .mount(&api_server)
        .await;

    Mock::given(method("POST"))
        .and(path(format!("/task_drafts/{draft_id}/submit")))
        .and(body_partial_json(
            json!({ "signature": tx_hash_hex.clone() }),
        ))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "id": task_id,
            "status": "open",
            "submission_fee_status": "pending_confirmation",
            "submission_fee_tx_hash": tx_hash_hex,
        })))
        .mount(&api_server)
        .await;

    mount_rpc_mocks(&rpc_server, &tx_hash_hex).await;

    let mut args = base_args(
        Some(wallet_addr.clone()),
        Some(keystore_path.display().to_string()),
    );
    args.wallet_password_file = Some(password_path);
    args.rpc_url = Some(rpc_server.uri());

    let envelope = run(&ctx_for(&api_server, Some("test-key")), args)
        .await
        .expect("post should succeed");

    let v = envelope_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["task_id"], task_id.to_string());
    assert_eq!(v["data"]["draft_id"], draft_id.to_string());
    assert_eq!(v["data"]["submission_fee_tx_hash"], tx_hash_hex);
    assert_eq!(v["data"]["status"], "open");
    assert_eq!(v["data"]["submission_fee_status"], "pending_confirmation");
    // No fee debt → no message (the key stays present for JSON stability).
    assert_eq!(v["data"]["message"], Value::Null);
}

#[tokio::test]
async fn post_blocked_on_submission_fee_debt_renders_message_and_fee_status() {
    // gh#156: when the fee transfer can't confirm inline, the task is
    // created at blocked_on_submission_fee_debt. Without a message the
    // post looks stalled; the envelope must say the task is waiting on
    // on-chain confirmation, not that the post failed.
    let api_server = MockServer::start().await;
    let rpc_server = MockServer::start().await;

    let signer = PrivateKeySigner::random();
    let wallet_addr = format!("{:#x}", signer.address());
    let tmp = tempfile::tempdir().expect("tempdir");
    let keystore_path = tmp.path().join("wallet.json");
    taskfast_agent::keystore::save_signer(&signer, &keystore_path, "pw").expect("keystore");
    let password_path = tmp.path().join("pw");
    std::fs::write(&password_path, b"pw").unwrap();

    let _ = mount_network_config_mock(&api_server).await;

    let draft_id = uuid::Uuid::new_v4();
    let task_id = uuid::Uuid::new_v4();
    let calldata_hex = format!("0x{}", "00".repeat(4 + 64));
    let token_addr = "0x20c0000000000000000000000000000000000000";
    let tx_hash_hex = format!("0x{}", "bb".repeat(32));

    Mock::given(method("POST"))
        .and(path("/task_drafts"))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "draft_id": draft_id,
            "payload_to_sign": calldata_hex,
            "token_address": token_addr,
        })))
        .mount(&api_server)
        .await;

    Mock::given(method("POST"))
        .and(path(format!("/task_drafts/{draft_id}/submit")))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "id": task_id,
            "status": "blocked_on_submission_fee_debt",
            "submission_fee_status": "pending_confirmation",
            "submission_fee_tx_hash": tx_hash_hex,
        })))
        .mount(&api_server)
        .await;

    mount_rpc_mocks(&rpc_server, &tx_hash_hex).await;

    let mut args = base_args(
        Some(wallet_addr.clone()),
        Some(keystore_path.display().to_string()),
    );
    args.wallet_password_file = Some(password_path);
    args.rpc_url = Some(rpc_server.uri());

    let envelope = run(&ctx_for(&api_server, Some("test-key")), args)
        .await
        .expect("post should succeed");

    let v = envelope_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["task_id"], task_id.to_string());
    assert_eq!(v["data"]["status"], "blocked_on_submission_fee_debt");
    assert_eq!(v["data"]["submission_fee_status"], "pending_confirmation");
    let message = v["data"]["message"]
        .as_str()
        .expect("blocked post must carry a message");
    assert!(
        message.contains("on-chain confirmation"),
        "message should name the pending confirmation, got: {message}"
    );
}

#[tokio::test]
async fn post_dry_run_short_circuits_without_any_http() {
    // No mocks — any network call fails the test.
    let api_server = MockServer::start().await;

    let args = base_args(
        Some("0x0000000000000000000000000000000000000001".into()),
        None, // keystore not required in dry-run
    );
    let mut ctx = ctx_for(&api_server, Some("test-key"));
    ctx.dry_run = true;

    let envelope = run(&ctx, args).await.expect("dry-run should succeed");
    let v = envelope_value(&envelope);
    assert_eq!(v["dry_run"], true);
    assert_eq!(v["data"]["action"], "would_post");
    assert_eq!(v["data"]["draft_id"], Value::Null);
    assert_eq!(v["data"]["title"], "test task");
    assert_eq!(v["data"]["assignment_type"], "open");
    // Dry-run predicts the proxy URL locally (no HTTP); shape is
    // `{api_base}/rpc/{network}`.
    assert!(
        v["data"]["rpc_url"]
            .as_str()
            .unwrap()
            .ends_with("/rpc/testnet"),
        "dry-run rpc_url: {}",
        v["data"]["rpc_url"]
    );
}

#[tokio::test]
async fn post_missing_wallet_address_is_usage_error_without_any_http() {
    let api_server = MockServer::start().await;
    let args = base_args(None, None);
    let err = run(&ctx_for(&api_server, Some("test-key")), args)
        .await
        .expect_err("missing wallet must fail locally");
    match err {
        CmdError::Usage(msg) => assert!(
            msg.contains("--wallet-address"),
            "unexpected message: {msg}"
        ),
        other => panic!("expected Usage, got {other:?}"),
    }
}

#[tokio::test]
async fn post_bad_wallet_address_is_usage_error() {
    let api_server = MockServer::start().await;
    let args = base_args(Some("not-an-address".into()), None);
    let err = run(&ctx_for(&api_server, Some("test-key")), args)
        .await
        .expect_err("bad address must fail locally");
    assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
}

#[tokio::test]
async fn post_direct_without_agent_id_is_usage_error() {
    let api_server = MockServer::start().await;
    let mut args = base_args(
        Some("0x0000000000000000000000000000000000000001".into()),
        None,
    );
    args.assignment_type = AssignmentType::Direct;
    args.direct_agent_id = None;
    let err = run(&ctx_for(&api_server, Some("test-key")), args)
        .await
        .expect_err("direct without id must fail");
    match err {
        CmdError::Usage(msg) => assert!(msg.contains("--direct-agent-id"), "unexpected: {msg}"),
        other => panic!("expected Usage, got {other:?}"),
    }
}

#[tokio::test]
async fn post_prepare_401_surfaces_as_auth_error() {
    let api_server = MockServer::start().await;
    let _ = mount_network_config_mock(&api_server).await;
    Mock::given(method("POST"))
        .and(path("/task_drafts"))
        .respond_with(ResponseTemplate::new(401).set_body_json(json!({
            "error": "invalid_api_key",
            "message": "bad key",
        })))
        .mount(&api_server)
        .await;

    let args = base_args(
        Some("0x0000000000000000000000000000000000000001".into()),
        Some("/tmp/does-not-matter".into()),
    );
    let err = run(&ctx_for(&api_server, Some("test-key")), args)
        .await
        .expect_err("401 must surface as Auth");
    match err {
        CmdError::Auth(_) => {}
        other => panic!("expected Auth, got {other:?}"),
    }
}

#[tokio::test]
async fn post_keystore_address_mismatch_is_usage_error() {
    let api_server = MockServer::start().await;
    let _ = mount_network_config_mock(&api_server).await;

    // Server returns a happy prepare; our signer won't match --wallet-address.
    let draft_id = uuid::Uuid::new_v4();
    let calldata_hex = format!("0x{}", "00".repeat(4 + 64));
    Mock::given(method("POST"))
        .and(path("/task_drafts"))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "draft_id": draft_id,
            "payload_to_sign": calldata_hex,
            "token_address": "0x20c0000000000000000000000000000000000000",
        })))
        .mount(&api_server)
        .await;

    let signer = PrivateKeySigner::random();
    let tmp = tempfile::tempdir().expect("tempdir");
    let keystore_path = tmp.path().join("wallet.json");
    taskfast_agent::keystore::save_signer(&signer, &keystore_path, "pw").expect("keystore");
    let password_path = tmp.path().join("pw");
    std::fs::write(&password_path, b"pw").unwrap();

    // Deliberate mismatch: wallet_address != signer.address().
    let mut args = base_args(
        Some("0x0000000000000000000000000000000000000001".into()),
        Some(keystore_path.display().to_string()),
    );
    args.wallet_password_file = Some(password_path);

    let err = run(&ctx_for(&api_server, Some("test-key")), args)
        .await
        .expect_err("address mismatch must fail");
    match err {
        CmdError::Usage(msg) => {
            assert!(msg.contains("does not match"), "unexpected message: {msg}")
        }
        other => panic!("expected Usage, got {other:?}"),
    }
}

#[tokio::test]
async fn post_rejects_non_allowlisted_fee_token() {
    // F1 regression: a compromised server (or MITM on a stolen PAT) returns
    // an attacker-controlled `token_address`. The CLI must refuse to sign
    // instead of broadcasting an ERC-20 transfer to whatever contract the
    // server named.
    let api_server = MockServer::start().await;
    let rpc_server = MockServer::start().await;
    let _ = mount_network_config_mock(&api_server).await;

    let draft_id = uuid::Uuid::new_v4();
    let calldata_hex = format!("0x{}", "00".repeat(4 + 64));
    let attacker_token = "0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef";

    Mock::given(method("POST"))
        .and(path("/task_drafts"))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "draft_id": draft_id,
            "payload_to_sign": calldata_hex,
            "token_address": attacker_token,
        })))
        .mount(&api_server)
        .await;

    // RPC returns the real testnet chain id → allowlist is active.
    mount_rpc_mocks(&rpc_server, &format!("0x{}", "aa".repeat(32))).await;

    let signer = PrivateKeySigner::random();
    let tmp = tempfile::tempdir().expect("tempdir");
    let keystore_path = tmp.path().join("wallet.json");
    taskfast_agent::keystore::save_signer(&signer, &keystore_path, "pw").expect("keystore");
    let password_path = tmp.path().join("pw");
    std::fs::write(&password_path, b"pw").unwrap();

    let wallet_addr = format!("{:#x}", signer.address());
    let mut args = base_args(Some(wallet_addr), Some(keystore_path.display().to_string()));
    args.wallet_password_file = Some(password_path);
    args.rpc_url = Some(rpc_server.uri());

    // Explicitly turn off the opt-in so the allowlist's chain-id guard is
    // active even though the api_base is a mock URL.
    let mut ctx = ctx_for(&api_server, Some("test-key"));
    ctx.allow_custom_endpoints = true; // needed for mock api/rpc URLs
    let err = run(&ctx, args)
        .await
        .expect_err("attacker token must be refused");
    match err {
        CmdError::Validation { code, message } => {
            assert_eq!(code, "fee_token_not_allowed");
            assert!(message.contains(attacker_token), "msg: {message}");
            assert!(message.contains("allowlist"), "msg: {message}");
        }
        other => panic!("expected Validation, got {other:?}"),
    }
}

#[tokio::test]
async fn post_missing_api_key_errors_before_any_http() {
    let api_server = MockServer::start().await;
    let args = base_args(
        Some("0x0000000000000000000000000000000000000001".into()),
        Some("/tmp/unused".into()),
    );
    let err = run(&ctx_for(&api_server, None), args)
        .await
        .expect_err("no key → MissingApiKey");
    assert!(matches!(err, CmdError::MissingApiKey), "got {err:?}");
}

/// Regression guard for am-en56: `--criterion` payloads must land on the wire
/// in the `POST /task_drafts` body. Empty criteria previously reached the
/// server silently and disarmed worker-payout evaluation.
#[tokio::test]
async fn post_forwards_completion_criteria() {
    let api_server = MockServer::start().await;
    let rpc_server = MockServer::start().await;
    let _ = mount_network_config_mock(&api_server).await;

    let signer = PrivateKeySigner::random();
    let wallet_addr = format!("{:#x}", signer.address());
    let tmp = tempfile::tempdir().expect("tempdir");
    let keystore_path = tmp.path().join("wallet.json");
    taskfast_agent::keystore::save_signer(&signer, &keystore_path, "pw").expect("keystore");
    let password_path = tmp.path().join("pw");
    std::fs::write(&password_path, b"pw").unwrap();

    let draft_id = uuid::Uuid::new_v4();
    let task_id = uuid::Uuid::new_v4();
    let calldata_hex = {
        let mut buf = vec![0xa9u8, 0x05, 0x9c, 0xbb];
        buf.extend([0u8; 32]);
        buf.extend([0u8; 32]);
        format!("0x{}", hex::encode(buf))
    };
    let token_addr = "0x20c0000000000000000000000000000000000000";
    let tx_hash_hex = format!("0x{}", "aa".repeat(32));

    // body_partial_json matches on a subset — this asserts the field is
    // present with the expected check_type without over-constraining order.
    Mock::given(method("POST"))
        .and(path("/task_drafts"))
        .and(body_partial_json(json!({
            "completion_criteria": [{"check_type": "regex"}]
        })))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "draft_id": draft_id,
            "payload_to_sign": calldata_hex,
            "token_address": token_addr,
        })))
        .mount(&api_server)
        .await;

    Mock::given(method("POST"))
        .and(path(format!("/task_drafts/{draft_id}/submit")))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "id": task_id,
            "status": "open",
            "submission_fee_status": "pending_confirmation",
            "submission_fee_tx_hash": tx_hash_hex,
        })))
        .mount(&api_server)
        .await;

    mount_rpc_mocks(&rpc_server, &tx_hash_hex).await;

    let mut args = base_args(
        Some(wallet_addr.clone()),
        Some(keystore_path.display().to_string()),
    );
    args.wallet_password_file = Some(password_path);
    args.rpc_url = Some(rpc_server.uri());
    args.criteria = vec![serde_json::to_string(&json!({
        "description": "matches anything",
        "check_type": "regex",
        "check_expression": ".*",
        "expected_value": ".",
    }))
    .unwrap()];

    let envelope = run(&ctx_for(&api_server, Some("test-key")), args)
        .await
        .expect("post with criteria should succeed");
    let v = envelope_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["task_id"], task_id.to_string());
}

/// `--venue` must forward `settlement_venue` in the `POST /task_drafts` body so
/// the task binds the elected settlement chain (ADR 0011 §5). The mock only
/// matches when the field is present with the exact chain_key, so a dropped
/// `settlement_venue` fails the prepare request rather than silently binding
/// the default venue.
#[tokio::test]
async fn post_forwards_settlement_venue() {
    let api_server = MockServer::start().await;
    let rpc_server = MockServer::start().await;
    let _ = mount_network_config_mock(&api_server).await;

    let signer = PrivateKeySigner::random();
    let wallet_addr = format!("{:#x}", signer.address());
    let tmp = tempfile::tempdir().expect("tempdir");
    let keystore_path = tmp.path().join("wallet.json");
    taskfast_agent::keystore::save_signer(&signer, &keystore_path, "pw").expect("keystore");
    let password_path = tmp.path().join("pw");
    std::fs::write(&password_path, b"pw").unwrap();

    let draft_id = uuid::Uuid::new_v4();
    let task_id = uuid::Uuid::new_v4();
    let calldata_hex = {
        let mut buf = vec![0xa9u8, 0x05, 0x9c, 0xbb];
        buf.extend([0u8; 32]);
        buf.extend([0u8; 32]);
        format!("0x{}", hex::encode(buf))
    };
    let token_addr = "0x20c0000000000000000000000000000000000000";
    let tx_hash_hex = format!("0x{}", "aa".repeat(32));

    Mock::given(method("POST"))
        .and(path("/task_drafts"))
        .and(body_partial_json(json!({
            "settlement_venue": "tempo-zone-moderato"
        })))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "draft_id": draft_id,
            "payload_to_sign": calldata_hex,
            "token_address": token_addr,
        })))
        .mount(&api_server)
        .await;

    Mock::given(method("POST"))
        .and(path(format!("/task_drafts/{draft_id}/submit")))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "id": task_id,
            "status": "open",
            "submission_fee_status": "pending_confirmation",
            "submission_fee_tx_hash": tx_hash_hex,
        })))
        .mount(&api_server)
        .await;

    mount_rpc_mocks(&rpc_server, &tx_hash_hex).await;

    let mut args = base_args(
        Some(wallet_addr.clone()),
        Some(keystore_path.display().to_string()),
    );
    args.wallet_password_file = Some(password_path);
    args.rpc_url = Some(rpc_server.uri());
    args.venue = Some("tempo-zone-moderato".into());

    let envelope = run(&ctx_for(&api_server, Some("test-key")), args)
        .await
        .expect("post with --venue should succeed");
    let v = envelope_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["task_id"], task_id.to_string());
}

#[tokio::test]
async fn post_bad_criterion_json_is_usage_error() {
    let api_server = MockServer::start().await;
    let mut args = base_args(
        Some("0x0000000000000000000000000000000000000001".into()),
        Some("/tmp/unused".into()),
    );
    args.criteria = vec!["not-json".into()];
    let err = run(&ctx_for(&api_server, Some("test-key")), args)
        .await
        .expect_err("malformed --criterion must fail locally");
    match err {
        CmdError::Usage(msg) => {
            assert!(msg.contains("--criterion"), "unexpected message: {msg}")
        }
        other => panic!("expected Usage, got {other:?}"),
    }
}

#[tokio::test]
async fn post_criteria_file_merges_with_inline() {
    let api_server = MockServer::start().await;
    let rpc_server = MockServer::start().await;

    let signer = PrivateKeySigner::random();
    let wallet_addr = format!("{:#x}", signer.address());
    let tmp = tempfile::tempdir().expect("tempdir");
    let keystore_path = tmp.path().join("wallet.json");
    taskfast_agent::keystore::save_signer(&signer, &keystore_path, "pw").expect("keystore");
    let password_path = tmp.path().join("pw");
    std::fs::write(&password_path, b"pw").unwrap();

    let criteria_path = tmp.path().join("criteria.json");
    std::fs::write(
        &criteria_path,
        serde_json::to_vec(&json!([{
            "description": "from file",
            "check_type": "file_exists",
            "check_expression": "out.csv",
            "expected_value": "true",
        }]))
        .unwrap(),
    )
    .unwrap();

    let draft_id = uuid::Uuid::new_v4();
    let task_id = uuid::Uuid::new_v4();
    let calldata_hex = {
        let mut buf = vec![0xa9u8, 0x05, 0x9c, 0xbb];
        buf.extend([0u8; 32]);
        buf.extend([0u8; 32]);
        format!("0x{}", hex::encode(buf))
    };
    let tx_hash_hex = format!("0x{}", "aa".repeat(32));

    // File entry goes first, inline second — assert both land in order.
    Mock::given(method("POST"))
        .and(path("/task_drafts"))
        .and(body_partial_json(json!({
            "completion_criteria": [
                {"check_type": "file_exists", "description": "from file"},
                {"check_type": "regex", "description": "inline"},
            ]
        })))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "draft_id": draft_id,
            "payload_to_sign": calldata_hex,
            "token_address": "0x20c0000000000000000000000000000000000000",
        })))
        .mount(&api_server)
        .await;
    Mock::given(method("POST"))
        .and(path(format!("/task_drafts/{draft_id}/submit")))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "id": task_id,
            "status": "open",
            "submission_fee_status": "pending_confirmation",
            "submission_fee_tx_hash": tx_hash_hex,
        })))
        .mount(&api_server)
        .await;
    mount_rpc_mocks(&rpc_server, &tx_hash_hex).await;

    let mut args = base_args(Some(wallet_addr), Some(keystore_path.display().to_string()));
    args.wallet_password_file = Some(password_path);
    args.rpc_url = Some(rpc_server.uri());
    args.criteria_file = Some(criteria_path);
    args.criteria = vec![serde_json::to_string(&json!({
        "description": "inline",
        "check_type": "regex",
        "check_expression": ".*",
        "expected_value": ".",
    }))
    .unwrap()];

    run(&ctx_for(&api_server, Some("test-key")), args)
        .await
        .expect("merged criteria should succeed");
}

#[tokio::test]
async fn post_preflight_reports_all_problems_in_one_pass() {
    // gh#144: every locally-checkable problem must surface in a single
    // error — no more one-retry-cycle-per-missing-input. No mocks are
    // mounted: any HTTP call fails the test (preflight is pre-network).
    let api_server = MockServer::start().await;
    let mut args = base_args(None, None); // missing wallet
    args.description = "   ".into(); // blank description
    args.assignment_type = AssignmentType::Direct; // without --direct-agent-id
    args.direct_agent_id = None;
    args.execution_deadline = Some("not-a-date".into());
    args.criteria = vec!["{not json".into()];
    args.pickup_deadline_hours = 3; // outside the contract set
    args.rpc_url = Some("https://mallory.example".into()); // custom endpoint…
    let mut ctx = ctx_for(&api_server, Some("test-key"));
    ctx.allow_custom_endpoints = false; // …without the opt-in

    let err = run(&ctx, args).await.expect_err("preflight must fail");
    match err {
        CmdError::Usage(msg) => {
            for fragment in [
                "--description",
                "--wallet-address",
                "--direct-agent-id",
                "--execution-deadline",
                "--criterion[0]",
                "pickup",
                "--allow-custom-endpoints",
            ] {
                assert!(msg.contains(fragment), "missing {fragment:?} in: {msg}");
            }
            assert!(
                msg.contains("1.") && msg.contains("2."),
                "problems must be enumerated: {msg}"
            );
        }
        other => panic!("expected Usage, got {other:?}"),
    }
}

#[tokio::test]
async fn post_preflight_single_problem_reports_without_enumeration_noise() {
    // gh#144: one problem still reads as one clear error (and the existing
    // per-error message text is preserved).
    let api_server = MockServer::start().await;
    let args = base_args(None, None);
    let err = run(&ctx_for(&api_server, Some("test-key")), args)
        .await
        .expect_err("missing wallet must fail");
    match err {
        CmdError::Usage(msg) => assert!(msg.contains("--wallet-address"), "msg: {msg}"),
        other => panic!("expected Usage, got {other:?}"),
    }
}