taskfast-cli 0.18.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
// SPDX-License-Identifier: MIT
//! End-to-end tests for `taskfast settle`.
//!
//! Wires three mocked server endpoints together (`GET /tasks/{id}`,
//! `GET /agents/me/readiness`, `POST /tasks/{id}/settle`) and drives
//! `cmd::settle::run` directly so we exercise the same code path `main`
//! dispatches in production — including real `sign_distribution` output
//! (verified against the Elixir fixture in
//! `crates/taskfast-agent/src/signing.rs`).

use std::path::PathBuf;
use std::str::FromStr;

use alloy_primitives::{Address, B256, U256};
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_chains::tempo::{verify_distribution, DistributionDomain};
use taskfast_cli::cmd::settle::{run, Args};
use taskfast_cli::cmd::{CmdError, Ctx};
use taskfast_cli::{Envelope, Environment};

const TASK_ID: &str = "00000000-0000-0000-0000-0000000000aa";
const ESCROW_ID: &str = "0xabababababababababababababababababababababababababababababababab";
const VERIFYING_CONTRACT: &str = "0x0000000000000000000000000000000000000001";
const CHAIN_ID: u64 = 42_431;

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) -> Value {
    serde_json::to_value(env).expect("serialize envelope")
}

struct Keys {
    _tmp: tempfile::TempDir,
    keystore_path: PathBuf,
    password_path: PathBuf,
    address: Address,
}

/// Create a fresh random signer and persist it as a JSON v3 keystore so the
/// `settle` command's real `keystore::load` path gets exercised. The tempdir
/// is owned by the returned struct and cleaned up when it drops.
fn fresh_keys() -> Keys {
    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").expect("write password");
    Keys {
        address: signer.address(),
        _tmp: tmp,
        keystore_path,
        password_path,
    }
}

fn base_args(keys: &Keys) -> Args {
    Args {
        task_id: TASK_ID.into(),
        deadline_unix: None,
        keystore: Some(keys.keystore_path.display().to_string()),
        wallet_password_file: Some(keys.password_path.clone()),
        wallet_address: None,
        yes: false,
    }
}

/// Canonical task-detail response with escrow + deadline populated. Tests
/// that need a null field clone + mutate.
fn task_detail_json() -> Value {
    json!({
        "id": TASK_ID,
        "status": "complete",
        "escrow_id": ESCROW_ID,
        "settlement_deadline": "2027-01-15T08:00:00Z",
    })
}

fn readiness_json() -> Value {
    json!({
        "ready_to_work": true,
        "checks": {
            "api_key": { "status": "complete" },
            "wallet": { "status": "complete" },
            "funded": { "status": "complete" },
            "webhook": { "status": "complete" },
        },
        "settlement_domain": {
            "chain_id": CHAIN_ID as i64,
            "verifying_contract": VERIFYING_CONTRACT,
        },
    })
}

async fn mount_task_get(server: &MockServer, body: Value) {
    Mock::given(method("GET"))
        .and(path(format!("/tasks/{TASK_ID}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(server)
        .await;
}

async fn mount_readiness(server: &MockServer) {
    Mock::given(method("GET"))
        .and(path("/agents/me/readiness"))
        .respond_with(ResponseTemplate::new(200).set_body_json(readiness_json()))
        .mount(server)
        .await;
}

#[tokio::test]
async fn settle_happy_path_returns_settled_status() {
    let server = MockServer::start().await;
    let keys = fresh_keys();

    mount_task_get(&server, task_detail_json()).await;
    mount_readiness(&server).await;
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/settle")))
        // Signature shape is validated by the generated newtype regex; we
        // assert the key is present rather than pinning a specific value
        // (it depends on the random signer).
        .and(body_partial_json(json!({})))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "task_id": TASK_ID,
            "status": "settled",
        })))
        .mount(&server)
        .await;

    let envelope = run(&ctx_for(&server, Some("test-key")), base_args(&keys))
        .await
        .expect("settle should succeed");

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

