taskfast-cli 0.17.1

`taskfast` CLI: worker + poster hot-loop operations, JSON-envelope output.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
// SPDX-License-Identifier: MIT
//! Subcommand module tree + shared [`Ctx`] / [`CmdError`] types.
//!
//! The taxonomy here is the CLI's stable, orchestrator-visible surface:
//!
//!   * `CmdError` codes (the short strings in the JSON envelope)
//!   * `ExitCode` bucket per variant
//!
//! Both are covered by tests at the bottom of this file so a refactor that
//! silently re-homes a variant will break the build.

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

use rust_decimal::Decimal;
use thiserror::Error;

use crate::config::{Config, ConfigError};
use crate::envelope::Envelope;
use crate::exit::ExitCode;
use crate::{is_well_known_api_base, Environment, Network};

use taskfast_agent::keystore::KeystoreError;
use taskfast_chains::tempo::SigningError;
use taskfast_chains::tempo::TEMPO_MAINNET_CHAIN_ID;
use taskfast_client::{Error as ClientError, TaskFastClient};

pub mod agent;
pub mod artifact;
pub mod backer;
pub mod bid;
pub mod bond;
pub mod cast;
pub mod config;
pub mod discover;
pub mod dispute;
pub mod escrow;
pub mod events;
pub mod init;
pub mod init_tui;
pub mod me;
pub mod message;
pub mod payment;
pub mod ping;
pub mod platform;
pub mod post;
pub mod review;
pub mod settle;
pub mod skills;
pub mod stake;
pub mod task;
pub mod wallet;
pub mod wallet_args;
pub mod webhook;

/// Shared invocation context threaded through every subcommand.
///
/// Built once in `main` from parsed global flags; subcommands only read.
#[derive(Clone)]
pub struct Ctx {
    pub api_key: Option<String>,
    pub environment: Environment,
    /// Explicit `--api-base` / `TASKFAST_API` override. Wins over
    /// [`Environment::api_base`] when set. Never persisted — the in-memory
    /// override is session-scoped only.
    pub api_base: Option<String>,
    /// Resolved path to the JSON config file (default
    /// `./.taskfast/config.json`, override via `--config` /
    /// `TASKFAST_CONFIG`). Subcommands that persist state (init,
    /// `config set`, etc.) write here; tests construct this directly.
    pub config_path: PathBuf,
    /// Poster wallet address from config — fallback when no flag/env set
    /// on `post`/`settle`/`escrow sign`. Persisted by `taskfast init`.
    pub wallet_address: Option<String>,
    /// Keystore path from config — fallback for the same trio.
    pub keystore_path: Option<PathBuf>,
    /// Stablecoin-units threshold above which mutating commands
    /// (`post`, `settle`) require an explicit `--yes`. `None` = gate
    /// disabled. Set via `confirm_above_budget` in the JSON config.
    pub confirm_above_budget: Option<String>,
    /// Default log format for `--verbose` output. `None` = text. Set
    /// via `log_format` in the JSON config or `TASKFAST_LOG_FORMAT` env.
    pub log_format: Option<String>,
    /// Receipt-polling ceiling for `escrow sign`. Parsed from the
    /// config file's `receipt_timeout` at startup. `None` = network-aware
    /// default (3min mainnet, 1min testnet). `--receipt-timeout` /
    /// `TASKFAST_RECEIPT_TIMEOUT` still win over this.
    pub receipt_timeout: Option<Duration>,
    pub dry_run: bool,
    pub quiet: bool,
    /// F2 opt-in: allow a custom `api_base` or `tempo_rpc_url` that isn't
    /// one of the well-known TaskFast defaults. Plumbed through to
    /// subcommands (notably `post`) that construct their own network
    /// clients outside the [`TaskFastClient`] covered by the Ctx-level
    /// guard.
    pub allow_custom_endpoints: bool,
}

/// Default environment when neither a flag nor the config file pins one.
pub const DEFAULT_ENVIRONMENT: Environment = Environment::Prod;

impl Default for Ctx {
    fn default() -> Self {
        Self {
            api_key: None,
            environment: DEFAULT_ENVIRONMENT,
            api_base: None,
            config_path: PathBuf::from("/dev/null"),
            wallet_address: None,
            keystore_path: None,
            confirm_above_budget: None,
            log_format: None,
            receipt_timeout: None,
            dry_run: false,
            quiet: false,
            allow_custom_endpoints: false,
        }
    }
}

