taskfast-cli 0.22.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
// SPDX-License-Identifier: MIT
//! End-to-end tests for `taskfast escrow sign`.
//!
//! Dry-run covers the happy path without RPC mocks (no tx broadcast).
//! Error-mapping tests cover 403/422 from both escrow/params and finalize
//! so the Auth-vs-Validation contract (exit code 2 vs 4) is pinned.
//!
//! The live on-chain path requires mocking the full Tempo RPC surface
//! (chainId, gasPrice, estimateGas, nonce, sendRawTransaction, receipt) —
//! that's smoke-test territory, deferred to the manual E2E in the plan.

use std::path::PathBuf;

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

use taskfast_cli::cmd::escrow::{run, Command, SignArgs};
use taskfast_cli::cmd::{CmdError, Ctx};
use taskfast_cli::{Envelope, Environment};

const BID_ID: &str = "00000000-0000-0000-0000-0000000000bb";
const TASK_ID: &str = "00000000-0000-0000-0000-0000000000cc";
const TASK_ESCROW: &str = "0x0000000000000000000000000000000000000001";
const TOKEN_ADDR: &str = "0x0000000000000000000000000000000000000002";
const WORKER_ADDR: &str = "0x0000000000000000000000000000000000000003";
const PLATFORM_WALLET: &str = "0x0000000000000000000000000000000000000004";
const ARBITRATOR_ADDR: &str = "0x0000000000000000000000000000000000000005";
const CHAIN_ID: u64 = 42_431;
/// Server-issued deadline the CLI signs verbatim. Far future (2100-01-01) so it
/// clears the min-lifetime floor in happy-path fixtures.
const POSTER_APPROVAL_DEADLINE: i64 = 4_102_444_800;
/// 120 days — matches the on-chain DISPUTE_TIMEOUT floor the server mirrors.
const POSTER_APPROVAL_MIN_LIFETIME: i64 = 10_368_000;

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,
        allow_custom_endpoints: 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,
}

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) -> SignArgs {
    SignArgs {
        bid_id: BID_ID.into(),
        keystore: Some(keys.keystore_path.display().to_string()),
        wallet_password_file: Some(keys.password_path.clone()),
        wallet_address: None,
        rpc_url: Some("http://rpc.invalid".into()), // never hit in dry-run
        skip_allowance_check: false,
        receipt_timeout: None,
    }
}

fn escrow_params_json() -> Value {
    escrow_params_json_with_chain_id(CHAIN_ID)
}

fn escrow_params_json_with_chain_id(chain_id: u64) -> Value {
    json!({
        "bid_id": BID_ID,
        "task_id": TASK_ID,
        "amount": "75.00",
        "platform_fee_amount": "3.75",
        "worker_address": WORKER_ADDR,
        "arbitrator_address": ARBITRATOR_ADDR,
        "task_escrow_contract": TASK_ESCROW,
        "token_address": TOKEN_ADDR,
        "platform_wallet": PLATFORM_WALLET,
        "chain_id": chain_id as i64,
        "decimals": 6,
        "memo_text": null,
        "memo_hash": null,
        "poster_approval_deadline": POSTER_APPROVAL_DEADLINE,
        "poster_approval_min_lifetime": POSTER_APPROVAL_MIN_LIFETIME,
    })
}

fn readiness_json() -> Value {
    readiness_json_with_chain_id(CHAIN_ID)
}

fn readiness_json_with_chain_id(chain_id: u64) -> 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": TASK_ESCROW,
        },
    })
}