#[tokio::test]
async fn settle_missing_escrow_id_is_usage_error_before_post() {
    let server = MockServer::start().await;
    let keys = fresh_keys();

    let mut task = task_detail_json();
    task["escrow_id"] = Value::Null;
    mount_task_get(&server, task).await;
    // Readiness + settle deliberately not mounted — any hit would 404 via
    // wiremock and the test would fail with a Network error rather than the
    // Usage we expect. That's the assertion.

    let err = run(&ctx_for(&server, Some("test-key")), base_args(&keys))
        .await
        .expect_err("missing escrow_id must fail locally");

    match err {
        CmdError::Usage(msg) => assert!(
            msg.contains("escrow_id"),
            "expected escrow_id usage message, got: {msg}"
        ),
        other => panic!("expected Usage, got {other:?}"),
    }
}

#[tokio::test]
async fn settle_403_not_poster_maps_to_auth() {
    let server = MockServer::start().await;
    let keys = fresh_keys();

    mount_task_get(&server, task_detail_json()).await;
    mount_readiness(&server).await;
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/settle")))
        .respond_with(ResponseTemplate::new(403).set_body_json(json!({
            "error": "forbidden",
            "detail": "caller is not the task poster",
        })))
        .mount(&server)
        .await;

    let err = run(&ctx_for(&server, Some("test-key")), base_args(&keys))
        .await
        .expect_err("403 must propagate");

    assert!(matches!(err, CmdError::Auth(_)), "got: {err:?}");
}

#[tokio::test]
async fn settle_409_without_status_advancement_maps_to_validation() {
    // Per `map_api_error`, 409 routes to Validation across the CLI — matches
    // the existing approve/dispute/cancel contract (tests in task.rs). The
    // gh#143 idempotent re-check only rewrites the error when the task has
    // actually reached (or passed) the settle target; here the re-check GET
    // still shows `complete`, so the original Validation must propagate.
    let server = MockServer::start().await;
    let keys = fresh_keys();

    mount_task_get(&server, task_detail_json()).await;
    mount_readiness(&server).await;
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/settle")))
        .respond_with(ResponseTemplate::new(409).set_body_json(json!({
            "error": "task_not_eligible",
            "detail": "task already settled",
        })))
        .mount(&server)
        .await;

    let err = run(&ctx_for(&server, Some("test-key")), base_args(&keys))
        .await
        .expect_err("409 must propagate");

    assert!(matches!(err, CmdError::Validation { .. }), "got: {err:?}");
}

#[tokio::test]
async fn settle_422_signer_mismatch_maps_to_validation() {
    let server = MockServer::start().await;
    let keys = fresh_keys();

    mount_task_get(&server, task_detail_json()).await;
    mount_readiness(&server).await;
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/settle")))
        .respond_with(ResponseTemplate::new(422).set_body_json(json!({
            "code": "signer_mismatch",
            "error": "recovered signer does not match agent wallet",
        })))
        .mount(&server)
        .await;

    let err = run(&ctx_for(&server, Some("test-key")), base_args(&keys))
        .await
        .expect_err("422 must propagate");

    assert!(matches!(err, CmdError::Validation { .. }), "got: {err:?}");
}

#[tokio::test]
async fn settle_bad_uuid_is_usage_error_without_any_http() {
    // No mounts — if the CLI hits the server for a UUID it couldn't parse,
    // wiremock returns 404 and the test fails loud.
    let server = MockServer::start().await;
    let keys = fresh_keys();

    let mut args = base_args(&keys);
    args.task_id = "not-a-uuid".into();

    let err = run(&ctx_for(&server, Some("test-key")), args)
        .await
        .expect_err("bad uuid must fail locally");

    assert!(matches!(err, CmdError::Usage(_)), "got: {err:?}");
}