impl Ctx {
    /// Build a [`Ctx`] by layering CLI flags (including clap's
    /// env-var folding) over the on-disk [`Config`]. Precedence:
    ///
    /// ```text
    /// flag > env var > config file > default
    /// ```
    ///
    /// Clap already folds `flag > env var` for each field (via
    /// `#[arg(env = "…")]`), so the merge here is just "cli wins, else
    /// config, else default". `dry_run` and `quiet` are never
    /// persisted — they're invocation-scoped.
    pub fn from_parts(
        cli_api_key: Option<String>,
        cli_env: Option<Environment>,
        cli_api_base: Option<String>,
        cli_config_path: Option<PathBuf>,
        cli_dry_run: bool,
        cli_quiet: bool,
        cli_allow_custom_endpoints: bool,
        cfg: &Config,
    ) -> Result<Self, CmdError> {
        let receipt_timeout =
            parse_duration_cfg(cfg.receipt_timeout.as_deref(), "receipt_timeout")?;
        let environment = cli_env.or(cfg.environment).unwrap_or(DEFAULT_ENVIRONMENT);
        // api_base is no longer persisted: only the CLI/env-supplied override
        // can deviate from `environment.api_base()`. The endpoint guard still
        // gates that override against the well-known set + opt-in flag.
        let api_base = cli_api_base;
        enforce_endpoint_guard(environment, api_base.as_deref(), cli_allow_custom_endpoints)?;
        Ok(Self {
            api_key: cli_api_key.or_else(|| cfg.api_key.clone()),
            environment,
            api_base,
            config_path: cli_config_path.unwrap_or_else(Config::default_path),
            wallet_address: cfg.wallet_address.clone(),
            keystore_path: cfg.keystore_path.clone(),
            confirm_above_budget: cfg.confirm_above_budget.clone(),
            log_format: cfg.log_format.clone(),
            receipt_timeout,
            dry_run: cli_dry_run,
            quiet: cli_quiet,
            allow_custom_endpoints: cli_allow_custom_endpoints,
        })
    }

    /// F15: gather non-fatal security warnings derived from the effective
    /// runtime state. Computed at emit time (not at construction) so
    /// subcommand-induced signals can be folded in here if needed later.
    /// Always safe to call — never allocates for a healthy run.
    pub fn security_warnings(&self) -> Vec<crate::envelope::SecurityWarning> {
        use crate::envelope::SecurityWarning;
        let mut out = Vec::new();
        if self.allow_custom_endpoints {
            let detail = self.api_base.as_deref().unwrap_or("(env default)");
            out.push(SecurityWarning {
                code: "custom_endpoints_allowed",
                message: format!(
                    "--allow-custom-endpoints is in effect; api_base={detail}. \
                     Traffic will go to a non-well-known host."
                ),
            });
        }
        if std::env::var("TASKFAST_WALLET_PASSWORD").is_ok_and(|v| !v.is_empty()) {
            out.push(SecurityWarning {
                code: "password_env_var",
                message: "TASKFAST_WALLET_PASSWORD is readable via /proc/<pid>/environ; \
                         prefer --wallet-password-file."
                    .into(),
            });
        }
        out
    }

    /// Resolved API base URL: override if set, else env default.
    pub fn base_url(&self) -> &str {
        match self.api_base.as_deref() {
            Some(u) => u,
            None => self.environment.api_base(),
        }
    }

    /// Build an authenticated client, or fail with [`CmdError::MissingApiKey`]
    /// if no key was supplied (via `--api-key` or `TASKFAST_API_KEY`).
    pub fn client(&self) -> Result<TaskFastClient, CmdError> {
        let key = self.api_key.as_deref().ok_or(CmdError::MissingApiKey)?;
        TaskFastClient::from_api_key(self.base_url(), key).map_err(CmdError::from)
    }

    /// Pick the reqwest client to use for a JSON-RPC URL.
    ///
    /// Any URL whose prefix is `{api_base}/rpc/` is this deployment's
    /// authenticated proxy and **must** be hit with the X-API-Key-bearing
    /// client; otherwise the proxy short-circuits with 401 "missing API key"
    /// before reaching the upstream RPC. Anything else (a bare upstream
    /// Tempo gateway via `--rpc-url`/`TEMPO_RPC_URL`) gets a fresh client
    /// with no TaskFast headers.
    ///
    /// This is selected by URL origin (same host as `api_base`), not by which
    /// resolution branch the URL came from, so a user who points `--rpc-url` /
    /// `TEMPO_RPC_URL` at the proxy still gets the authenticated client.
    pub fn rpc_http_client(&self, client: &TaskFastClient, rpc_url: &str) -> reqwest::Client {
        if is_proxy_rpc_url(rpc_url, self.base_url()) {
            client.http_client()
        } else {
            reqwest::Client::new()
        }
    }

    /// Fail-closed budget gate. When `confirm_above_budget` is set in the
    /// config, any mutation whose budget exceeds it must be opted into via
    /// `--yes`. By design there's no TTY prompt — automation-first stays
    /// intact; the gate just stops a fat-finger script before it broadcasts
    /// an oversized ERC-20 approve. `verb` is the action ("post a task",
    /// "settle this task") for the error message.
    pub fn enforce_budget_gate(
        &self,
        budget: Option<&str>,
        yes: bool,
        verb: &str,
    ) -> Result<(), CmdError> {
        let threshold_str = match self.confirm_above_budget.as_deref() {
            Some(t) => t,
            None => return Ok(()),
        };
        let budget_str = match budget {
            Some(b) => b,
            None => return Ok(()),
        };
        // Decimal (not f64): budget values are decimal strings like "0.1"
        // that f64 cannot represent exactly. An f64 compare could flip the
        // gate around an exact-boundary threshold, which defeats the whole
        // point of a safety rail against oversized approvals.
        let threshold = Decimal::from_str(threshold_str).map_err(|_| {
            CmdError::Usage(format!(
                "config `confirm_above_budget` is not a decimal: {threshold_str:?}"
            ))
        })?;
        let amount = Decimal::from_str(budget_str)
            .map_err(|_| CmdError::Usage(format!("budget {budget_str:?} is not a decimal")))?;
        if amount > threshold && !yes {
            return Err(CmdError::Usage(format!(
                "refusing to {verb}: budget {amount} exceeds confirm_above_budget \
                 {threshold} (pass --yes to override)"
            )));
        }
        Ok(())
    }
}