async fn mount_params(server: &MockServer, body: Value, status: u16) {
    Mock::given(method("GET"))
        .and(path(format!("/bids/{BID_ID}/escrow/params")))
        .respond_with(ResponseTemplate::new(status).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;
}

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

#[tokio::test]
async fn escrow_sign_dry_run_signs_server_issued_deadline_verbatim() {
    // The CLI no longer computes a deadline — it signs the exact
    // `poster_approval_deadline` the server returned in escrow params.
    let server = MockServer::start().await;
    let keys = fresh_keys();
    mount_params(&server, escrow_params_json(), 200).await;
    mount_readiness(&server).await;

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

    let env = run(&ctx, Command::Sign(base_args(&keys)))
        .await
        .expect("dry-run");
    let deadline = envelope_value(&env)["data"]["deadline"]
        .as_u64()
        .expect("deadline");
    assert_eq!(deadline, POSTER_APPROVAL_DEADLINE as u64);
}

#[tokio::test]
async fn escrow_sign_aborts_before_broadcast_when_deadline_below_min_lifetime() {
    // Defense-in-depth: a server-issued deadline already inside its minimum
    // lifetime (here, a past deadline) must abort before any tx is broadcast,
    // so on-chain funds are never stranded behind an approval finalize rejects.
    let server = MockServer::start().await;
    let keys = fresh_keys();
    let mut params = escrow_params_json();
    params["poster_approval_deadline"] = json!(1_700_000_000i64); // 2023 — long past
    mount_params(&server, params, 200).await;
    mount_readiness(&server).await;

    // Not dry-run: the abort must gate the real broadcast path. rpc_url points
    // at an invalid host, so reaching RPC at all would surface a different error.
    let err = run(
        &ctx_for(&server, Some("k")),
        Command::Sign(base_args(&keys)),
    )
    .await
    .expect_err("below-minimum deadline must abort");

    match err {
        CmdError::Validation { code, .. } => assert_eq!(code, "deadline_below_minimum"),
        other => panic!("expected Validation(deadline_below_minimum), got {other:?}"),
    }
}

#[tokio::test]
async fn escrow_sign_params_missing_deadline_is_actionable_version_skew() {
    // A server predating the deadline rollout omits `poster_approval_*`; the
    // 200 body then fails to deserialize. Surface an actionable code instead of
    // a raw serde "missing field" decode error.
    let server = MockServer::start().await;
    let keys = fresh_keys();
    let mut params = escrow_params_json();
    params
        .as_object_mut()
        .unwrap()
        .remove("poster_approval_deadline");
    params
        .as_object_mut()
        .unwrap()
        .remove("poster_approval_min_lifetime");
    mount_params(&server, params, 200).await;

    let err = run(
        &ctx_for(&server, Some("k")),
        Command::Sign(base_args(&keys)),
    )
    .await
    .expect_err("missing deadline field must fail");

    match err {
        CmdError::Validation { code, .. } => assert_eq!(code, "server_missing_approval_deadline"),
        other => panic!("expected Validation(server_missing_approval_deadline), got {other:?}"),
    }
}

fn without_approval_fields(mut params: Value) -> Value {
    let o = params.as_object_mut().unwrap();
    o.remove("poster_approval_deadline");
    o.remove("poster_approval_min_lifetime");
    params
}

#[tokio::test]
async fn escrow_sign_v2_params_with_both_fields_present_sign_as_before() {
    let server = MockServer::start().await;
    let keys = fresh_keys();
    let mut params = escrow_params_json();
    params["contract_version"] = json!("v2");
    mount_params(&server, params, 200).await;
    mount_readiness(&server).await;
    let mut ctx = ctx_for(&server, Some("k"));
    ctx.dry_run = true;

    let env = run(&ctx, Command::Sign(base_args(&keys)))
        .await
        .expect("v2");
    let data = &envelope_value(&env)["data"];
    assert_eq!(
        data["deadline"].as_u64(),
        Some(POSTER_APPROVAL_DEADLINE as u64)
    );
    assert!(data["signature"]
        .as_str()
        .is_some_and(|s| s.starts_with("0x")));
}

#[tokio::test]
async fn escrow_sign_v3_params_without_approval_fields_are_accepted() {
    let server = MockServer::start().await;
    let keys = fresh_keys();
    let mut params = without_approval_fields(escrow_params_json());
    params["contract_version"] = json!("v3");
    params["review_window_seconds"] = json!(86_400);
    mount_params(&server, params, 200).await;
    mount_readiness(&server).await;
    let mut ctx = ctx_for(&server, Some("k"));
    ctx.dry_run = true;

    let env = run(&ctx, Command::Sign(base_args(&keys)))
        .await
        .expect("v3");
    let data = &envelope_value(&env)["data"];
    assert!(data["deadline"].is_null());
    assert!(data["signature"].is_null());
}

#[tokio::test]
async fn escrow_sign_non_v3_params_without_approval_fields_still_abort() {
    for version in [Some("v2"), Some("v4"), None] {
        let server = MockServer::start().await;
        let keys = fresh_keys();
        let mut params = without_approval_fields(escrow_params_json());
        if let Some(v) = version {
            params["contract_version"] = json!(v);
        }
        mount_params(&server, params, 200).await;

        let err = run(
            &ctx_for(&server, Some("k")),
            Command::Sign(base_args(&keys)),
        )
        .await
        .expect_err("non-v3 without deadline must abort");
        match err {
            CmdError::Validation { code, .. } => {
                assert_eq!(
                    code, "server_missing_approval_deadline",
                    "version {version:?}"
                )
            }
            other => panic!("expected Validation, got {other:?}"),
        }
    }
}

#[tokio::test]
async fn escrow_sign_params_with_unknown_extra_field_still_decode() {
    let server = MockServer::start().await;
    let keys = fresh_keys();
    let mut params = escrow_params_json();
    params["some_future_field"] = json!({"nested": [1, 2, 3]});
    mount_params(&server, params, 200).await;
    mount_readiness(&server).await;
    let mut ctx = ctx_for(&server, Some("k"));
    ctx.dry_run = true;

    let env = run(&ctx, Command::Sign(base_args(&keys)))
        .await
        .expect("extra field");
    assert_eq!(
        envelope_value(&env)["data"]["deadline"].as_u64(),
        Some(POSTER_APPROVAL_DEADLINE as u64)
    );
}

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

    mount_params(&server, escrow_params_json(), 200).await;
    mount_readiness(&server).await;
    // No /escrow/finalize mount — dry-run must not POST.

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

    let envelope = run(&ctx, Command::Sign(base_args(&keys)))
        .await
        .expect("dry-run must succeed");

    let v = envelope_value(&envelope);
    assert_eq!(v["dry_run"], true);
    assert_eq!(v["data"]["action"], "would_sign_escrow");
    assert_eq!(v["data"]["bid_id"], BID_ID);
    assert_eq!(v["data"]["task_id"], TASK_ID);

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

    let escrow_id = v["data"]["escrow_id"].as_str().expect("escrow_id");
    assert_eq!(escrow_id.len(), 66, "bytes32 hex is 0x + 32 bytes");

    // Calldata must be at least the 4-byte TaskEscrow.open() selector + 6
    // 32-byte slots = 4 + 192 bytes → 0x + 392 chars.
    let calldata = v["data"]["open_calldata"].as_str().expect("calldata");
    assert!(
        calldata.starts_with("0x") && calldata.len() >= 2 + 2 * (4 + 32 * 6),
        "expected TaskEscrow.open calldata shape, got len={}",
        calldata.len()
    );
    // Ensure the signer address actually came from our keystore.
    let _ = keys.address;
}