#[tokio::test]
async fn settle_dry_run_skips_post_but_still_signs() {
    let server = MockServer::start().await;
    let keys = fresh_keys();

    mount_task_get(&server, task_detail_json()).await;
    mount_readiness(&server).await;
    // Intentionally NO `/settle` POST mount — any hit fails the test.

    let mut ctx = ctx_for(&server, Some("test-key"));
    ctx.dry_run = true;

    let envelope = run(&ctx, base_args(&keys))
        .await
        .expect("dry-run should succeed");

    let v = envelope_value(&envelope);
    assert_eq!(v["dry_run"], true);
    assert_eq!(v["data"]["action"], "would_settle");
    assert_eq!(v["data"]["task_id"], TASK_ID);
    assert_eq!(v["data"]["escrow_id"], ESCROW_ID);
    assert_eq!(v["data"]["domain"]["chain_id"], CHAIN_ID as i64);
    assert_eq!(
        v["data"]["domain"]["verifying_contract"],
        VERIFYING_CONTRACT
    );

    let sig = v["data"]["signature"].as_str().expect("signature string");
    assert_eq!(sig.len(), 132, "r||s||v hex is 0x + 65 bytes");
    assert!(sig.starts_with("0x"));

    // Cross-check the signature recovers to our signer against the same
    // domain values the envelope advertises. This is the strongest possible
    // dry-run assertion: if the CLI signed something other than what it
    // claimed, verification would fail.
    let deadline_signed = v["data"]["deadline"].as_u64().expect("deadline u64");
    let domain = DistributionDomain::new(CHAIN_ID, Address::from_str(VERIFYING_CONTRACT).unwrap());
    let escrow_id = B256::from_str(ESCROW_ID).unwrap();
    let ok = verify_distribution(
        sig,
        &domain,
        escrow_id,
        U256::from(deadline_signed),
        keys.address,
    )
    .expect("verify");
    assert!(ok, "dry-run signature must recover to keystore address");
}

#[tokio::test]
async fn settle_missing_keystore_is_usage_error() {
    let server = MockServer::start().await;
    let keys = fresh_keys();

    mount_task_get(&server, task_detail_json()).await;
    mount_readiness(&server).await;

    // Strip the keystore so the signer load fails. The settle command is
    // supposed to require it even in dry-run (bead acceptance spec).
    // `TEMPO_KEY_SOURCE` is only read via clap's `#[arg(env = ...)]`, which
    // never fires when Args is built manually — no env mutation needed.
    let mut args = base_args(&keys);
    args.keystore = None;

    let err = run(&ctx_for(&server, Some("test-key")), args)
        .await
        .expect_err("settle without keystore must fail");

    match err {
        CmdError::Usage(msg) => assert!(
            msg.contains("keystore") || msg.contains("TEMPO_KEY_SOURCE"),
            "expected keystore-usage message, got: {msg}"
        ),
        other => panic!("expected Usage, got {other:?}"),
    }
}

#[tokio::test]
async fn settle_deadline_override_binds_into_signature() {
    // Prove `--deadline-unix` actually lands in the signed digest rather than
    // being ignored in favor of the task's `settlement_deadline`. We sign in
    // dry-run (no HTTP needed) and verify against the override value.
    let server = MockServer::start().await;
    let keys = fresh_keys();

    mount_task_get(&server, task_detail_json()).await;
    mount_readiness(&server).await;

    let override_deadline: u64 = 1_234_567_890; // distinct from task.settlement_deadline
    let mut ctx = ctx_for(&server, Some("test-key"));
    ctx.dry_run = true;
    let mut args = base_args(&keys);
    args.deadline_unix = Some(override_deadline);

    let envelope = run(&ctx, args).await.expect("dry-run override succeeds");
    let v = envelope_value(&envelope);
    assert_eq!(v["data"]["deadline"].as_u64(), Some(override_deadline));

    let sig = v["data"]["signature"].as_str().unwrap();
    let domain = DistributionDomain::new(CHAIN_ID, Address::from_str(VERIFYING_CONTRACT).unwrap());
    let escrow_id = B256::from_str(ESCROW_ID).unwrap();

    // Verification with the override deadline succeeds...
    let ok = verify_distribution(
        sig,
        &domain,
        escrow_id,
        U256::from(override_deadline),
        keys.address,
    )
    .expect("verify override");
    assert!(ok, "override deadline must be the one signed");

    // ...and verification against the task's deadline (unix of
    // 2027-01-15T08:00:00Z = 1_799_467_200) fails, proving the override
    // really took effect.
    let task_deadline: u64 = 1_799_467_200;
    let mismatch = verify_distribution(
        sig,
        &domain,
        escrow_id,
        U256::from(task_deadline),
        keys.address,
    )
    .expect("verify task deadline");
    assert!(
        !mismatch,
        "signature must NOT verify under the task's settlement_deadline \
         when an override was passed"
    );
}

