Skip to main content

taskfast_cli/cmd/
mod.rs

1// SPDX-License-Identifier: MIT
2//! Subcommand module tree + shared [`Ctx`] / [`CmdError`] types.
3//!
4//! The taxonomy here is the CLI's stable, orchestrator-visible surface:
5//!
6//!   * `CmdError` codes (the short strings in the JSON envelope)
7//!   * `ExitCode` bucket per variant
8//!
9//! Both are covered by tests at the bottom of this file so a refactor that
10//! silently re-homes a variant will break the build.
11
12use std::path::PathBuf;
13use std::str::FromStr;
14use std::time::Duration;
15
16use rust_decimal::Decimal;
17use thiserror::Error;
18
19use crate::config::{Config, ConfigError};
20use crate::envelope::Envelope;
21use crate::exit::ExitCode;
22use crate::{is_well_known_api_base, Environment, Network};
23
24use taskfast_agent::keystore::KeystoreError;
25use taskfast_chains::tempo::SigningError;
26use taskfast_chains::tempo::TEMPO_MAINNET_CHAIN_ID;
27use taskfast_client::{Error as ClientError, TaskFastClient};
28
29pub mod agent;
30pub mod artifact;
31pub mod backer;
32pub mod bid;
33pub mod bond;
34pub mod config;
35pub mod discover;
36pub mod dispute;
37pub mod escrow;
38pub mod events;
39pub mod init;
40pub mod init_tui;
41pub mod me;
42pub mod message;
43pub mod payment;
44pub mod ping;
45pub mod platform;
46pub mod post;
47pub mod review;
48pub mod settle;
49pub mod skills;
50pub mod stake;
51pub mod task;
52pub mod wallet;
53pub mod wallet_args;
54pub mod webhook;
55
56/// Shared invocation context threaded through every subcommand.
57///
58/// Built once in `main` from parsed global flags; subcommands only read.
59#[derive(Clone)]
60pub struct Ctx {
61    pub api_key: Option<String>,
62    pub environment: Environment,
63    /// Explicit `--api-base` / `TASKFAST_API` override. Wins over
64    /// [`Environment::api_base`] when set. Never persisted — the in-memory
65    /// override is session-scoped only.
66    pub api_base: Option<String>,
67    /// Resolved path to the JSON config file (default
68    /// `./.taskfast/config.json`, override via `--config` /
69    /// `TASKFAST_CONFIG`). Subcommands that persist state (init,
70    /// `config set`, etc.) write here; tests construct this directly.
71    pub config_path: PathBuf,
72    /// Poster wallet address from config — fallback when no flag/env set
73    /// on `post`/`settle`/`escrow sign`. Persisted by `taskfast init`.
74    pub wallet_address: Option<String>,
75    /// Keystore path from config — fallback for the same trio.
76    pub keystore_path: Option<PathBuf>,
77    /// Stablecoin-units threshold above which mutating commands
78    /// (`post`, `settle`) require an explicit `--yes`. `None` = gate
79    /// disabled. Set via `confirm_above_budget` in the JSON config.
80    pub confirm_above_budget: Option<String>,
81    /// Default log format for `--verbose` output. `None` = text. Set
82    /// via `log_format` in the JSON config or `TASKFAST_LOG_FORMAT` env.
83    pub log_format: Option<String>,
84    /// Poster approval-deadline horizon for `escrow sign`. Parsed from
85    /// the config file's `approval_horizon` at startup (fail-fast on
86    /// malformed values). `None` = built-in default (7 days). The
87    /// `--approval-horizon` flag / `TASKFAST_APPROVAL_HORIZON` env
88    /// still win over this.
89    pub approval_horizon: Option<Duration>,
90    /// Receipt-polling ceiling for `escrow sign`. Parsed from the
91    /// config file's `receipt_timeout` at startup. `None` = network-aware
92    /// default (3min mainnet, 1min testnet). `--receipt-timeout` /
93    /// `TASKFAST_RECEIPT_TIMEOUT` still win over this.
94    pub receipt_timeout: Option<Duration>,
95    pub dry_run: bool,
96    pub quiet: bool,
97    /// F2 opt-in: allow a custom `api_base` or `tempo_rpc_url` that isn't
98    /// one of the well-known TaskFast defaults. Plumbed through to
99    /// subcommands (notably `post`) that construct their own network
100    /// clients outside the [`TaskFastClient`] covered by the Ctx-level
101    /// guard.
102    pub allow_custom_endpoints: bool,
103}
104
105/// Default environment when neither a flag nor the config file pins one.
106pub const DEFAULT_ENVIRONMENT: Environment = Environment::Prod;
107
108impl Default for Ctx {
109    fn default() -> Self {
110        Self {
111            api_key: None,
112            environment: DEFAULT_ENVIRONMENT,
113            api_base: None,
114            config_path: PathBuf::from("/dev/null"),
115            wallet_address: None,
116            keystore_path: None,
117            confirm_above_budget: None,
118            log_format: None,
119            approval_horizon: None,
120            receipt_timeout: None,
121            dry_run: false,
122            quiet: false,
123            allow_custom_endpoints: false,
124        }
125    }
126}
127
128impl Ctx {
129    /// Build a [`Ctx`] by layering CLI flags (including clap's
130    /// env-var folding) over the on-disk [`Config`]. Precedence:
131    ///
132    /// ```text
133    /// flag > env var > config file > default
134    /// ```
135    ///
136    /// Clap already folds `flag > env var` for each field (via
137    /// `#[arg(env = "…")]`), so the merge here is just "cli wins, else
138    /// config, else default". `dry_run` and `quiet` are never
139    /// persisted — they're invocation-scoped.
140    pub fn from_parts(
141        cli_api_key: Option<String>,
142        cli_env: Option<Environment>,
143        cli_api_base: Option<String>,
144        cli_config_path: Option<PathBuf>,
145        cli_dry_run: bool,
146        cli_quiet: bool,
147        cli_allow_custom_endpoints: bool,
148        cfg: &Config,
149    ) -> Result<Self, CmdError> {
150        let approval_horizon =
151            parse_duration_cfg(cfg.approval_horizon.as_deref(), "approval_horizon")?;
152        let receipt_timeout =
153            parse_duration_cfg(cfg.receipt_timeout.as_deref(), "receipt_timeout")?;
154        let environment = cli_env.or(cfg.environment).unwrap_or(DEFAULT_ENVIRONMENT);
155        // api_base is no longer persisted: only the CLI/env-supplied override
156        // can deviate from `environment.api_base()`. The endpoint guard still
157        // gates that override against the well-known set + opt-in flag.
158        let api_base = cli_api_base;
159        enforce_endpoint_guard(environment, api_base.as_deref(), cli_allow_custom_endpoints)?;
160        Ok(Self {
161            api_key: cli_api_key.or_else(|| cfg.api_key.clone()),
162            environment,
163            api_base,
164            config_path: cli_config_path.unwrap_or_else(Config::default_path),
165            wallet_address: cfg.wallet_address.clone(),
166            keystore_path: cfg.keystore_path.clone(),
167            confirm_above_budget: cfg.confirm_above_budget.clone(),
168            log_format: cfg.log_format.clone(),
169            approval_horizon,
170            receipt_timeout,
171            dry_run: cli_dry_run,
172            quiet: cli_quiet,
173            allow_custom_endpoints: cli_allow_custom_endpoints,
174        })
175    }
176
177    /// F15: gather non-fatal security warnings derived from the effective
178    /// runtime state. Computed at emit time (not at construction) so
179    /// subcommand-induced signals can be folded in here if needed later.
180    /// Always safe to call — never allocates for a healthy run.
181    pub fn security_warnings(&self) -> Vec<crate::envelope::SecurityWarning> {
182        use crate::envelope::SecurityWarning;
183        let mut out = Vec::new();
184        if self.allow_custom_endpoints {
185            let detail = self.api_base.as_deref().unwrap_or("(env default)");
186            out.push(SecurityWarning {
187                code: "custom_endpoints_allowed",
188                message: format!(
189                    "--allow-custom-endpoints is in effect; api_base={detail}. \
190                     Traffic will go to a non-well-known host."
191                ),
192            });
193        }
194        if std::env::var("TASKFAST_WALLET_PASSWORD").is_ok_and(|v| !v.is_empty()) {
195            out.push(SecurityWarning {
196                code: "password_env_var",
197                message: "TASKFAST_WALLET_PASSWORD is readable via /proc/<pid>/environ; \
198                         prefer --wallet-password-file."
199                    .into(),
200            });
201        }
202        out
203    }
204
205    /// Resolved API base URL: override if set, else env default.
206    pub fn base_url(&self) -> &str {
207        match self.api_base.as_deref() {
208            Some(u) => u,
209            None => self.environment.api_base(),
210        }
211    }
212
213    /// Build an authenticated client, or fail with [`CmdError::MissingApiKey`]
214    /// if no key was supplied (via `--api-key` or `TASKFAST_API_KEY`).
215    pub fn client(&self) -> Result<TaskFastClient, CmdError> {
216        let key = self.api_key.as_deref().ok_or(CmdError::MissingApiKey)?;
217        TaskFastClient::from_api_key(self.base_url(), key).map_err(CmdError::from)
218    }
219
220    /// Pick the reqwest client to use for a JSON-RPC URL.
221    ///
222    /// Any URL whose prefix is `{api_base}/rpc/` is this deployment's
223    /// authenticated proxy and **must** be hit with the X-API-Key-bearing
224    /// client; otherwise the proxy short-circuits with 401 "missing API key"
225    /// before reaching the upstream RPC. Anything else (a bare upstream
226    /// Tempo gateway via `--rpc-url`/`TEMPO_RPC_URL`) gets a fresh client
227    /// with no TaskFast headers.
228    ///
229    /// This is selected by URL origin (same host as `api_base`), not by which
230    /// resolution branch the URL came from, so a user who points `--rpc-url` /
231    /// `TEMPO_RPC_URL` at the proxy still gets the authenticated client.
232    pub fn rpc_http_client(&self, client: &TaskFastClient, rpc_url: &str) -> reqwest::Client {
233        if is_proxy_rpc_url(rpc_url, self.base_url()) {
234            client.http_client()
235        } else {
236            reqwest::Client::new()
237        }
238    }
239
240    /// Fail-closed budget gate. When `confirm_above_budget` is set in the
241    /// config, any mutation whose budget exceeds it must be opted into via
242    /// `--yes`. By design there's no TTY prompt — automation-first stays
243    /// intact; the gate just stops a fat-finger script before it broadcasts
244    /// an oversized ERC-20 approve. `verb` is the action ("post a task",
245    /// "settle this task") for the error message.
246    pub fn enforce_budget_gate(
247        &self,
248        budget: Option<&str>,
249        yes: bool,
250        verb: &str,
251    ) -> Result<(), CmdError> {
252        let threshold_str = match self.confirm_above_budget.as_deref() {
253            Some(t) => t,
254            None => return Ok(()),
255        };
256        let budget_str = match budget {
257            Some(b) => b,
258            None => return Ok(()),
259        };
260        // Decimal (not f64): budget values are decimal strings like "0.1"
261        // that f64 cannot represent exactly. An f64 compare could flip the
262        // gate around an exact-boundary threshold, which defeats the whole
263        // point of a safety rail against oversized approvals.
264        let threshold = Decimal::from_str(threshold_str).map_err(|_| {
265            CmdError::Usage(format!(
266                "config `confirm_above_budget` is not a decimal: {threshold_str:?}"
267            ))
268        })?;
269        let amount = Decimal::from_str(budget_str)
270            .map_err(|_| CmdError::Usage(format!("budget {budget_str:?} is not a decimal")))?;
271        if amount > threshold && !yes {
272            return Err(CmdError::Usage(format!(
273                "refusing to {verb}: budget {amount} exceeds confirm_above_budget \
274                 {threshold} (pass --yes to override)"
275            )));
276        }
277        Ok(())
278    }
279}
280
281/// True when `rpc_url` is served from the same origin (scheme + host + port)
282/// as this deployment's `base_url` — i.e. it is this deployment's own
283/// authenticated proxy, whatever path it is mounted at (`/rpc/…` or
284/// `/api/rpc/…`). Used both to gate off-host RPC routing and to decide
285/// whether the authenticated reqwest client (with the `X-API-Key` default
286/// header) is required for the call.
287///
288/// The path is deliberately irrelevant: every route on `base_url` is a
289/// TaskFast route that already accepts the key, so the only boundary that
290/// matters is the host — we never leak the key off-host. `Url::origin()`
291/// folds in the scheme, so an `https`→`http` downgrade is a different origin
292/// and is correctly rejected.
293pub(crate) fn is_proxy_rpc_url(rpc_url: &str, base_url: &str) -> bool {
294    match (url::Url::parse(rpc_url), url::Url::parse(base_url)) {
295        // Two opaque origins are never equal, so a match here is always a
296        // genuine same-host tuple origin.
297        (Ok(rpc), Ok(base)) => rpc.origin() == base.origin(),
298        _ => false,
299    }
300}
301
302fn is_loopback_url(url: &str) -> bool {
303    match url::Url::parse(url) {
304        Ok(u) => matches!(
305            u.host_str(),
306            Some("localhost" | "127.0.0.1" | "[::1]" | "::1")
307        ),
308        Err(_) => false,
309    }
310}
311
312pub(crate) fn validate_override_rpc_url(
313    url: &str,
314    network: Network,
315    allow_custom: bool,
316) -> Result<&str, CmdError> {
317    if !allow_custom {
318        return Err(CmdError::Usage(format!(
319            "refusing to use custom tempo_rpc_url {url:?}: pass \
320             --allow-custom-endpoints (or set \
321             TASKFAST_ALLOW_CUSTOM_ENDPOINTS=1) to override. The default \
322             path routes RPC through `{{api_base}}/rpc/{{network}}` \
323             which inherits the api_base endpoint guard."
324        )));
325    }
326
327    let is_plain_http_mainnet =
328        matches!(network, Network::Mainnet) && url.starts_with("http://") && !is_loopback_url(url);
329    if is_plain_http_mainnet {
330        return Err(CmdError::Usage(format!(
331            "refusing plain-HTTP mainnet tempo_rpc_url {url:?}: MITM on a \
332             mainnet RPC can observe the poster wallet and inflate gas \
333             price. Use HTTPS or point at loopback for local testing."
334        )));
335    }
336
337    Ok(url)
338}
339
340/// Trim and validate a user-supplied EVM wallet address, returning the
341/// trimmed form to forward to the server. Mirrors the `--wallet-address`
342/// preflight in `post`/`escrow`/`settle`: a malformed address is a
343/// never-retry [`CmdError::Usage`], and trimming keeps a copy-pasted
344/// trailing newline/space from turning into a server-side 422.
345pub(crate) fn parse_wallet_address(raw: &str) -> Result<String, CmdError> {
346    let trimmed = raw.trim();
347    let _: alloy_primitives::Address = trimmed
348        .parse()
349        .map_err(|e| CmdError::Usage(format!("--wallet is not a valid EVM address: {e}")))?;
350    Ok(trimmed.to_string())
351}
352
353pub(crate) fn network_policy_for_chain_id(chain_id: u64) -> Network {
354    if chain_id == TEMPO_MAINNET_CHAIN_ID {
355        Network::Mainnet
356    } else {
357        Network::Testnet
358    }
359}
360
361/// F2 endpoint-override guard. Refuses to run when the effective
362/// `api_base` deviates from [`well_known_api_bases`][crate::well_known_api_bases]
363/// unless the caller explicitly opts in via `--allow-custom-endpoints`
364/// (or env `TASKFAST_ALLOW_CUSTOM_ENDPOINTS=1`) or the environment is
365/// [`Environment::Local`] (local dev is already network-sandboxed).
366///
367/// Threat: a malicious cloned repo ships `.taskfast/config.json` with an
368/// attacker `api_base`; `taskfast` loads config from CWD, so the next
369/// invocation silently exfiltrates the PAT (carried in `X-API-Key`) to
370/// the attacker host. The guard turns that silent redirect into a loud
371/// `Usage` error before any request fires.
372fn enforce_endpoint_guard(
373    environment: Environment,
374    api_base: Option<&str>,
375    allow_custom: bool,
376) -> Result<(), CmdError> {
377    if allow_custom || environment == Environment::Local {
378        return Ok(());
379    }
380    let Some(url) = api_base else { return Ok(()) };
381    if is_well_known_api_base(url) {
382        return Ok(());
383    }
384    Err(CmdError::Usage(format!(
385        "refusing to use custom api_base {url:?} for env {env}: \
386         pass --allow-custom-endpoints (or set TASKFAST_ALLOW_CUSTOM_ENDPOINTS=1) \
387         to override. This guard blocks a malicious .taskfast/config.json in \
388         a cloned repo from silently redirecting API traffic.",
389        env = environment.as_str()
390    )))
391}
392
393/// Runtime cross-system check for the env→network invariant. The
394/// compile-time table in [`Environment::network`] says each env runs
395/// exactly one Tempo network; this verifies that the deployment at
396/// `ctx.base_url()` agrees by inspecting `/config/network`.
397///
398/// **Default: warn-only.** Today's deployments still advertise multiple
399/// networks in one response (server-side one-network-per-deployment
400/// tracked in #62). Until that lands, a mismatch logs a `tracing::warn!`
401/// and continues. Set `TASKFAST_STRICT_ENV_NETWORK=1` to fail-closed
402/// instead. The default flips to strict in a follow-up CLI release once
403/// #62 is deployed across prod + staging.
404///
405/// Bypassed entirely for [`Environment::Local`] (sandboxed dev) and when
406/// `--allow-custom-endpoints` is set, matching the F2 endpoint guard.
407pub async fn enforce_server_network_invariant(
408    ctx: &Ctx,
409    client: &TaskFastClient,
410) -> Result<(), CmdError> {
411    if ctx.allow_custom_endpoints || ctx.environment == Environment::Local {
412        return Ok(());
413    }
414    let cfg = client
415        .fetch_network_config()
416        .await
417        .map_err(CmdError::from)?;
418    let strict = std::env::var("TASKFAST_STRICT_ENV_NETWORK")
419        .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
420    let advertised: Vec<String> = cfg.networks.keys().cloned().collect();
421    check_network_invariant(ctx.environment, ctx.base_url(), &advertised, strict)
422}
423
424/// Pure-logic core of [`enforce_server_network_invariant`]. Split out so
425/// the strict / warn / bypass branches are unit-testable without spinning
426/// up a wiremock server.
427fn check_network_invariant(
428    env: Environment,
429    api_base: &str,
430    advertised: &[String],
431    strict: bool,
432) -> Result<(), CmdError> {
433    let expected = env.network().as_str();
434    if advertised.len() == 1 && advertised[0] == expected {
435        return Ok(());
436    }
437    if strict {
438        return Err(CmdError::Server(format!(
439            "deployment at {api_base} advertises networks {advertised:?}; env {} requires \
440             exactly [{expected}]. Server-side fix tracked in issue #62. Unset \
441             TASKFAST_STRICT_ENV_NETWORK or pass --allow-custom-endpoints to bypass.",
442            env.as_str(),
443        )));
444    }
445    tracing::warn!(
446        api_base = %api_base,
447        env = env.as_str(),
448        expected = expected,
449        advertised = ?advertised,
450        "deployment advertises a different network shape than env requires; \
451         server-side fix tracked in issue #62. Set TASKFAST_STRICT_ENV_NETWORK=1 \
452         to fail-closed."
453    );
454    Ok(())
455}
456
457/// Parse a human-readable duration string from the config file,
458/// wrapping a malformed value in [`CmdError::Usage`] that names the
459/// field. Startup-time parsing lets a bad `approval_horizon: "7xyz"`
460/// surface before any on-chain operation instead of mid-`escrow sign`.
461fn parse_duration_cfg(
462    raw: Option<&str>,
463    field: &'static str,
464) -> Result<Option<Duration>, CmdError> {
465    match raw {
466        None => Ok(None),
467        Some(s) => humantime::parse_duration(s).map(Some).map_err(|e| {
468            CmdError::Usage(format!("config `{field}` is not a duration: {s:?} ({e})"))
469        }),
470    }
471}
472
473/// Resolve a duration with the CLI precedence: flag > Ctx (config) > default.
474/// Pulled out so #9 (`approval_horizon`) and #10 (`receipt_timeout`) share one
475/// pinning path — and tests exercise the precedence once, not per command.
476pub fn resolve_duration(
477    flag: Option<Duration>,
478    ctx_field: Option<Duration>,
479    default: Duration,
480) -> Duration {
481    flag.or(ctx_field).unwrap_or(default)
482}
483
484pub type CmdResult = Result<Envelope, CmdError>;
485
486/// CLI-layer error. Every variant maps to a stable `code` string (in the
487/// envelope) and a stable [`ExitCode`] bucket — both are part of the
488/// orchestrator contract.
489#[derive(Debug, Error)]
490pub enum CmdError {
491    #[error("missing API key: set --api-key or TASKFAST_API_KEY")]
492    MissingApiKey,
493
494    #[error("usage: {0}")]
495    Usage(String),
496
497    #[error("auth: {0}")]
498    Auth(String),
499
500    #[error("rate limited (retry in {retry_after:?})")]
501    RateLimited { retry_after: Duration },
502
503    #[error("validation [{code}]: {message}")]
504    Validation { code: String, message: String },
505
506    #[error("server: {0}")]
507    Server(String),
508
509    #[error("network: {0}")]
510    Network(String),
511
512    #[error("decode: {0}")]
513    Decode(String),
514
515    #[error("keystore: {0}")]
516    Keystore(String),
517
518    #[error("signing: {0}")]
519    Signing(String),
520
521    #[error("not yet implemented: {0}")]
522    Unimplemented(&'static str),
523
524    #[error(transparent)]
525    Config(#[from] ConfigError),
526}
527
528impl CmdError {
529    /// Short, stable code string for the JSON envelope's `error.code` field.
530    pub fn code(&self) -> &'static str {
531        match self {
532            Self::MissingApiKey => "missing_api_key",
533            Self::Usage(_) => "usage",
534            Self::Auth(_) => "auth",
535            Self::RateLimited { .. } => "rate_limited",
536            Self::Validation { .. } => "validation",
537            Self::Server(_) => "server",
538            Self::Network(_) => "network",
539            Self::Decode(_) => "decode",
540            Self::Keystore(_) => "keystore",
541            Self::Signing(_) => "signing",
542            Self::Unimplemented(_) => "unimplemented",
543            Self::Config(_) => "config",
544        }
545    }
546
547    /// Stable exit-code bucket — see [`ExitCode`] docstring for the taxonomy.
548    pub fn exit_code(&self) -> ExitCode {
549        match self {
550            Self::MissingApiKey | Self::Usage(_) | Self::Config(_) => ExitCode::Usage,
551            Self::Auth(_) => ExitCode::Auth,
552            Self::RateLimited { .. } => ExitCode::RateLimited,
553            Self::Validation { .. } => ExitCode::Validation,
554            Self::Server(_) | Self::Network(_) | Self::Decode(_) => ExitCode::Server,
555            Self::Keystore(_) | Self::Signing(_) => ExitCode::Wallet,
556            Self::Unimplemented(_) => ExitCode::Unimplemented,
557        }
558    }
559
560    /// Server-directed sleep hint, if any. Populated only for
561    /// [`Self::RateLimited`] so orchestrators can read it directly from the
562    /// envelope instead of parsing the message.
563    pub fn retry_after(&self) -> Option<Duration> {
564        match self {
565            Self::RateLimited { retry_after } => Some(*retry_after),
566            _ => None,
567        }
568    }
569}
570
571impl From<ClientError> for CmdError {
572    fn from(e: ClientError) -> Self {
573        match e {
574            ClientError::Auth(m) => Self::Auth(m),
575            ClientError::Validation { code, message } => Self::Validation { code, message },
576            ClientError::RateLimited { retry_after } => Self::RateLimited { retry_after },
577            ClientError::Server(m) => Self::Server(m),
578            ClientError::Network(e) => Self::Network(e.to_string()),
579            ClientError::Decode(e) => Self::Decode(e.to_string()),
580        }
581    }
582}
583
584impl From<KeystoreError> for CmdError {
585    fn from(e: KeystoreError) -> Self {
586        Self::Keystore(e.to_string())
587    }
588}
589
590impl From<SigningError> for CmdError {
591    fn from(e: SigningError) -> Self {
592        Self::Signing(e.to_string())
593    }
594}
595
596#[cfg(test)]
597mod tests {
598    use super::*;
599    use std::collections::HashSet;
600
601    fn sample(variant: &str) -> CmdError {
602        match variant {
603            "missing_api_key" => CmdError::MissingApiKey,
604            "usage" => CmdError::Usage("bad flag".into()),
605            "auth" => CmdError::Auth("401".into()),
606            "rate_limited" => CmdError::RateLimited {
607                retry_after: Duration::from_secs(30),
608            },
609            "validation" => CmdError::Validation {
610                code: "bad_field".into(),
611                message: "x".into(),
612            },
613            "server" => CmdError::Server("500".into()),
614            "network" => CmdError::Network("dns".into()),
615            "decode" => CmdError::Decode("json".into()),
616            "keystore" => CmdError::Keystore("bad pw".into()),
617            "signing" => CmdError::Signing("hsm".into()),
618            "unimplemented" => CmdError::Unimplemented("soon"),
619            "config" => CmdError::Config(ConfigError::Io {
620                path: PathBuf::from("/x"),
621                source: std::io::Error::other("boom"),
622            }),
623            _ => unreachable!(),
624        }
625    }
626
627    const ALL: &[&str] = &[
628        "missing_api_key",
629        "usage",
630        "auth",
631        "rate_limited",
632        "validation",
633        "server",
634        "network",
635        "decode",
636        "keystore",
637        "signing",
638        "unimplemented",
639        "config",
640    ];
641
642    #[test]
643    fn every_variant_has_distinct_code() {
644        let codes: HashSet<&'static str> = ALL.iter().map(|v| sample(v).code()).collect();
645        assert_eq!(codes.len(), ALL.len(), "codes must be unique per variant");
646        for v in ALL {
647            assert_eq!(sample(v).code(), *v, "code() for {v} must match the label");
648        }
649    }
650
651    #[test]
652    fn exit_code_taxonomy_matches_plan() {
653        // Pinning here is intentional: changing any of these is a breaking
654        // change to the orchestrator contract.
655        assert_eq!(CmdError::MissingApiKey.exit_code(), ExitCode::Usage);
656        assert_eq!(sample("usage").exit_code(), ExitCode::Usage);
657        assert_eq!(sample("auth").exit_code(), ExitCode::Auth);
658        assert_eq!(sample("rate_limited").exit_code(), ExitCode::RateLimited);
659        assert_eq!(sample("validation").exit_code(), ExitCode::Validation);
660        assert_eq!(sample("server").exit_code(), ExitCode::Server);
661        assert_eq!(sample("network").exit_code(), ExitCode::Server);
662        assert_eq!(sample("decode").exit_code(), ExitCode::Server);
663        assert_eq!(sample("keystore").exit_code(), ExitCode::Wallet);
664        assert_eq!(sample("signing").exit_code(), ExitCode::Wallet);
665        assert_eq!(sample("unimplemented").exit_code(), ExitCode::Unimplemented);
666        assert_eq!(sample("config").exit_code(), ExitCode::Usage);
667    }
668
669    #[test]
670    fn client_error_folds_retry_after_into_cmd_error() {
671        let ce = ClientError::RateLimited {
672            retry_after: Duration::from_secs(42),
673        };
674        let cmd: CmdError = ce.into();
675        match cmd {
676            CmdError::RateLimited { retry_after } => {
677                assert_eq!(retry_after, Duration::from_secs(42));
678            }
679            other => panic!("expected RateLimited, got {other:?}"),
680        }
681        // And the hint is available via the convenience accessor.
682        assert_eq!(
683            sample("rate_limited").retry_after(),
684            Some(Duration::from_secs(30))
685        );
686        assert!(sample("auth").retry_after().is_none());
687    }
688
689    #[test]
690    fn is_proxy_rpc_url_matches_same_origin() {
691        let base = "https://staging.api.taskfast.app";
692        // Proxy mounted at /rpc/ — same origin, authenticated client.
693        assert!(is_proxy_rpc_url(
694            "https://staging.api.taskfast.app/rpc/testnet",
695            base
696        ));
697        // Proxy mounted at /api/rpc/ (gh#79) — same origin, still ours.
698        // The path differs but the host is the one the endpoint-guard
699        // already approved, so the API key belongs here.
700        assert!(is_proxy_rpc_url(
701            "https://staging.api.taskfast.app/api/rpc/testnet",
702            base
703        ));
704        // Trailing slash on base must not break the match.
705        assert!(is_proxy_rpc_url(
706            "https://staging.api.taskfast.app/rpc/mainnet",
707            "https://staging.api.taskfast.app/"
708        ));
709        // Bare upstream Tempo gateway — different host, bare client is
710        // correct (no TaskFast auth header to leak off-host).
711        assert!(!is_proxy_rpc_url("https://rpc.moderato.tempo.xyz", base));
712        // Different host, even one that pretends to be a proxy path,
713        // must not pick up the authenticated client.
714        assert!(!is_proxy_rpc_url(
715            "https://attacker.example/rpc/testnet",
716            base
717        ));
718        // Scheme downgrade is a *different* origin — never send the key
719        // over plaintext, even to the same host.
720        assert!(!is_proxy_rpc_url(
721            "http://staging.api.taskfast.app/rpc/testnet",
722            base
723        ));
724    }
725
726    #[test]
727    fn ctx_base_url_override_wins_over_environment_default() {
728        let ctx = Ctx {
729            api_key: None,
730            environment: Environment::Prod,
731            api_base: Some("http://localhost:9999".into()),
732            config_path: PathBuf::from("/dev/null"),
733            dry_run: false,
734            quiet: false,
735            ..Default::default()
736        };
737        assert_eq!(ctx.base_url(), "http://localhost:9999");
738    }
739
740    #[test]
741    fn ctx_base_url_falls_back_to_environment_default() {
742        for (env, expected) in [
743            (Environment::Prod, "https://api.taskfast.app"),
744            (Environment::Staging, "https://staging.api.taskfast.app"),
745            (Environment::Local, "http://127.0.0.1:4000"),
746        ] {
747            let ctx = Ctx {
748                api_key: None,
749                environment: env,
750                api_base: None,
751                config_path: PathBuf::from("/dev/null"),
752                dry_run: false,
753                quiet: false,
754                ..Default::default()
755            };
756            assert_eq!(ctx.base_url(), expected);
757        }
758    }
759
760    #[test]
761    fn ctx_client_errors_when_api_key_missing() {
762        let ctx = Ctx {
763            api_key: None,
764            environment: Environment::Local,
765            api_base: None,
766            config_path: PathBuf::from("/dev/null"),
767            dry_run: false,
768            quiet: false,
769            ..Default::default()
770        };
771        match ctx.client() {
772            Err(CmdError::MissingApiKey) => {}
773            Err(other) => panic!("expected MissingApiKey, got {other:?}"),
774            Ok(_) => panic!("expected MissingApiKey, got Ok(client)"),
775        }
776    }
777
778    #[test]
779    fn ctx_client_builds_when_api_key_present() {
780        let ctx = Ctx {
781            api_key: Some("tk_test_abc".into()),
782            environment: Environment::Local,
783            api_base: None,
784            config_path: PathBuf::from("/dev/null"),
785            dry_run: false,
786            quiet: false,
787            ..Default::default()
788        };
789        ctx.client().expect("client should build with a valid key");
790    }
791
792    fn cfg_with(api_key: Option<&str>, environment: Option<Environment>) -> Config {
793        Config {
794            api_key: api_key.map(str::to_string),
795            environment,
796            ..Config::default()
797        }
798    }
799
800    #[test]
801    fn from_parts_threads_wallet_keystore_confirm_log_format_from_config() {
802        let cfg = Config {
803            wallet_address: Some("0xfeed".into()),
804            keystore_path: Some(PathBuf::from("/tmp/k.json")),
805            confirm_above_budget: Some("500".into()),
806            log_format: Some("json".into()),
807            ..Config::default()
808        };
809        let ctx =
810            Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("valid cfg");
811        assert_eq!(ctx.wallet_address.as_deref(), Some("0xfeed"));
812        assert_eq!(
813            ctx.keystore_path.as_deref(),
814            Some(std::path::Path::new("/tmp/k.json"))
815        );
816        assert_eq!(ctx.confirm_above_budget.as_deref(), Some("500"));
817        assert_eq!(ctx.log_format.as_deref(), Some("json"));
818    }
819
820    #[test]
821    fn from_parts_parses_approval_horizon_from_config() {
822        let cfg = Config {
823            approval_horizon: Some("7d".into()),
824            ..Config::default()
825        };
826        let ctx =
827            Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("parse 7d");
828        assert_eq!(ctx.approval_horizon, Some(Duration::from_hours(24 * 7)));
829    }
830
831    #[test]
832    fn from_parts_parses_receipt_timeout_from_config() {
833        let cfg = Config {
834            receipt_timeout: Some("3min".into()),
835            ..Config::default()
836        };
837        let ctx =
838            Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("parse 3min");
839        assert_eq!(ctx.receipt_timeout, Some(Duration::from_mins(3)));
840    }
841
842    #[test]
843    fn from_parts_rejects_malformed_approval_horizon() {
844        let cfg = Config {
845            approval_horizon: Some("7xyz".into()),
846            ..Config::default()
847        };
848        let err = Ctx::from_parts(None, None, None, None, false, false, false, &cfg)
849            .err()
850            .expect("malformed config must fail at startup");
851        match err {
852            CmdError::Usage(msg) => {
853                assert!(msg.contains("approval_horizon"), "msg: {msg}");
854                assert!(msg.contains("7xyz"), "msg: {msg}");
855            }
856            other => panic!("expected Usage, got {other:?}"),
857        }
858    }
859
860    #[test]
861    fn from_parts_rejects_malformed_receipt_timeout() {
862        let cfg = Config {
863            receipt_timeout: Some("nope".into()),
864            ..Config::default()
865        };
866        let err = Ctx::from_parts(None, None, None, None, false, false, false, &cfg)
867            .err()
868            .expect("malformed timeout = startup error");
869        assert!(matches!(err, CmdError::Usage(msg) if msg.contains("receipt_timeout")));
870    }
871
872    #[test]
873    fn from_parts_duration_fields_none_when_config_absent() {
874        let ctx = Ctx::from_parts(
875            None,
876            None,
877            None,
878            None,
879            false,
880            false,
881            false,
882            &Config::default(),
883        )
884        .expect("default cfg is valid");
885        assert!(ctx.approval_horizon.is_none());
886        assert!(ctx.receipt_timeout.is_none());
887    }
888
889    #[test]
890    fn resolve_duration_flag_wins_over_ctx_and_default() {
891        let out = resolve_duration(
892            Some(Duration::from_secs(10)),
893            Some(Duration::from_secs(20)),
894            Duration::from_secs(30),
895        );
896        assert_eq!(out, Duration::from_secs(10));
897    }
898
899    #[test]
900    fn resolve_duration_ctx_wins_over_default_when_no_flag() {
901        let out = resolve_duration(None, Some(Duration::from_secs(20)), Duration::from_secs(30));
902        assert_eq!(out, Duration::from_secs(20));
903    }
904
905    #[test]
906    fn resolve_duration_falls_back_to_default() {
907        let out = resolve_duration(None, None, Duration::from_secs(30));
908        assert_eq!(out, Duration::from_secs(30));
909    }
910
911    fn ctx_with_threshold(threshold: Option<&str>) -> Ctx {
912        Ctx {
913            confirm_above_budget: threshold.map(str::to_string),
914            ..Default::default()
915        }
916    }
917
918    #[test]
919    fn budget_gate_no_op_when_threshold_unset() {
920        let ctx = ctx_with_threshold(None);
921        ctx.enforce_budget_gate(Some("99999"), false, "post a task")
922            .expect("no threshold = no gate");
923    }
924
925    #[test]
926    fn budget_gate_no_op_when_budget_absent() {
927        let ctx = ctx_with_threshold(Some("100"));
928        ctx.enforce_budget_gate(None, false, "post a task")
929            .expect("no budget = nothing to compare");
930    }
931
932    #[test]
933    fn budget_gate_passes_when_under_threshold() {
934        let ctx = ctx_with_threshold(Some("100"));
935        ctx.enforce_budget_gate(Some("50"), false, "post a task")
936            .expect("under threshold passes without --yes");
937    }
938
939    #[test]
940    fn budget_gate_passes_at_threshold_boundary() {
941        let ctx = ctx_with_threshold(Some("100"));
942        ctx.enforce_budget_gate(Some("100"), false, "post a task")
943            .expect("equal-to-threshold passes (gate is strict >)");
944    }
945
946    #[test]
947    fn budget_gate_blocks_above_threshold_without_yes() {
948        let ctx = ctx_with_threshold(Some("100"));
949        let err = ctx
950            .enforce_budget_gate(Some("100.01"), false, "post a task")
951            .expect_err("over threshold without --yes must fail");
952        match err {
953            CmdError::Usage(msg) => {
954                assert!(msg.contains("--yes"), "msg: {msg}");
955                assert!(msg.contains("post a task"), "msg: {msg}");
956            }
957            other => panic!("expected Usage, got {other:?}"),
958        }
959    }
960
961    #[test]
962    fn budget_gate_passes_above_threshold_with_yes() {
963        let ctx = ctx_with_threshold(Some("100"));
964        ctx.enforce_budget_gate(Some("9999"), true, "post a task")
965            .expect("--yes overrides the gate");
966    }
967
968    #[test]
969    fn budget_gate_uses_decimal_not_float_precision() {
970        // f64 parsing would round "0.30000000000000004" to 0.3 and let it
971        // slip past a "0.3" threshold. Decimal preserves every digit so
972        // the gate correctly blocks.
973        let ctx = ctx_with_threshold(Some("0.3"));
974        ctx.enforce_budget_gate(Some("0.30000000000000004"), false, "post a task")
975            .expect_err("decimal compare must detect trailing precision");
976    }
977
978    #[test]
979    fn budget_gate_rejects_non_decimal_threshold() {
980        let ctx = ctx_with_threshold(Some("not-a-number"));
981        let err = ctx
982            .enforce_budget_gate(Some("50"), false, "post a task")
983            .expect_err("garbage threshold = usage error");
984        assert!(matches!(err, CmdError::Usage(_)));
985    }
986
987    #[test]
988    fn from_parts_flag_wins_over_config() {
989        let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
990        let ctx = Ctx::from_parts(
991            Some("flag_key".into()),
992            Some(Environment::Local),
993            Some("http://flag".into()),
994            None,
995            false,
996            false,
997            false,
998            &cfg,
999        )
1000        .expect("valid cfg");
1001        assert_eq!(ctx.api_key.as_deref(), Some("flag_key"));
1002        assert_eq!(ctx.environment, Environment::Local);
1003        // `--api-base` is the only api_base source post-v2 — it should
1004        // round-trip into the in-memory Ctx field unchanged.
1005        assert_eq!(ctx.api_base.as_deref(), Some("http://flag"));
1006    }
1007
1008    #[test]
1009    fn from_parts_config_fills_when_flags_absent() {
1010        // Post-v2: `api_base` is no longer a config field, so the only
1011        // thing the config can supply here is api_key + environment.
1012        let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
1013        let ctx =
1014            Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("valid cfg");
1015        assert_eq!(ctx.api_key.as_deref(), Some("cfg_key"));
1016        assert_eq!(ctx.environment, Environment::Staging);
1017        // No CLI override and no persisted field → in-memory api_base
1018        // stays None; `base_url()` falls through to env default.
1019        assert!(ctx.api_base.is_none());
1020        assert_eq!(ctx.base_url(), Environment::Staging.api_base());
1021    }
1022
1023    #[test]
1024    fn from_parts_defaults_when_nothing_set() {
1025        let ctx = Ctx::from_parts(
1026            None,
1027            None,
1028            None,
1029            None,
1030            false,
1031            false,
1032            false,
1033            &Config::default(),
1034        )
1035        .expect("default cfg is valid");
1036        assert!(ctx.api_key.is_none());
1037        assert_eq!(ctx.environment, DEFAULT_ENVIRONMENT);
1038        assert!(ctx.api_base.is_none());
1039        assert!(!ctx.dry_run);
1040        assert!(!ctx.quiet);
1041    }
1042
1043    #[test]
1044    fn from_parts_flag_partial_overrides_preserve_other_config_fields() {
1045        // Only `api_key` passed on the CLI — environment should still come
1046        // from the config file. (api_base no longer persisted, so there's
1047        // nothing for the config to contribute on that axis.)
1048        let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
1049        let ctx = Ctx::from_parts(
1050            Some("flag_key".into()),
1051            None,
1052            None,
1053            None,
1054            false,
1055            false,
1056            false,
1057            &cfg,
1058        )
1059        .expect("valid cfg");
1060        assert_eq!(ctx.api_key.as_deref(), Some("flag_key"));
1061        assert_eq!(ctx.environment, Environment::Staging);
1062        assert!(ctx.api_base.is_none());
1063    }
1064
1065    #[test]
1066    fn from_parts_rejects_custom_api_base_for_non_local_env() {
1067        // Hostile invocation: --env prod with a CLI-supplied attacker
1068        // api_base. Guard must refuse before any request.
1069        let cfg = cfg_with(Some("stolen_pat"), Some(Environment::Prod));
1070        let err = Ctx::from_parts(
1071            None,
1072            None,
1073            Some("https://evil.example".into()),
1074            None,
1075            false,
1076            false,
1077            false,
1078            &cfg,
1079        )
1080        .err()
1081        .expect("custom api_base on prod must be refused");
1082        match err {
1083            CmdError::Usage(msg) => {
1084                assert!(msg.contains("evil.example"), "msg: {msg}");
1085                assert!(msg.contains("--allow-custom-endpoints"), "msg: {msg}");
1086            }
1087            other => panic!("expected Usage, got {other:?}"),
1088        }
1089    }
1090
1091    #[test]
1092    fn from_parts_allows_custom_api_base_when_opt_in_flag_set() {
1093        let cfg = cfg_with(Some("k"), Some(Environment::Prod));
1094        let ctx = Ctx::from_parts(
1095            None,
1096            None,
1097            Some("https://evil.example".into()),
1098            None,
1099            false,
1100            false,
1101            true,
1102            &cfg,
1103        )
1104        .expect("--allow-custom-endpoints must bypass the guard");
1105        assert_eq!(ctx.api_base.as_deref(), Some("https://evil.example"));
1106    }
1107
1108    #[test]
1109    fn from_parts_allows_custom_api_base_for_local_env() {
1110        // Local dev is sandboxed — no guard penalty.
1111        let cfg = cfg_with(Some("k"), Some(Environment::Local));
1112        let ctx = Ctx::from_parts(
1113            None,
1114            None,
1115            Some("http://127.0.0.1:4001".into()),
1116            None,
1117            false,
1118            false,
1119            false,
1120            &cfg,
1121        )
1122        .expect("local env bypasses guard");
1123        assert_eq!(ctx.api_base.as_deref(), Some("http://127.0.0.1:4001"));
1124    }
1125
1126    #[test]
1127    fn from_parts_accepts_well_known_api_base_without_opt_in() {
1128        let cfg = cfg_with(Some("k"), Some(Environment::Prod));
1129        let ctx = Ctx::from_parts(
1130            None,
1131            None,
1132            Some("https://api.taskfast.app".into()),
1133            None,
1134            false,
1135            false,
1136            false,
1137            &cfg,
1138        )
1139        .expect("well-known api_base passes without --allow-custom-endpoints");
1140        assert_eq!(ctx.api_base.as_deref(), Some("https://api.taskfast.app"));
1141    }
1142
1143    #[test]
1144    fn from_parts_guard_ignores_missing_api_base() {
1145        // No override ⇒ we use the env default ⇒ nothing to guard against.
1146        let ctx = Ctx::from_parts(
1147            None,
1148            None,
1149            None,
1150            None,
1151            false,
1152            false,
1153            false,
1154            &Config::default(),
1155        )
1156        .expect("no api_base = no guard");
1157        assert!(ctx.api_base.is_none());
1158    }
1159
1160    #[test]
1161    fn network_invariant_ok_when_single_advertised_matches() {
1162        let res = check_network_invariant(
1163            Environment::Prod,
1164            "https://api.taskfast.app",
1165            &["mainnet".into()],
1166            true,
1167        );
1168        assert!(res.is_ok(), "exact match passes strict mode: {res:?}");
1169    }
1170
1171    #[test]
1172    fn network_invariant_strict_rejects_wrong_single_network() {
1173        let err = check_network_invariant(
1174            Environment::Prod,
1175            "https://api.taskfast.app",
1176            &["testnet".into()],
1177            true,
1178        )
1179        .expect_err("strict mode must reject wrong network");
1180        match err {
1181            CmdError::Server(msg) => {
1182                assert!(msg.contains("testnet"), "msg: {msg}");
1183                assert!(msg.contains("mainnet"), "msg: {msg}");
1184                assert!(msg.contains("issue #62"), "remediation hint: {msg}");
1185            }
1186            other => panic!("expected Server, got {other:?}"),
1187        }
1188    }
1189
1190    #[test]
1191    fn network_invariant_strict_rejects_extra_advertised() {
1192        let err = check_network_invariant(
1193            Environment::Prod,
1194            "https://api.taskfast.app",
1195            &["mainnet".into(), "testnet".into()],
1196            true,
1197        )
1198        .expect_err("strict mode must reject len != 1");
1199        assert!(matches!(err, CmdError::Server(_)));
1200    }
1201
1202    #[test]
1203    fn network_invariant_warn_passes_under_today_server_shape() {
1204        // Today's deployments advertise both networks. Warn-only mode
1205        // (default) keeps the CLI usable until issue #62 closes.
1206        let res = check_network_invariant(
1207            Environment::Staging,
1208            "https://staging.api.taskfast.app",
1209            &["mainnet".into(), "testnet".into()],
1210            false,
1211        );
1212        assert!(
1213            res.is_ok(),
1214            "non-strict mode must let today's multi-network deployments through: {res:?}"
1215        );
1216    }
1217
1218    #[test]
1219    fn network_invariant_warn_passes_when_wrong_single_network() {
1220        // Even a wrong-single-network advertised should warn-only —
1221        // strict mode is opt-in.
1222        let res = check_network_invariant(
1223            Environment::Prod,
1224            "https://api.taskfast.app",
1225            &["testnet".into()],
1226            false,
1227        );
1228        assert!(res.is_ok(), "non-strict mode warns rather than errors");
1229    }
1230
1231    #[test]
1232    fn from_parts_dry_run_and_quiet_are_invocation_scoped() {
1233        // These never come from config, only from the CLI.
1234        let ctx = Ctx::from_parts(
1235            None,
1236            None,
1237            None,
1238            None,
1239            true,
1240            true,
1241            false,
1242            &Config::default(),
1243        )
1244        .expect("default cfg is valid");
1245        assert!(ctx.dry_run);
1246        assert!(ctx.quiet);
1247    }
1248}