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