#[tokio::test]
async fn settle_wallet_address_mismatch_is_usage_error() {
    // Preflight parity with `taskfast post`: if the caller pins
    // --wallet-address but the keystore decrypts to a different key, fail
    // locally rather than eating the round-trip and a server 422.
    let server = MockServer::start().await;
    let keys = fresh_keys();

    mount_task_get(&server, task_detail_json()).await;
    mount_readiness(&server).await;

    let mut args = base_args(&keys);
    args.wallet_address = Some("0x0000000000000000000000000000000000000002".into());

    let err = run(&ctx_for(&server, Some("test-key")), args)
        .await
        .expect_err("mismatched wallet-address must fail locally");

    match err {
        CmdError::Usage(msg) => assert!(
            msg.contains("does not match"),
            "expected mismatch message, got: {msg}"
        ),
        other => panic!("expected Usage, got {other:?}"),
    }
}

#[tokio::test]
async fn settle_prefers_per_task_settlement_domain_over_readiness() {
    // gh#865 / #111 (settle half): a zone-bound task carries its own
    // `settlement_domain` (the venue's escrow + chain_id). settle MUST sign
    // against that, never the global L1 readiness domain — else the signature
    // verifies against the wrong escrow and the zone rejects it. Readiness is
    // deliberately NOT mounted: if settle fetched it, wiremock would 404 and
    // this test would fail, proving the per-task domain short-circuits it.
    const ZONE_CHAIN_ID: u64 = 421_700_005;
    const ZONE_CONTRACT: &str = "0x00000000000000000000000000000000000000ee";

    let server = MockServer::start().await;
    let keys = fresh_keys();

    let mut task = task_detail_json();
    task["settlement_domain"] = json!({
        "chain_id": ZONE_CHAIN_ID as i64,
        "verifying_contract": ZONE_CONTRACT,
    });
    mount_task_get(&server, task).await;
    // NO readiness mount, NO /settle mount — dry-run signs locally.

    let mut ctx = ctx_for(&server, Some("test-key"));
    ctx.dry_run = true;

    let envelope = run(&ctx, base_args(&keys))
        .await
        .expect("zone settle dry-run should succeed without readiness");
    let v = envelope_value(&envelope);
    assert_eq!(v["data"]["domain"]["chain_id"], ZONE_CHAIN_ID as i64);
    assert_eq!(v["data"]["domain"]["verifying_contract"], ZONE_CONTRACT);

    // Strongest assertion: the signature recovers under the ZONE domain and
    // NOT under the L1 readiness domain — proving which domain was signed.
    let sig = v["data"]["signature"].as_str().expect("signature string");
    let deadline_signed = v["data"]["deadline"].as_u64().expect("deadline u64");
    let escrow_id = B256::from_str(ESCROW_ID).unwrap();

    let zone_domain =
        DistributionDomain::new(ZONE_CHAIN_ID, Address::from_str(ZONE_CONTRACT).unwrap());
    assert!(
        verify_distribution(
            sig,
            &zone_domain,
            escrow_id,
            U256::from(deadline_signed),
            keys.address
        )
        .expect("verify zone"),
        "signature must recover under the task's zone domain"
    );

    let l1_domain =
        DistributionDomain::new(CHAIN_ID, Address::from_str(VERIFYING_CONTRACT).unwrap());
    assert!(
        !verify_distribution(
            sig,
            &l1_domain,
            escrow_id,
            U256::from(deadline_signed),
            keys.address
        )
        .expect("verify l1"),
        "signature must NOT recover under the global L1 readiness domain"
    );
}