#[tokio::test]
async fn escrow_sign_rejects_custom_rpc_without_opt_in() {
    let server = MockServer::start().await;
    let keys = fresh_keys();
    mount_params(&server, escrow_params_json(), 200).await;
    mount_readiness(&server).await;

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

    let err = run(&ctx, Command::Sign(base_args(&keys)))
        .await
        .expect_err("custom rpc url must require opt-in");

    match err {
        CmdError::Usage(msg) => {
            assert!(msg.contains("custom tempo_rpc_url"), "msg: {msg}");
            assert!(msg.contains("--allow-custom-endpoints"), "msg: {msg}");
        }
        other => panic!("expected Usage, got {other:?}"),
    }
}

#[tokio::test]
async fn escrow_sign_rejects_plain_http_mainnet_rpc() {
    let server = MockServer::start().await;
    let keys = fresh_keys();
    mount_params(&server, escrow_params_json_with_chain_id(4_217), 200).await;
    mount_readiness_with_chain_id(&server, 4_217).await;

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

    let err = run(&ctx, Command::Sign(base_args(&keys)))
        .await
        .expect_err("mainnet plain-http rpc must fail");

    match err {
        CmdError::Usage(msg) => {
            assert!(msg.contains("plain-HTTP mainnet"), "msg: {msg}");
            assert!(msg.contains("tempo_rpc_url"), "msg: {msg}");
        }
        other => panic!("expected Usage, got {other:?}"),
    }
}

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

    mount_params(
        &server,
        json!({ "error": "forbidden", "detail": "caller is not the poster" }),
        403,
    )
    .await;

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

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

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

    mount_params(
        &server,
        json!({ "error": "conflict", "detail": "bid not in :accepted_pending_escrow" }),
        409,
    )
    .await;

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

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

#[tokio::test]
async fn escrow_sign_zone_task_signs_against_params_domain_not_global_readiness() {
    // A zone-bound task's escrow lives on a different contract + chain than
    // the global readiness `settlement_domain`. The signing domain must come
    // from the escrow params themselves (chain_id + task_escrow_contract) —
    // the venue's escrow is the EIP-712 verifying contract. Previously the
    // global-readiness cross-check hard-failed such tasks (gh#111).
    const ZONE_ESCROW: &str = "0x000000000000000000000000000000000000000a";
    const ZONE_CHAIN_ID: u64 = 424_242;

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

    let mut params = escrow_params_json_with_chain_id(ZONE_CHAIN_ID);
    params["task_escrow_contract"] = json!(ZONE_ESCROW);
    mount_params(&server, params, 200).await;
    // Global readiness disagrees on both chain_id (42431) and
    // verifying_contract (TASK_ESCROW). It must not gate the zone sign.
    mount_readiness(&server).await;

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

    let env = run(&ctx, Command::Sign(base_args(&keys)))
        .await
        .expect("zone task must sign against its own escrow domain");

    let v = envelope_value(&env);
    assert_eq!(v["data"]["domain"]["chain_id"], ZONE_CHAIN_ID);
    assert_eq!(
        v["data"]["domain"]["verifying_contract"]
            .as_str()
            .expect("verifying_contract")
            .to_lowercase(),
        ZONE_ESCROW,
    );
}

#[tokio::test]
async fn escrow_sign_bad_uuid_is_usage_error_without_http() {
    // No mounts — if any HTTP hit escapes local validation, wiremock 404s
    // and the test fails.
    let server = MockServer::start().await;
    let keys = fresh_keys();

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

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

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

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

    mount_params(&server, escrow_params_json(), 200).await;
    mount_readiness(&server).await;

    let mut args = base_args(&keys);
    // A random other address — keystore will decrypt to its own random
    // address which is vanishingly unlikely to match.
    args.wallet_address = Some("0x0000000000000000000000000000000000000099".into());

    let mut ctx = ctx_for(&server, Some("test-key"));
    ctx.dry_run = true;
    let err = run(&ctx, Command::Sign(args))
        .await
        .expect_err("wallet mismatch must fail");

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