/// True when `rpc_url` is served from the same origin (scheme + host + port)
/// as this deployment's `base_url` — i.e. it is this deployment's own
/// authenticated proxy, whatever path it is mounted at (`/rpc/…` or
/// `/api/rpc/…`). Used both to gate off-host RPC routing and to decide
/// whether the authenticated reqwest client (with the `X-API-Key` default
/// header) is required for the call.
///
/// The path is deliberately irrelevant: every route on `base_url` is a
/// TaskFast route that already accepts the key, so the only boundary that
/// matters is the host — we never leak the key off-host. `Url::origin()`
/// folds in the scheme, so an `https`→`http` downgrade is a different origin
/// and is correctly rejected.
pub(crate) fn is_proxy_rpc_url(rpc_url: &str, base_url: &str) -> bool {
    match (url::Url::parse(rpc_url), url::Url::parse(base_url)) {
        // Two opaque origins are never equal, so a match here is always a
        // genuine same-host tuple origin.
        (Ok(rpc), Ok(base)) => rpc.origin() == base.origin(),
        _ => false,
    }
}

fn is_loopback_url(url: &str) -> bool {
    match url::Url::parse(url) {
        Ok(u) => matches!(
            u.host_str(),
            Some("localhost" | "127.0.0.1" | "[::1]" | "::1")
        ),
        Err(_) => false,
    }
}

pub(crate) fn validate_override_rpc_url(
    url: &str,
    network: Network,
    allow_custom: bool,
) -> Result<&str, CmdError> {
    if !allow_custom {
        return Err(CmdError::Usage(format!(
            "refusing to use custom tempo_rpc_url {url:?}: pass \
             --allow-custom-endpoints (or set \
             TASKFAST_ALLOW_CUSTOM_ENDPOINTS=1) to override. The default \
             path routes RPC through `{{api_base}}/rpc/{{network}}` \
             which inherits the api_base endpoint guard."
        )));
    }

    let is_plain_http_mainnet =
        matches!(network, Network::Mainnet) && url.starts_with("http://") && !is_loopback_url(url);
    if is_plain_http_mainnet {
        return Err(CmdError::Usage(format!(
            "refusing plain-HTTP mainnet tempo_rpc_url {url:?}: MITM on a \
             mainnet RPC can observe the poster wallet and inflate gas \
             price. Use HTTPS or point at loopback for local testing."
        )));
    }

    Ok(url)
}

/// Trim and validate a user-supplied EVM wallet address, returning the
/// trimmed form to forward to the server. Mirrors the `--wallet-address`
/// preflight in `post`/`escrow`/`settle`: a malformed address is a
/// never-retry [`CmdError::Usage`], and trimming keeps a copy-pasted
/// trailing newline/space from turning into a server-side 422.
pub(crate) fn parse_wallet_address(raw: &str) -> Result<String, CmdError> {
    let trimmed = raw.trim();
    let _: alloy_primitives::Address = trimmed
        .parse()
        .map_err(|e| CmdError::Usage(format!("--wallet is not a valid EVM address: {e}")))?;
    Ok(trimmed.to_string())
}

pub(crate) fn network_policy_for_chain_id(chain_id: u64) -> Network {
    if chain_id == TEMPO_MAINNET_CHAIN_ID {
        Network::Mainnet
    } else {
        Network::Testnet
    }
}

/// F2 endpoint-override guard. Refuses to run when the effective
/// `api_base` deviates from [`well_known_api_bases`][crate::well_known_api_bases]
/// unless the caller explicitly opts in via `--allow-custom-endpoints`
/// (or env `TASKFAST_ALLOW_CUSTOM_ENDPOINTS=1`) or the environment is
/// [`Environment::Local`] (local dev is already network-sandboxed).
///
/// Threat: a malicious cloned repo ships `.taskfast/config.json` with an
/// attacker `api_base`; `taskfast` loads config from CWD, so the next
/// invocation silently exfiltrates the PAT (carried in `X-API-Key`) to
/// the attacker host. The guard turns that silent redirect into a loud
/// `Usage` error before any request fires.
fn enforce_endpoint_guard(
    environment: Environment,
    api_base: Option<&str>,
    allow_custom: bool,
) -> Result<(), CmdError> {
    if allow_custom || environment == Environment::Local {
        return Ok(());
    }
    let Some(url) = api_base else { return Ok(()) };
    if is_well_known_api_base(url) {
        return Ok(());
    }
    Err(CmdError::Usage(format!(
        "refusing to use custom api_base {url:?} for env {env}: \
         pass --allow-custom-endpoints (or set TASKFAST_ALLOW_CUSTOM_ENDPOINTS=1) \
         to override. This guard blocks a malicious .taskfast/config.json in \
         a cloned repo from silently redirecting API traffic.",
        env = environment.as_str()
    )))
}