#[tokio::test]
async fn settle_missing_settlement_domain_decodes_as_error() {
    // settlement_domain is now a required field on AgentReadiness — a server
    // omitting it is a contract violation, surfaced as a Decode error rather
    // than a friendly Usage hint. Verifies the decode-error path so a future
    // server regression that drops the field doesn't silently sign with a
    // zero-initialized domain.
    let server = MockServer::start().await;
    let keys = fresh_keys();

    mount_task_get(&server, task_detail_json()).await;
    Mock::given(method("GET"))
        .and(path("/agents/me/readiness"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "ready_to_work": true,
            "checks": {
                "api_key": { "status": "complete" },
                "wallet": { "status": "complete" },
                "funded": { "status": "complete" },
                "webhook": { "status": "complete" },
            },
            // settlement_domain deliberately omitted — server contract violation
        })))
        .mount(&server)
        .await;

    let err = run(&ctx_for(&server, Some("test-key")), base_args(&keys))
        .await
        .expect_err("missing settlement_domain must fail locally");

    match err {
        CmdError::Decode(msg) => assert!(
            msg.contains("settlement_domain"),
            "expected settlement_domain in decode message, got: {msg}"
        ),
        other => panic!("expected Decode, got {other:?}"),
    }
}

#[tokio::test]
async fn settle_already_settled_without_escrow_returns_success_note() {
    // gh#143: dev auto-disburse settles before the poster's explicit settle,
    // leaving the task without escrow data. Report success with a note
    // instead of the "no escrow_id" usage error — and never touch the
    // keystore (bogus path below proves the early return precedes signing).
    let server = MockServer::start().await;
    let mut task = task_detail_json();
    task["status"] = json!("settled");
    task["escrow_id"] = Value::Null;
    task["settlement_deadline"] = Value::Null;
    mount_task_get(&server, task).await;

    let args = Args {
        task_id: TASK_ID.into(),
        deadline_unix: None,
        keystore: Some("/nonexistent/wallet.json".into()),
        wallet_password_file: None,
        wallet_address: None,
        yes: false,
    };
    let envelope = run(&ctx_for(&server, Some("test-key")), args)
        .await
        .expect("already-settled task must report success");

    let v = envelope_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["task_id"], TASK_ID);
    assert_eq!(v["data"]["status"], "settled");
    assert_eq!(v["data"]["note"], "already settled");
}

#[tokio::test]
async fn settle_disbursement_pending_without_escrow_returns_underway_note() {
    // gh#143: a task in disbursement_pending has already recorded a settle —
    // disbursement is in flight, so the explicit settle's goal is met.
    let server = MockServer::start().await;
    let mut task = task_detail_json();
    task["status"] = json!("disbursement_pending");
    task["escrow_id"] = Value::Null;
    task["settlement_deadline"] = Value::Null;
    mount_task_get(&server, task).await;

    let args = Args {
        task_id: TASK_ID.into(),
        deadline_unix: None,
        keystore: Some("/nonexistent/wallet.json".into()),
        wallet_password_file: None,
        wallet_address: None,
        yes: false,
    };
    let envelope = run(&ctx_for(&server, Some("test-key")), args)
        .await
        .expect("in-flight settlement must report success");

    let v = envelope_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["status"], "disbursement_pending");
    assert_eq!(v["data"]["note"], "settlement underway");
}

#[tokio::test]
async fn settle_409_task_not_eligible_succeeds_when_recheck_shows_settled() {
    // gh#143: auto-disburse lands between our preflight GET (which saw a
    // settleable task) and the signed POST. The 409 then describes a task
    // that already settled — re-check and report success with a note.
    let server = MockServer::start().await;
    let keys = fresh_keys();

    // First GET: settleable (complete + escrow). One-shot — the re-check
    // after the 409 must see the advanced state.
    Mock::given(method("GET"))
        .and(path(format!("/tasks/{TASK_ID}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(task_detail_json()))
        .up_to_n_times(1)
        .mount(&server)
        .await;
    let mut settled = task_detail_json();
    settled["status"] = json!("settled");
    settled["escrow_id"] = Value::Null;
    Mock::given(method("GET"))
        .and(path(format!("/tasks/{TASK_ID}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(settled))
        .mount(&server)
        .await;
    mount_readiness(&server).await;
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/settle")))
        .respond_with(ResponseTemplate::new(409).set_body_json(json!({
            "error": "task_not_eligible",
            "message": "Task is not eligible for this action",
        })))
        .mount(&server)
        .await;

    let envelope = run(&ctx_for(&server, Some("test-key")), base_args(&keys))
        .await
        .expect("settle race with auto-disburse must report success");

    let v = envelope_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["status"], "settled");
    assert_eq!(v["data"]["note"], "already settled");
}