/// Runtime cross-system check for the env→network invariant. The
/// compile-time table in [`Environment::network`] says each env runs
/// exactly one Tempo network; this verifies that the deployment at
/// `ctx.base_url()` agrees by inspecting `/config/network`.
///
/// **Default: warn-only.** Today's deployments still advertise multiple
/// networks in one response (server-side one-network-per-deployment
/// tracked in #62). Until that lands, a mismatch logs a `tracing::warn!`
/// and continues. Set `TASKFAST_STRICT_ENV_NETWORK=1` to fail-closed
/// instead. The default flips to strict in a follow-up CLI release once
/// #62 is deployed across prod + staging.
///
/// Bypassed entirely for [`Environment::Local`] (sandboxed dev) and when
/// `--allow-custom-endpoints` is set, matching the F2 endpoint guard.
pub async fn enforce_server_network_invariant(
    ctx: &Ctx,
    client: &TaskFastClient,
) -> Result<(), CmdError> {
    if ctx.allow_custom_endpoints || ctx.environment == Environment::Local {
        return Ok(());
    }
    let cfg = client
        .fetch_network_config()
        .await
        .map_err(CmdError::from)?;
    let strict = std::env::var("TASKFAST_STRICT_ENV_NETWORK")
        .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
    let advertised: Vec<String> = cfg.networks.keys().cloned().collect();
    check_network_invariant(ctx.environment, ctx.base_url(), &advertised, strict)
}

/// Pure-logic core of [`enforce_server_network_invariant`]. Split out so
/// the strict / warn / bypass branches are unit-testable without spinning
/// up a wiremock server.
fn check_network_invariant(
    env: Environment,
    api_base: &str,
    advertised: &[String],
    strict: bool,
) -> Result<(), CmdError> {
    let expected = env.network().as_str();
    if advertised.len() == 1 && advertised[0] == expected {
        return Ok(());
    }
    if strict {
        return Err(CmdError::Server(format!(
            "deployment at {api_base} advertises networks {advertised:?}; env {} requires \
             exactly [{expected}]. Server-side fix tracked in issue #62. Unset \
             TASKFAST_STRICT_ENV_NETWORK or pass --allow-custom-endpoints to bypass.",
            env.as_str(),
        )));
    }
    tracing::warn!(
        api_base = %api_base,
        env = env.as_str(),
        expected = expected,
        advertised = ?advertised,
        "deployment advertises a different network shape than env requires; \
         server-side fix tracked in issue #62. Set TASKFAST_STRICT_ENV_NETWORK=1 \
         to fail-closed."
    );
    Ok(())
}

/// Parse a human-readable duration string from the config file,
/// wrapping a malformed value in [`CmdError::Usage`] that names the
/// field. Startup-time parsing lets a bad `receipt_timeout: "7xyz"`
/// surface before any on-chain operation instead of mid-`escrow sign`.
fn parse_duration_cfg(
    raw: Option<&str>,
    field: &'static str,
) -> Result<Option<Duration>, CmdError> {
    match raw {
        None => Ok(None),
        Some(s) => humantime::parse_duration(s).map(Some).map_err(|e| {
            CmdError::Usage(format!("config `{field}` is not a duration: {s:?} ({e})"))
        }),
    }
}

/// Resolve a duration with the CLI precedence: flag > Ctx (config) > default.
/// Pulled out so the `receipt_timeout` resolvers (escrow / bond / cast) share
/// one pinning path — and tests exercise the precedence once, not per command.
pub fn resolve_duration(
    flag: Option<Duration>,
    ctx_field: Option<Duration>,
    default: Duration,
) -> Duration {
    flag.or(ctx_field).unwrap_or(default)
}

pub type CmdResult = Result<Envelope, CmdError>;

/// CLI-layer error. Every variant maps to a stable `code` string (in the
/// envelope) and a stable [`ExitCode`] bucket — both are part of the
/// orchestrator contract.
#[derive(Debug, Error)]
pub enum CmdError {
    #[error("missing API key: set --api-key or TASKFAST_API_KEY")]
    MissingApiKey,

    #[error("usage: {0}")]
    Usage(String),

    #[error("auth: {0}")]
    Auth(String),

    #[error("rate limited (retry in {retry_after:?})")]
    RateLimited { retry_after: Duration },

    #[error("validation [{code}]: {message}")]
    Validation { code: String, message: String },

    #[error("server: {0}")]
    Server(String),

    #[error("network: {0}")]
    Network(String),

    #[error("decode: {0}")]
    Decode(String),

    #[error("keystore: {0}")]
    Keystore(String),

    #[error("signing: {0}")]
    Signing(String),

    #[error("not yet implemented: {0}")]
    Unimplemented(&'static str),

    #[error(transparent)]
    Config(#[from] ConfigError),
}

impl CmdError {
    /// Short, stable code string for the JSON envelope's `error.code` field.
    pub fn code(&self) -> &'static str {
        match self {
            Self::MissingApiKey => "missing_api_key",
            Self::Usage(_) => "usage",
            Self::Auth(_) => "auth",
            Self::RateLimited { .. } => "rate_limited",
            Self::Validation { .. } => "validation",
            Self::Server(_) => "server",
            Self::Network(_) => "network",
            Self::Decode(_) => "decode",
            Self::Keystore(_) => "keystore",
            Self::Signing(_) => "signing",
            Self::Unimplemented(_) => "unimplemented",
            Self::Config(_) => "config",
        }
    }

    /// Stable exit-code bucket — see [`ExitCode`] docstring for the taxonomy.
    pub fn exit_code(&self) -> ExitCode {
        match self {
            Self::MissingApiKey | Self::Usage(_) | Self::Config(_) => ExitCode::Usage,
            Self::Auth(_) => ExitCode::Auth,
            Self::RateLimited { .. } => ExitCode::RateLimited,
            Self::Validation { .. } => ExitCode::Validation,
            Self::Server(_) | Self::Network(_) | Self::Decode(_) => ExitCode::Server,
            Self::Keystore(_) | Self::Signing(_) => ExitCode::Wallet,
            Self::Unimplemented(_) => ExitCode::Unimplemented,
        }
    }

    /// Server-directed sleep hint, if any. Populated only for
    /// [`Self::RateLimited`] so orchestrators can read it directly from the
    /// envelope instead of parsing the message.
    pub fn retry_after(&self) -> Option<Duration> {
        match self {
            Self::RateLimited { retry_after } => Some(*retry_after),
            _ => None,
        }
    }
}

impl From<ClientError> for CmdError {
    fn from(e: ClientError) -> Self {
        match e {
            ClientError::Auth(m) => Self::Auth(m),
            ClientError::Validation { code, message } => Self::Validation { code, message },
            ClientError::RateLimited { retry_after } => Self::RateLimited { retry_after },
            ClientError::Server(m) => Self::Server(m),
            ClientError::Network(e) => Self::Network(e.to_string()),
            ClientError::Decode(e) => Self::Decode(e.to_string()),
        }
    }
}

impl From<KeystoreError> for CmdError {
    fn from(e: KeystoreError) -> Self {
        Self::Keystore(e.to_string())
    }
}

impl From<SigningError> for CmdError {
    fn from(e: SigningError) -> Self {
        Self::Signing(e.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;

    fn sample(variant: &str) -> CmdError {
        match variant {
            "missing_api_key" => CmdError::MissingApiKey,
            "usage" => CmdError::Usage("bad flag".into()),
            "auth" => CmdError::Auth("401".into()),
            "rate_limited" => CmdError::RateLimited {
                retry_after: Duration::from_secs(30),
            },
            "validation" => CmdError::Validation {
                code: "bad_field".into(),
                message: "x".into(),
            },
            "server" => CmdError::Server("500".into()),
            "network" => CmdError::Network("dns".into()),
            "decode" => CmdError::Decode("json".into()),
            "keystore" => CmdError::Keystore("bad pw".into()),
            "signing" => CmdError::Signing("hsm".into()),
            "unimplemented" => CmdError::Unimplemented("soon"),
            "config" => CmdError::Config(ConfigError::Io {
                path: PathBuf::from("/x"),
                source: std::io::Error::other("boom"),
            }),
            _ => unreachable!(),
        }
    }

    const ALL: &[&str] = &[
        "missing_api_key",
        "usage",
        "auth",
        "rate_limited",
        "validation",
        "server",
        "network",
        "decode",
        "keystore",
        "signing",
        "unimplemented",
        "config",
    ];

    #[test]
    fn every_variant_has_distinct_code() {
        let codes: HashSet<&'static str> = ALL.iter().map(|v| sample(v).code()).collect();
        assert_eq!(codes.len(), ALL.len(), "codes must be unique per variant");
        for v in ALL {
            assert_eq!(sample(v).code(), *v, "code() for {v} must match the label");
        }
    }

    #[test]
    fn exit_code_taxonomy_matches_plan() {
        // Pinning here is intentional: changing any of these is a breaking
        // change to the orchestrator contract.
        assert_eq!(CmdError::MissingApiKey.exit_code(), ExitCode::Usage);
        assert_eq!(sample("usage").exit_code(), ExitCode::Usage);
        assert_eq!(sample("auth").exit_code(), ExitCode::Auth);
        assert_eq!(sample("rate_limited").exit_code(), ExitCode::RateLimited);
        assert_eq!(sample("validation").exit_code(), ExitCode::Validation);
        assert_eq!(sample("server").exit_code(), ExitCode::Server);
        assert_eq!(sample("network").exit_code(), ExitCode::Server);
        assert_eq!(sample("decode").exit_code(), ExitCode::Server);
        assert_eq!(sample("keystore").exit_code(), ExitCode::Wallet);
        assert_eq!(sample("signing").exit_code(), ExitCode::Wallet);
        assert_eq!(sample("unimplemented").exit_code(), ExitCode::Unimplemented);
        assert_eq!(sample("config").exit_code(), ExitCode::Usage);
    }

    #[test]
    fn client_error_folds_retry_after_into_cmd_error() {
        let ce = ClientError::RateLimited {
            retry_after: Duration::from_secs(42),
        };
        let cmd: CmdError = ce.into();
        match cmd {
            CmdError::RateLimited { retry_after } => {
                assert_eq!(retry_after, Duration::from_secs(42));
            }
            other => panic!("expected RateLimited, got {other:?}"),
        }
        // And the hint is available via the convenience accessor.
        assert_eq!(
            sample("rate_limited").retry_after(),
            Some(Duration::from_secs(30))
        );
        assert!(sample("auth").retry_after().is_none());
    }

    #[test]
    fn is_proxy_rpc_url_matches_same_origin() {
        let base = "https://staging.api.taskfast.app";
        // Proxy mounted at /rpc/ — same origin, authenticated client.
        assert!(is_proxy_rpc_url(
            "https://staging.api.taskfast.app/rpc/testnet",
            base
        ));
        // Proxy mounted at /api/rpc/ (gh#79) — same origin, still ours.
        // The path differs but the host is the one the endpoint-guard
        // already approved, so the API key belongs here.
        assert!(is_proxy_rpc_url(
            "https://staging.api.taskfast.app/api/rpc/testnet",
            base
        ));
        // Trailing slash on base must not break the match.
        assert!(is_proxy_rpc_url(
            "https://staging.api.taskfast.app/rpc/mainnet",
            "https://staging.api.taskfast.app/"
        ));
        // Bare upstream Tempo gateway — different host, bare client is
        // correct (no TaskFast auth header to leak off-host).
        assert!(!is_proxy_rpc_url("https://rpc.moderato.tempo.xyz", base));
        // Different host, even one that pretends to be a proxy path,
        // must not pick up the authenticated client.
        assert!(!is_proxy_rpc_url(
            "https://attacker.example/rpc/testnet",
            base
        ));
        // Scheme downgrade is a *different* origin — never send the key
        // over plaintext, even to the same host.
        assert!(!is_proxy_rpc_url(
            "http://staging.api.taskfast.app/rpc/testnet",
            base
        ));
    }

    #[test]
    fn ctx_base_url_override_wins_over_environment_default() {
        let ctx = Ctx {
            api_key: None,
            environment: Environment::Prod,
            api_base: Some("http://localhost:9999".into()),
            config_path: PathBuf::from("/dev/null"),
            dry_run: false,
            quiet: false,
            ..Default::default()
        };
        assert_eq!(ctx.base_url(), "http://localhost:9999");
    }

    #[test]
    fn ctx_base_url_falls_back_to_environment_default() {
        for (env, expected) in [
            (Environment::Prod, "https://api.taskfast.app"),
            (Environment::Staging, "https://staging.api.taskfast.app"),
            (Environment::Local, "http://127.0.0.1:4000"),
        ] {
            let ctx = Ctx {
                api_key: None,
                environment: env,
                api_base: None,
                config_path: PathBuf::from("/dev/null"),
                dry_run: false,
                quiet: false,
                ..Default::default()
            };
            assert_eq!(ctx.base_url(), expected);
        }
    }

    #[test]
    fn ctx_client_errors_when_api_key_missing() {
        let ctx = Ctx {
            api_key: None,
            environment: Environment::Local,
            api_base: None,
            config_path: PathBuf::from("/dev/null"),
            dry_run: false,
            quiet: false,
            ..Default::default()
        };
        match ctx.client() {
            Err(CmdError::MissingApiKey) => {}
            Err(other) => panic!("expected MissingApiKey, got {other:?}"),
            Ok(_) => panic!("expected MissingApiKey, got Ok(client)"),
        }
    }

    #[test]
    fn ctx_client_builds_when_api_key_present() {
        let ctx = Ctx {
            api_key: Some("tk_test_abc".into()),
            environment: Environment::Local,
            api_base: None,
            config_path: PathBuf::from("/dev/null"),
            dry_run: false,
            quiet: false,
            ..Default::default()
        };
        ctx.client().expect("client should build with a valid key");
    }

    fn cfg_with(api_key: Option<&str>, environment: Option<Environment>) -> Config {
        Config {
            api_key: api_key.map(str::to_string),
            environment,
            ..Config::default()
        }
    }

    #[test]
    fn from_parts_threads_wallet_keystore_confirm_log_format_from_config() {
        let cfg = Config {
            wallet_address: Some("0xfeed".into()),
            keystore_path: Some(PathBuf::from("/tmp/k.json")),
            confirm_above_budget: Some("500".into()),
            log_format: Some("json".into()),
            ..Config::default()
        };
        let ctx =
            Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("valid cfg");
        assert_eq!(ctx.wallet_address.as_deref(), Some("0xfeed"));
        assert_eq!(
            ctx.keystore_path.as_deref(),
            Some(std::path::Path::new("/tmp/k.json"))
        );
        assert_eq!(ctx.confirm_above_budget.as_deref(), Some("500"));
        assert_eq!(ctx.log_format.as_deref(), Some("json"));
    }

    #[test]
    fn from_parts_parses_receipt_timeout_from_config() {
        let cfg = Config {
            receipt_timeout: Some("3min".into()),
            ..Config::default()
        };
        let ctx =
            Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("parse 3min");
        assert_eq!(ctx.receipt_timeout, Some(Duration::from_mins(3)));
    }

    #[test]
    fn from_parts_rejects_malformed_receipt_timeout() {
        let cfg = Config {
            receipt_timeout: Some("nope".into()),
            ..Config::default()
        };
        let err = Ctx::from_parts(None, None, None, None, false, false, false, &cfg)
            .err()
            .expect("malformed timeout = startup error");
        assert!(matches!(err, CmdError::Usage(msg) if msg.contains("receipt_timeout")));
    }

    #[test]
    fn from_parts_duration_fields_none_when_config_absent() {
        let ctx = Ctx::from_parts(
            None,
            None,
            None,
            None,
            false,
            false,
            false,
            &Config::default(),
        )
        .expect("default cfg is valid");
        assert!(ctx.receipt_timeout.is_none());
    }

    #[test]
    fn resolve_duration_flag_wins_over_ctx_and_default() {
        let out = resolve_duration(
            Some(Duration::from_secs(10)),
            Some(Duration::from_secs(20)),
            Duration::from_secs(30),
        );
        assert_eq!(out, Duration::from_secs(10));
    }

    #[test]
    fn resolve_duration_ctx_wins_over_default_when_no_flag() {
        let out = resolve_duration(None, Some(Duration::from_secs(20)), Duration::from_secs(30));
        assert_eq!(out, Duration::from_secs(20));
    }

    #[test]
    fn resolve_duration_falls_back_to_default() {
        let out = resolve_duration(None, None, Duration::from_secs(30));
        assert_eq!(out, Duration::from_secs(30));
    }

    fn ctx_with_threshold(threshold: Option<&str>) -> Ctx {
        Ctx {
            confirm_above_budget: threshold.map(str::to_string),
            ..Default::default()
        }
    }

    #[test]
    fn budget_gate_no_op_when_threshold_unset() {
        let ctx = ctx_with_threshold(None);
        ctx.enforce_budget_gate(Some("99999"), false, "post a task")
            .expect("no threshold = no gate");
    }

    #[test]
    fn budget_gate_no_op_when_budget_absent() {
        let ctx = ctx_with_threshold(Some("100"));
        ctx.enforce_budget_gate(None, false, "post a task")
            .expect("no budget = nothing to compare");
    }

    #[test]
    fn budget_gate_passes_when_under_threshold() {
        let ctx = ctx_with_threshold(Some("100"));
        ctx.enforce_budget_gate(Some("50"), false, "post a task")
            .expect("under threshold passes without --yes");
    }

    #[test]
    fn budget_gate_passes_at_threshold_boundary() {
        let ctx = ctx_with_threshold(Some("100"));
        ctx.enforce_budget_gate(Some("100"), false, "post a task")
            .expect("equal-to-threshold passes (gate is strict >)");
    }

    #[test]
    fn budget_gate_blocks_above_threshold_without_yes() {
        let ctx = ctx_with_threshold(Some("100"));
        let err = ctx
            .enforce_budget_gate(Some("100.01"), false, "post a task")
            .expect_err("over threshold without --yes must fail");
        match err {
            CmdError::Usage(msg) => {
                assert!(msg.contains("--yes"), "msg: {msg}");
                assert!(msg.contains("post a task"), "msg: {msg}");
            }
            other => panic!("expected Usage, got {other:?}"),
        }
    }

    #[test]
    fn budget_gate_passes_above_threshold_with_yes() {
        let ctx = ctx_with_threshold(Some("100"));
        ctx.enforce_budget_gate(Some("9999"), true, "post a task")
            .expect("--yes overrides the gate");
    }

    #[test]
    fn budget_gate_uses_decimal_not_float_precision() {
        // f64 parsing would round "0.30000000000000004" to 0.3 and let it
        // slip past a "0.3" threshold. Decimal preserves every digit so
        // the gate correctly blocks.
        let ctx = ctx_with_threshold(Some("0.3"));
        ctx.enforce_budget_gate(Some("0.30000000000000004"), false, "post a task")
            .expect_err("decimal compare must detect trailing precision");
    }

    #[test]
    fn budget_gate_rejects_non_decimal_threshold() {
        let ctx = ctx_with_threshold(Some("not-a-number"));
        let err = ctx
            .enforce_budget_gate(Some("50"), false, "post a task")
            .expect_err("garbage threshold = usage error");
        assert!(matches!(err, CmdError::Usage(_)));
    }

    #[test]
    fn from_parts_flag_wins_over_config() {
        let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
        let ctx = Ctx::from_parts(
            Some("flag_key".into()),
            Some(Environment::Local),
            Some("http://flag".into()),
            None,
            false,
            false,
            false,
            &cfg,
        )
        .expect("valid cfg");
        assert_eq!(ctx.api_key.as_deref(), Some("flag_key"));
        assert_eq!(ctx.environment, Environment::Local);
        // `--api-base` is the only api_base source post-v2 — it should
        // round-trip into the in-memory Ctx field unchanged.
        assert_eq!(ctx.api_base.as_deref(), Some("http://flag"));
    }

    #[test]
    fn from_parts_config_fills_when_flags_absent() {
        // Post-v2: `api_base` is no longer a config field, so the only
        // thing the config can supply here is api_key + environment.
        let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
        let ctx =
            Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("valid cfg");
        assert_eq!(ctx.api_key.as_deref(), Some("cfg_key"));
        assert_eq!(ctx.environment, Environment::Staging);
        // No CLI override and no persisted field → in-memory api_base
        // stays None; `base_url()` falls through to env default.
        assert!(ctx.api_base.is_none());
        assert_eq!(ctx.base_url(), Environment::Staging.api_base());
    }

    #[test]
    fn from_parts_defaults_when_nothing_set() {
        let ctx = Ctx::from_parts(
            None,
            None,
            None,
            None,
            false,
            false,
            false,
            &Config::default(),
        )
        .expect("default cfg is valid");
        assert!(ctx.api_key.is_none());
        assert_eq!(ctx.environment, DEFAULT_ENVIRONMENT);
        assert!(ctx.api_base.is_none());
        assert!(!ctx.dry_run);
        assert!(!ctx.quiet);
    }

    #[test]
    fn from_parts_flag_partial_overrides_preserve_other_config_fields() {
        // Only `api_key` passed on the CLI — environment should still come
        // from the config file. (api_base no longer persisted, so there's
        // nothing for the config to contribute on that axis.)
        let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
        let ctx = Ctx::from_parts(
            Some("flag_key".into()),
            None,
            None,
            None,
            false,
            false,
            false,
            &cfg,
        )
        .expect("valid cfg");
        assert_eq!(ctx.api_key.as_deref(), Some("flag_key"));
        assert_eq!(ctx.environment, Environment::Staging);
        assert!(ctx.api_base.is_none());
    }

    #[test]
    fn from_parts_rejects_custom_api_base_for_non_local_env() {
        // Hostile invocation: --env prod with a CLI-supplied attacker
        // api_base. Guard must refuse before any request.
        let cfg = cfg_with(Some("stolen_pat"), Some(Environment::Prod));
        let err = Ctx::from_parts(
            None,
            None,
            Some("https://evil.example".into()),
            None,
            false,
            false,
            false,
            &cfg,
        )
        .err()
        .expect("custom api_base on prod must be refused");
        match err {
            CmdError::Usage(msg) => {
                assert!(msg.contains("evil.example"), "msg: {msg}");
                assert!(msg.contains("--allow-custom-endpoints"), "msg: {msg}");
            }
            other => panic!("expected Usage, got {other:?}"),
        }
    }

    #[test]
    fn from_parts_allows_custom_api_base_when_opt_in_flag_set() {
        let cfg = cfg_with(Some("k"), Some(Environment::Prod));
        let ctx = Ctx::from_parts(
            None,
            None,
            Some("https://evil.example".into()),
            None,
            false,
            false,
            true,
            &cfg,
        )
        .expect("--allow-custom-endpoints must bypass the guard");
        assert_eq!(ctx.api_base.as_deref(), Some("https://evil.example"));
    }

    #[test]
    fn from_parts_allows_custom_api_base_for_local_env() {
        // Local dev is sandboxed — no guard penalty.
        let cfg = cfg_with(Some("k"), Some(Environment::Local));
        let ctx = Ctx::from_parts(
            None,
            None,
            Some("http://127.0.0.1:4001".into()),
            None,
            false,
            false,
            false,
            &cfg,
        )
        .expect("local env bypasses guard");
        assert_eq!(ctx.api_base.as_deref(), Some("http://127.0.0.1:4001"));
    }

    #[test]
    fn from_parts_accepts_well_known_api_base_without_opt_in() {
        let cfg = cfg_with(Some("k"), Some(Environment::Prod));
        let ctx = Ctx::from_parts(
            None,
            None,
            Some("https://api.taskfast.app".into()),
            None,
            false,
            false,
            false,
            &cfg,
        )
        .expect("well-known api_base passes without --allow-custom-endpoints");
        assert_eq!(ctx.api_base.as_deref(), Some("https://api.taskfast.app"));
    }

    #[test]
    fn from_parts_guard_ignores_missing_api_base() {
        // No override ⇒ we use the env default ⇒ nothing to guard against.
        let ctx = Ctx::from_parts(
            None,
            None,
            None,
            None,
            false,
            false,
            false,
            &Config::default(),
        )
        .expect("no api_base = no guard");
        assert!(ctx.api_base.is_none());
    }

    #[test]
    fn network_invariant_ok_when_single_advertised_matches() {
        let res = check_network_invariant(
            Environment::Prod,
            "https://api.taskfast.app",
            &["mainnet".into()],
            true,
        );
        assert!(res.is_ok(), "exact match passes strict mode: {res:?}");
    }

    #[test]
    fn network_invariant_strict_rejects_wrong_single_network() {
        let err = check_network_invariant(
            Environment::Prod,
            "https://api.taskfast.app",
            &["testnet".into()],
            true,
        )
        .expect_err("strict mode must reject wrong network");
        match err {
            CmdError::Server(msg) => {
                assert!(msg.contains("testnet"), "msg: {msg}");
                assert!(msg.contains("mainnet"), "msg: {msg}");
                assert!(msg.contains("issue #62"), "remediation hint: {msg}");
            }
            other => panic!("expected Server, got {other:?}"),
        }
    }

    #[test]
    fn network_invariant_strict_rejects_extra_advertised() {
        let err = check_network_invariant(
            Environment::Prod,
            "https://api.taskfast.app",
            &["mainnet".into(), "testnet".into()],
            true,
        )
        .expect_err("strict mode must reject len != 1");
        assert!(matches!(err, CmdError::Server(_)));
    }

    #[test]
    fn network_invariant_warn_passes_under_today_server_shape() {
        // Today's deployments advertise both networks. Warn-only mode
        // (default) keeps the CLI usable until issue #62 closes.
        let res = check_network_invariant(
            Environment::Staging,
            "https://staging.api.taskfast.app",
            &["mainnet".into(), "testnet".into()],
            false,
        );
        assert!(
            res.is_ok(),
            "non-strict mode must let today's multi-network deployments through: {res:?}"
        );
    }

    #[test]
    fn network_invariant_warn_passes_when_wrong_single_network() {
        // Even a wrong-single-network advertised should warn-only —
        // strict mode is opt-in.
        let res = check_network_invariant(
            Environment::Prod,
            "https://api.taskfast.app",
            &["testnet".into()],
            false,
        );
        assert!(res.is_ok(), "non-strict mode warns rather than errors");
    }

    #[test]
    fn from_parts_dry_run_and_quiet_are_invocation_scoped() {
        // These never come from config, only from the CLI.
        let ctx = Ctx::from_parts(
            None,
            None,
            None,
            None,
            true,
            true,
            false,
            &Config::default(),
        )
        .expect("default cfg is valid");
        assert!(ctx.dry_run);
        assert!(ctx.quiet);
    }
}