Skip to main content

taskfast_cli/cmd/
init.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast init` — the onboarding command.
3//!
4//! Replaces `init.sh`'s step 1-9 orchestration with a non-interactive,
5//! CLI-driven flow. Every input comes from a flag, an env var, or the
6//! existing [`Config`] file — there are no TTY prompts, because the
7//! caller is expected to be another agent/LLM.
8//!
9//! # Scope (this slice, am-yvc)
10//!
11//! * api_key: direct via `--api-key` / `TASKFAST_API_KEY` / config file.
12//! * validate: `GET /agents/me` — must be active.
13//! * readiness: `GET /agents/me/readiness` — informs wallet gate.
14//! * wallet: BYOW via `--wallet-address`, or generate + keystore with a
15//!   password sourced from `--wallet-password-file` / `TASKFAST_WALLET_PASSWORD`.
16//! * config file: load + write at `ctx.config_path` (default
17//!   `./.taskfast/config.json`, chmod 600 on unix).
18//! * final readiness assert.
19//!
20//! # Scope (am-z58 extension)
21//!
22//! * `--human-api-key` (+ optional agent-* fields): when no agent key is
23//!   available, POST /agents with the user PAT to mint one. The server
24//!   derives `owner_id` from the PAT, so the CLI never asks the caller for
25//!   it. The minted `api_key` is then used for the rest of the flow and
26//!   written to the config file. Under `--dry-run` the mint is skipped and the
27//!   envelope reports `agent.action = "would_mint"` — the rest of the flow
28//!   is also skipped because the real agent key never materialized.
29//!
30//! # Scope (am-iit extension)
31//!
32//! * Optional `--webhook-url` (+ `--webhook-secret-file`, repeat
33//!   `--webhook-event`) folds webhook registration into the init run:
34//!   PUT /agents/me/webhooks, persist the returned secret (chmod 600),
35//!   and optionally replace the subscription list. Skipped silently
36//!   when the URL isn't supplied so callers who prefer a separate
37//!   `taskfast webhook register` step still get the pre-am-iit flow.
38//!
39//! Deferred to separate beads so this slice stays reviewable:
40//! * `am-c74` — balance polling after faucet dispense.
41//!
42//! # Scope (gh#142 extension)
43//!
44//! * End-of-init funding sanity check: a failed `--fund` faucet request
45//!   or a zero wallet balance prints a prominent stderr warning with the
46//!   manual fallback (`cast rpc tempo_fundAddress …` against the
47//!   deployment's advertised rpc_url, or <https://wallet.tempo.xyz>) and
48//!   the server's `funding_hint` when the readiness `funded` gate emits
49//!   one. The run stays `ok:true` — the gap is a warning, not a failure.
50//!
51//! # `--dry-run` semantics
52//!
53//! Mutations short-circuit: no wallet POST, no config file write, no
54//! keystore write. A wallet is still generated (so the address is real)
55//! but its signer is dropped at the end of the function. Readiness and
56//! profile reads pass through.
57
58use std::path::{Path, PathBuf};
59
60use clap::Parser;
61use serde_json::json;
62
63use super::{CmdError, CmdResult, Ctx};
64use crate::config::Config;
65use crate::envelope::Envelope;
66
67use alloy_signer_local::PrivateKeySigner;
68use taskfast_agent::bootstrap::{create_agent_headless, get_readiness, validate_auth};
69use taskfast_agent::faucet::{request_testnet_funds, FaucetDrop};
70use taskfast_agent::keystore;
71use taskfast_agent::wallet;
72use taskfast_agent::webhooks;
73use taskfast_client::api::types::{AgentCreateRequest, AgentReadiness, WebhookConfigRequest};
74use taskfast_client::TaskFastClient;
75
76use super::webhook::persist_secret;
77
78/// Wallet status string emitted by the server when the agent hasn't
79/// registered one yet. `AgentReadinessChecks.wallet.status == "complete"`
80/// means it's already done.
81const WALLET_STATUS_COMPLETE: &str = "complete";
82
83#[derive(Debug, Parser)]
84// CLI surface: each flag is an independent user opt-in/out. Collapsing
85// them into a state machine or nested enum would make clap's derive
86// macro unergonomic without narrowing the actual accepted inputs.
87#[allow(clippy::struct_excessive_bools)]
88pub struct Args {
89    /// Wallet address to register (BYOW). Mutually exclusive with
90    /// `--generate-wallet`.
91    #[arg(long, conflicts_with = "generate_wallet")]
92    pub wallet_address: Option<String>,
93
94    /// Generate a fresh keypair, persist it via the keystore module, then
95    /// register the derived address with TaskFast.
96    #[arg(long)]
97    pub generate_wallet: bool,
98
99    /// Path to a file containing the keystore password. Required when
100    /// `--generate-wallet` is used without `TASKFAST_WALLET_PASSWORD` set.
101    /// Prefer a mode-0400 file over `--wallet-password` (which leaks via
102    /// process args).
103    #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
104    pub wallet_password_file: Option<PathBuf>,
105
106    /// Explicit keystore path override. Default: XDG data dir +
107    /// `<address>.json`.
108    #[arg(long)]
109    pub keystore_path: Option<PathBuf>,
110
111    /// Skip wallet provisioning entirely. Useful for workers that never
112    /// settle (rare) or for rebuilding config state without touching chain.
113    #[arg(long)]
114    pub skip_wallet: bool,
115
116    /// Opt in to the testnet faucet for a freshly-generated wallet on
117    /// testnet environments (Staging / Local). Off by default so prod
118    /// scripts (and CI flows supplying funds out-of-band) never
119    /// accidentally hit the faucet. No-op on Prod — mainnet is never
120    /// auto-funded.
121    #[arg(long)]
122    pub fund: bool,
123
124    /// User PAT (`tf_user_*`) used to headlessly mint a fresh agent via
125    /// `POST /agents` when no agent API key is available. The server
126    /// derives the owning user from the PAT, so no owner UUID is required.
127    /// Ignored if an agent key is already resolvable (direct flag / env
128    /// var / config file).
129    #[arg(long, env = "TASKFAST_HUMAN_API_KEY")]
130    pub human_api_key: Option<String>,
131
132    /// Display name for the minted agent.
133    #[arg(long, default_value = "taskfast-agent")]
134    pub agent_name: String,
135
136    /// Description for the minted agent.
137    #[arg(long, default_value = "Headless agent registered via taskfast init")]
138    pub agent_description: String,
139
140    /// Capability tag for the minted agent (repeat to pass multiple). If
141    /// none are provided, defaults to `["general"]` so the request still
142    /// satisfies the non-empty-array convention most consumers expect.
143    #[arg(long = "agent-capability", value_name = "CAP")]
144    pub agent_capabilities: Vec<String>,
145
146    /// HTTPS URL to register for webhook event delivery. When supplied,
147    /// init PUTs `/agents/me/webhooks` after the wallet step and (if
148    /// the server returns one) persists the signing secret to
149    /// `--webhook-secret-file`. Omitting this flag leaves webhooks
150    /// untouched — `taskfast webhook register` can configure them later.
151    #[arg(long)]
152    pub webhook_url: Option<String>,
153
154    /// Path to persist the webhook signing secret (chmod 600 on unix).
155    /// The platform returns the secret exactly once at creation time
156    /// — a fresh re-register with an existing config returns `null`
157    /// and the existing file is left untouched.
158    #[arg(long)]
159    pub webhook_secret_file: Option<PathBuf>,
160
161    /// Event type to subscribe to after webhook registration. Repeat
162    /// for multiple. Ignored unless `--webhook-url` is also set. When
163    /// `--webhook-url` is supplied and this flag is omitted, init
164    /// auto-subscribes to the worker default set (same list as
165    /// `taskfast webhook subscribe --default-events`); pass
166    /// `--no-default-events` to opt out and register a URL-only endpoint.
167    #[arg(long = "webhook-event", value_name = "EVENT")]
168    pub webhook_events: Vec<String>,
169
170    /// Opt out of auto-subscribing to default worker events when
171    /// `--webhook-url` is set without any explicit `--webhook-event`.
172    /// Preserves the pre-existing behavior of registering a URL with
173    /// zero subscriptions (a deliberate URL-only push endpoint).
174    #[arg(long)]
175    pub no_default_events: bool,
176
177    /// Disable all TTY prompts even when stdin is a terminal. Use in
178    /// scripts or pipes where interactive fallback would stall. Env:
179    /// `TASKFAST_NO_INTERACTIVE=1`.
180    #[arg(long, env = "TASKFAST_NO_INTERACTIVE")]
181    pub no_interactive: bool,
182
183    /// Inline keystore password populated by the interactive wallet-
184    /// generate prompt. Never exposed as a CLI arg (would leak via
185    /// process args). Takes precedence over `--wallet-password-file`
186    /// when set, so the prompted value round-trips into the normal
187    /// password-resolution path.
188    #[arg(skip)]
189    pub inline_wallet_password: Option<String>,
190}
191
192pub async fn run(ctx: &Ctx, args: Args) -> CmdResult {
193    let interactive = !args.no_interactive && crate::cmd::init_tui::is_interactive();
194    run_with_prompter(
195        ctx,
196        args,
197        &crate::cmd::init_tui::DialoguerPrompter,
198        interactive,
199    )
200    .await
201}
202
203/// Same as [`run`] but with an injectable [`crate::cmd::init_tui::Prompter`] and an explicit
204/// `interactive` gate so tests can drive the TUI branches under
205/// `cargo test` (where neither stdin nor stdout is a TTY). Production
206/// callers should use [`run`].
207pub async fn run_with_prompter<P: crate::cmd::init_tui::Prompter>(
208    ctx: &Ctx,
209    mut args: Args,
210    prompter: &P,
211    interactive: bool,
212) -> CmdResult {
213    let cfg_path = ctx.config_path.clone();
214
215    // 1. Load any existing config so re-running init is idempotent. A
216    //    config-supplied api_key is layered under the CLI/env sources
217    //    Ctx already resolved (flag > env var > config).
218    let mut cfg = Config::load(&cfg_path)?;
219
220    // 1a. Resolve the agent API key. If none is available but the caller
221    //     supplied a user PAT, mint a fresh agent headlessly and use the
222    //     returned key. Under --dry-run we short-circuit before the POST
223    //     and return early — the rest of the flow depends on a real key.
224    //
225    //     Interactive fallback: when no key and no --human-api-key, and
226    //     we're attached to a TTY, prompt the human for their PAT and
227    //     greet them via /users/me before minting.
228    let (api_key, agent_outcome) = match resolve_api_key(ctx, &cfg) {
229        Ok(k) => (k, AgentOutcome::PreExisting),
230        Err(CmdError::MissingApiKey) => {
231            let pat = resolve_pat(ctx, &args, interactive, prompter).await?;
232            let minted = mint_agent(ctx, &args, &pat).await?;
233            match minted {
234                MintedAgent::DryRun { ref intent } => {
235                    return Ok(Envelope::success(
236                        ctx.environment,
237                        ctx.dry_run,
238                        build_dry_run_mint_envelope(&cfg_path, intent),
239                    ));
240                }
241                MintedAgent::Live { ref api_key, .. } => {
242                    (api_key.clone(), AgentOutcome::Minted(minted))
243                }
244            }
245        }
246        Err(e) => return Err(e),
247    };
248
249    // 1b. Interactive wallet-mode prompt. Only fires when this run just
250    //     minted a fresh agent AND the human gave us zero wallet signal
251    //     on the command line. Re-init against an existing agent key is
252    //     treated as silent (preserves `init_idempotent_on_reinit`) so
253    //     humans re-running `taskfast init` to refresh state don't get
254    //     re-prompted about wallet setup they already completed.
255    if interactive
256        && matches!(agent_outcome, AgentOutcome::Minted(_))
257        && args.wallet_address.is_none()
258        && !args.generate_wallet
259        && !args.skip_wallet
260    {
261        apply_wallet_mode_prompt(&mut args, prompter)?;
262    }
263
264    let effective_ctx = Ctx {
265        api_key: Some(api_key.clone()),
266        ..ctx.clone()
267    };
268    let client = effective_ctx.client()?;
269
270    // 2. Validate auth + fetch readiness.
271    //    On Auth failure with a PreExisting key, rewrite the error with a
272    //    remediation hint — the common cause is a stale api_key left over in
273    //    the config from a prior init run whose agent was deleted server-side.
274    let profile = match validate_auth(&client).await {
275        Ok(p) => p,
276        Err(taskfast_client::Error::Auth(msg))
277            if matches!(agent_outcome, AgentOutcome::PreExisting) =>
278        {
279            return Err(CmdError::Auth(stale_key_hint(
280                &msg, &cfg_path, &cfg, ctx, &args,
281            )));
282        }
283        Err(e) => return Err(CmdError::from(e)),
284    };
285    assert_active(&profile)?;
286    // Cross-system invariant — fail-closed before any wallet/agent state
287    // is written if the deployment advertises a different (or additional)
288    // network than the env mandates. Skipped under --dry-run so a `taskfast
289    // init --dry-run` still succeeds against a fresh deployment.
290    if !ctx.dry_run {
291        super::enforce_server_network_invariant(&effective_ctx, &client).await?;
292    }
293    let readiness = get_readiness(&client).await.map_err(CmdError::from)?;
294
295    // 3. Wallet provisioning.
296    let wallet_outcome = if args.skip_wallet {
297        WalletOutcome::Skipped
298    } else if readiness.checks.wallet.status == WALLET_STATUS_COMPLETE
299        && args.wallet_address.is_none()
300        && !args.generate_wallet
301    {
302        // Nothing to do — server already has a wallet and caller isn't
303        // forcing a new one.
304        WalletOutcome::AlreadyConfigured
305    } else {
306        provision_wallet(&client, &args, ctx.dry_run).await?
307    };
308
309    // 4. Update the config in-memory (always — writing is gated by dry-run).
310    //    `api_base` and `network` are no longer persisted — both are derived
311    //    from `environment` at runtime via `Environment::api_base` /
312    //    `Environment::network`.
313    cfg.environment = Some(ctx.environment);
314    cfg.api_key = Some(api_key.clone());
315    if let Some(addr) = wallet_outcome.address() {
316        cfg.wallet_address = Some(addr.to_string());
317    }
318    if let Some(path) = wallet_outcome.keystore_path() {
319        cfg.keystore_path = Some(path.to_path_buf());
320    }
321    if let AgentOutcome::Minted(MintedAgent::Live { id: Some(id), .. }) = &agent_outcome {
322        cfg.agent_id = Some(id.clone());
323    }
324    if let Some(url) = args.webhook_url.as_deref().filter(|s| !s.trim().is_empty()) {
325        cfg.webhook_url = Some(url.to_string());
326    }
327    if let Some(path) = args.webhook_secret_file.as_ref() {
328        cfg.webhook_secret_path = Some(path.clone());
329    }
330
331    let config_written = if ctx.dry_run {
332        false
333    } else {
334        cfg.save(&cfg_path)?;
335        true
336    };
337
338    // 4b. Testnet funding. When a wallet was just generated on `--network
339    //     testnet`, hit the public Tempo moderato faucet. Fire-and-surface:
340    //     we report the faucet's tx hashes in the envelope but don't block
341    //     on confirmation here. Caller-side balance polling lives under
342    //     am-c74.
343    //
344    //     Mainnet is deliberately skipped — production wallets must be
345    //     funded by the owning human at `https://wallet.tempo.xyz`. The
346    //     envelope surfaces this with `status: "skipped", reason: "mainnet"`
347    //     plus a `funding_hint` so orchestrators can tell the human where
348    //     to go.
349    let faucet_outcome = maybe_request_faucet(
350        &args,
351        ctx.environment.network(),
352        &wallet_outcome,
353        ctx.dry_run,
354    )
355    .await;
356
357    // 4c. Optional webhook registration. Only runs when `--webhook-url`
358    //     is provided; otherwise the envelope reports `status: "skipped"`
359    //     so orchestrators can tell the step ran and found nothing to do
360    //     (vs. the CLI not supporting webhooks at all).
361    let webhook_outcome = maybe_configure_webhook(&client, &args, ctx.dry_run).await;
362
363    // 5. Final readiness check — surfaces any remaining gates (webhook,
364    //    funding) the caller still has to clear.
365    let final_readiness = get_readiness(&client).await.map_err(CmdError::from)?;
366
367    // 5b. Funding sanity check (gh#142): a faucet failure or zero wallet
368    //     balance gets a prominent stderr warning with the manual fallback,
369    //     so it can't sit quietly next to a successful envelope.
370    warn_if_unfunded(
371        &client,
372        ctx,
373        cfg.wallet_address.as_deref(),
374        &faucet_outcome,
375        &final_readiness,
376    )
377    .await;
378
379    let data = build_envelope_data(
380        &cfg_path,
381        config_written,
382        &wallet_outcome,
383        &agent_outcome,
384        &final_readiness,
385        &faucet_outcome,
386        &webhook_outcome,
387        ctx.dry_run,
388    );
389    Ok(Envelope::success(ctx.environment, ctx.dry_run, data))
390}
391
392/// Result of the agent-key resolution step. When the caller already had
393/// a key (flag / env var / config file), this is `PreExisting` and the
394/// envelope stays quiet about it. When a key was minted via
395/// `--human-api-key`, the envelope surfaces the minted agent's id/name.
396enum AgentOutcome {
397    PreExisting,
398    Minted(MintedAgent),
399}
400
401/// Live vs dry-run distinction for minting. Live carries the full
402/// response; dry-run carries just the would-have-called payload so the
403/// envelope can echo it back without touching the network.
404enum MintedAgent {
405    Live {
406        api_key: String,
407        id: Option<String>,
408        name: Option<String>,
409    },
410    DryRun {
411        intent: MintIntent,
412    },
413}
414
415struct MintIntent {
416    name: String,
417    description: String,
418    capabilities: Vec<String>,
419}
420
421/// Resolve the PAT used to mint a fresh agent. Priority: `--human-api-key`
422/// (flag / env) → interactive prompt (when TTY-attached). Absent both,
423/// propagate the original [`CmdError::MissingApiKey`] so non-interactive
424/// callers see the same message they did before the TUI landed.
425async fn resolve_pat<P: crate::cmd::init_tui::Prompter>(
426    ctx: &Ctx,
427    args: &Args,
428    interactive: bool,
429    prompter: &P,
430) -> Result<String, CmdError> {
431    if let Some(p) = args.human_api_key.as_deref().filter(|s| !s.is_empty()) {
432        return Ok(p.to_string());
433    }
434    if !interactive {
435        return Err(CmdError::MissingApiKey);
436    }
437    let accounts_url = crate::accounts_url(ctx.base_url());
438    let pat = prompter
439        .pat(&accounts_url)
440        .map_err(|e| CmdError::Usage(format!("PAT prompt failed: {e}")))?;
441    // Greet via /users/me when available. 404 (endpoint not yet deployed)
442    // falls back to a neutral confirmation — we never block the flow on
443    // the greeting.
444    let pat_client = TaskFastClient::from_api_key(ctx.base_url(), &pat).map_err(CmdError::from)?;
445    let profile = pat_client.get_user_profile().await.ok().flatten();
446    eprintln!("{}", crate::cmd::init_tui::greeting(profile.as_ref()));
447    Ok(pat)
448}
449
450/// Drive the interactive wallet-mode prompt and fold the result back
451/// into `args` so the existing `provision_wallet` branches see the same
452/// state they would have after flag parsing.
453fn apply_wallet_mode_prompt<P: crate::cmd::init_tui::Prompter>(
454    args: &mut Args,
455    prompter: &P,
456) -> Result<(), CmdError> {
457    use crate::cmd::init_tui::WalletMode;
458    let mode = prompter
459        .wallet_mode()
460        .map_err(|e| CmdError::Usage(format!("wallet-mode prompt failed: {e}")))?;
461    match mode {
462        WalletMode::Byow => {
463            let addr = prompter
464                .wallet_address()
465                .map_err(|e| CmdError::Usage(format!("wallet-address prompt failed: {e}")))?;
466            args.wallet_address = Some(addr.trim().to_string());
467        }
468        WalletMode::Generate => {
469            args.generate_wallet = true;
470            let pw = prompter
471                .wallet_password()
472                .map_err(|e| CmdError::Usage(format!("password prompt failed: {e}")))?;
473            args.inline_wallet_password = Some(pw);
474        }
475        WalletMode::Skip => {
476            args.skip_wallet = true;
477        }
478    }
479    Ok(())
480}
481
482async fn mint_agent(ctx: &Ctx, args: &Args, pat: &str) -> Result<MintedAgent, CmdError> {
483    if pat.is_empty() {
484        return Err(CmdError::Usage("PAT is empty".into()));
485    }
486
487    let capabilities = if args.agent_capabilities.is_empty() {
488        vec!["general".to_string()]
489    } else {
490        args.agent_capabilities.clone()
491    };
492
493    if ctx.dry_run {
494        return Ok(MintedAgent::DryRun {
495            intent: MintIntent {
496                name: args.agent_name.clone(),
497                description: args.agent_description.clone(),
498                capabilities,
499            },
500        });
501    }
502
503    let pat_client = TaskFastClient::from_api_key(ctx.base_url(), pat).map_err(CmdError::from)?;
504    let body = AgentCreateRequest {
505        owner_id: None,
506        name: args.agent_name.clone(),
507        description: args.agent_description.clone(),
508        capabilities,
509        rate: None,
510        max_task_budget: None,
511        daily_spend_limit: None,
512        payout_method: None,
513        payment_method: None,
514        tempo_wallet_address: None,
515    };
516    let resp = create_agent_headless(&pat_client, &body)
517        .await
518        .map_err(CmdError::from)?;
519    let api_key = resp
520        .api_key
521        .clone()
522        .ok_or_else(|| CmdError::Server("POST /agents returned no api_key despite 201".into()))?;
523    Ok(MintedAgent::Live {
524        api_key,
525        id: resp.id.map(|u| u.to_string()),
526        name: resp.name.clone(),
527    })
528}
529
530fn build_dry_run_mint_envelope(cfg_path: &Path, intent: &MintIntent) -> serde_json::Value {
531    json!({
532        "agent": {
533            "action": "would_mint",
534            "name": intent.name,
535            "description": intent.description,
536            "capabilities": intent.capabilities,
537        },
538        "config_file": {
539            "path": cfg_path.display().to_string(),
540            "written": false,
541            "would_write": true,
542        },
543        "ready_to_work": false,
544    })
545}
546
547/// Layered api_key resolution: Ctx (flag / env var / already-merged
548/// config value) wins, then the on-disk config, else
549/// [`CmdError::MissingApiKey`].
550///
551/// `Ctx::from_parts` already folds `cfg.api_key` into `ctx.api_key`, so
552/// by the time we get here the config lookup is a redundant last resort
553/// — kept for the test-driven path that constructs `Ctx` directly
554/// without going through `from_parts`.
555fn resolve_api_key(ctx: &Ctx, cfg: &Config) -> Result<String, CmdError> {
556    if let Some(k) = ctx.api_key.as_deref() {
557        if !k.is_empty() {
558            return Ok(k.to_string());
559        }
560    }
561    if let Some(k) = cfg.api_key.as_deref() {
562        if !k.is_empty() {
563            return Ok(k.to_string());
564        }
565    }
566    Err(CmdError::MissingApiKey)
567}
568
569/// Build a remediation hint for the common "stale config" failure: the agent
570/// api_key stored in the config (or passed via flag/env) is rejected by the
571/// server. Lists the key's likely source and the minimum steps to recover.
572fn stale_key_hint(msg: &str, cfg_path: &Path, cfg: &Config, ctx: &Ctx, args: &Args) -> String {
573    let source = if cfg.api_key.as_deref().is_some_and(|k| !k.is_empty()) {
574        format!("config file {}", cfg_path.display())
575    } else if ctx.api_key.is_some() {
576        "--api-key flag or TASKFAST_API_KEY env".to_string()
577    } else {
578        "unknown".to_string()
579    };
580    let had_pat = args.human_api_key.is_some();
581    let pat_note = if had_pat {
582        "\n  note: --human-api-key was provided but ignored because an existing api_key was found; \
583         the PAT mints a new agent only when no api_key is resolvable."
584    } else {
585        ""
586    };
587    format!(
588        "{msg}\n  hint: agent api_key rejected — likely stale (agent deleted or key rotated).\n  \
589         source: {source}\n  fix: delete {path} (and unset TASKFAST_API_KEY if set), then re-run \
590         `taskfast --env {env} init --human-api-key <tf_user_...>` to mint a fresh agent.{pat_note}",
591        path = cfg_path.display(),
592        env = ctx.environment.as_str(),
593    )
594}
595
596fn assert_active(profile: &taskfast_client::api::types::AgentProfile) -> Result<(), CmdError> {
597    match profile.status.as_deref() {
598        Some("active") => Ok(()),
599        Some(other) => Err(CmdError::Validation {
600            code: "agent_not_active".into(),
601            message: format!("agent status is {other}; owner must reactivate"),
602        }),
603        None => Err(CmdError::Server(
604            "GET /agents/me returned no status field".into(),
605        )),
606    }
607}
608
609/// Side-effect summary the CLI envelope surfaces to orchestrators.
610enum WalletOutcome {
611    /// Server already had a wallet on file and the caller didn't override.
612    AlreadyConfigured,
613    /// BYOW path — caller supplied `--wallet-address`.
614    ByoRegistered { address: String },
615    /// Generated keypair, saved to keystore, registered with server.
616    Generated {
617        address: String,
618        keystore_path: PathBuf,
619    },
620    /// Dry-run generate — address is real but keystore wasn't written.
621    DryRunGenerated { address: String },
622    /// `--skip-wallet` or dry-run BYOW without register.
623    Skipped,
624}
625
626impl WalletOutcome {
627    fn address(&self) -> Option<&str> {
628        match self {
629            Self::ByoRegistered { address }
630            | Self::Generated { address, .. }
631            | Self::DryRunGenerated { address } => Some(address),
632            Self::AlreadyConfigured | Self::Skipped => None,
633        }
634    }
635
636    fn keystore_path(&self) -> Option<&Path> {
637        match self {
638            Self::Generated { keystore_path, .. } => Some(keystore_path),
639            _ => None,
640        }
641    }
642
643    fn tag(&self) -> &'static str {
644        match self {
645            Self::AlreadyConfigured => "already_configured",
646            Self::ByoRegistered { .. } => "byo_registered",
647            Self::Generated { .. } => "generated",
648            Self::DryRunGenerated { .. } => "dry_run_generated",
649            Self::Skipped => "skipped",
650        }
651    }
652}
653
654async fn provision_wallet(
655    client: &TaskFastClient,
656    args: &Args,
657    dry_run: bool,
658) -> Result<WalletOutcome, CmdError> {
659    if let Some(addr) = args.wallet_address.as_deref() {
660        if dry_run {
661            return Ok(WalletOutcome::Skipped);
662        }
663        wallet::register_wallet(client, addr)
664            .await
665            .map_err(CmdError::from)?;
666        return Ok(WalletOutcome::ByoRegistered {
667            address: addr.to_string(),
668        });
669    }
670    if !args.generate_wallet {
671        return Err(CmdError::Usage(
672            "pass --wallet-address <0x...> or --generate-wallet (or --skip-wallet to defer)".into(),
673        ));
674    }
675
676    let signer = wallet::generate_signer();
677    let address = format!("0x{}", hex::encode(signer.address().as_slice()));
678
679    if dry_run {
680        // Return the address without resolving the password or persisting;
681        // caller just needs to see what *would* have been generated.
682        return Ok(WalletOutcome::DryRunGenerated { address });
683    }
684
685    let password = resolve_wallet_password(args)?;
686    let keystore_path = persist_keystore(&signer, args, &password)?;
687    wallet::register_wallet(client, &address)
688        .await
689        .map_err(CmdError::from)?;
690    Ok(WalletOutcome::Generated {
691        address,
692        keystore_path,
693    })
694}
695
696fn resolve_wallet_password(args: &Args) -> Result<String, CmdError> {
697    // Interactive prompt populates this; takes precedence so the prompted
698    // value isn't second-guessed by a stale env var from a prior shell.
699    if let Some(pw) = args.inline_wallet_password.as_deref() {
700        if !pw.is_empty() {
701            return Ok(pw.to_string());
702        }
703    }
704    if let Ok(pw) = std::env::var("TASKFAST_WALLET_PASSWORD") {
705        if !pw.is_empty() {
706            return Ok(pw);
707        }
708    }
709    let path = args.wallet_password_file.as_deref().ok_or_else(|| {
710        CmdError::Usage(
711            "--generate-wallet requires --wallet-password-file or TASKFAST_WALLET_PASSWORD".into(),
712        )
713    })?;
714    let raw = std::fs::read_to_string(path).map_err(|e| {
715        CmdError::Usage(format!(
716            "cannot read wallet password file {}: {e}",
717            path.display()
718        ))
719    })?;
720    let trimmed = raw.trim_end_matches(['\n', '\r']);
721    if trimmed.is_empty() {
722        return Err(CmdError::Usage(format!(
723            "wallet password file {} is empty",
724            path.display()
725        )));
726    }
727    Ok(trimmed.to_string())
728}
729
730fn persist_keystore(
731    signer: &PrivateKeySigner,
732    args: &Args,
733    password: &str,
734) -> Result<PathBuf, CmdError> {
735    let path = match &args.keystore_path {
736        Some(p) => p.clone(),
737        None => keystore::default_keyfile_path(signer.address()).map_err(CmdError::from)?,
738    };
739    keystore::save_signer(signer, &path, password).map_err(CmdError::from)
740}
741
742/// Envelope-friendly description of the faucet step. `Skipped` covers the
743/// common cases where no request was warranted (mainnet, BYOW, wallet
744/// already present, dry-run) — the reason is echoed so the caller can tell
745/// *why* we didn't hit the faucet.
746enum FaucetOutcome {
747    Skipped { reason: &'static str },
748    Requested { drops: Vec<FaucetDrop> },
749    Failed { error: String },
750}
751
752async fn maybe_request_faucet(
753    args: &Args,
754    network: crate::Network,
755    wallet: &WalletOutcome,
756    dry_run: bool,
757) -> FaucetOutcome {
758    if dry_run {
759        return FaucetOutcome::Skipped { reason: "dry_run" };
760    }
761    if !args.fund {
762        return FaucetOutcome::Skipped {
763            reason: "fund_flag_not_set",
764        };
765    }
766    if !matches!(network, crate::Network::Testnet) {
767        return FaucetOutcome::Skipped { reason: "mainnet" };
768    }
769    let address = match wallet {
770        WalletOutcome::Generated { address, .. } => address.clone(),
771        WalletOutcome::ByoRegistered { address } => address.clone(),
772        _ => {
773            return FaucetOutcome::Skipped {
774                reason: "no_fresh_wallet",
775            };
776        }
777    };
778    let http = reqwest::Client::new();
779    match request_testnet_funds(&http, &address).await {
780        Ok(drops) => FaucetOutcome::Requested { drops },
781        Err(e) => FaucetOutcome::Failed {
782            error: e.to_string(),
783        },
784    }
785}
786
787/// Parse the server's hex-encoded wei balance string (`"0x0"` = zero,
788/// all-zero hex = zero). Anything unparseable yields `None` = unknown.
789fn parse_wei_hex(s: Option<&str>) -> Option<u128> {
790    let s = s?.trim();
791    let hex = s.strip_prefix("0x").unwrap_or(s);
792    if hex.is_empty() {
793        return None;
794    }
795    u128::from_str_radix(hex, 16).ok()
796}
797
798/// Build the end-of-init funding warning (gh#142). Fires when the faucet
799/// step failed or the wallet balance is zero — a funding gap must not sit
800/// quietly next to a successful init, because the next on-chain command
801/// (post, escrow sign, settle) would fail. Returns `None` on healthy or
802/// unknown states so the warning never becomes noise.
803fn build_funding_warning(
804    faucet_error: Option<&str>,
805    balance_wei: Option<u128>,
806    address: &str,
807    rpc_url: Option<&str>,
808    funding_hint: Option<&str>,
809) -> Option<String> {
810    let zero_balance = balance_wei.is_some_and(|b| b == 0);
811    if faucet_error.is_none() && !zero_balance {
812        return None;
813    }
814    let mut lines = Vec::new();
815    match (faucet_error, zero_balance) {
816        (Some(err), _) => lines.push(format!(
817            "WARNING: testnet faucet funding failed (--fund): {err}"
818        )),
819        (None, true) => lines.push(format!(
820            "WARNING: wallet {address} balance is zero at the end of init"
821        )),
822        (None, false) => return None,
823    }
824    lines.push(
825        "  the next on-chain command will fail until the wallet is funded. \
826         manual fallback:"
827            .to_string(),
828    );
829    if let Some(rpc) = rpc_url {
830        lines.push(format!(
831            "    cast rpc tempo_fundAddress '[\"{address}\"]' --raw --rpc-url {rpc}"
832        ));
833    }
834    lines.push("  or fund at https://wallet.tempo.xyz".to_string());
835    if let Some(hint) = funding_hint {
836        lines.push(format!("  server funding hint: {hint}"));
837    }
838    Some(lines.join("\n"))
839}
840
841/// End-of-init funding sanity check (gh#142). Consults the server's
842/// balance proxy once and, when the wallet looks unfunded, prints the
843/// stderr warning with the manual fallback (Tempo RPC faucet via `cast`,
844/// or the web wallet). Best-effort: any balance/RPC lookup failure stays
845/// silent — the faucet step's own error (if any) still warns, and the
846/// envelope keeps carrying the server's `readiness.checks.funded` gate
847/// for machine consumers. Testnet only; mainnet wallets are the owning
848/// human's to fund and the envelope already points at wallet.tempo.xyz.
849async fn warn_if_unfunded(
850    client: &TaskFastClient,
851    ctx: &Ctx,
852    wallet_address: Option<&str>,
853    faucet: &FaucetOutcome,
854    readiness: &AgentReadiness,
855) {
856    if ctx.dry_run {
857        return;
858    }
859    if !matches!(ctx.environment.network(), crate::Network::Testnet) {
860        return;
861    }
862    let Some(address) = wallet_address else {
863        return;
864    };
865    let faucet_error = match faucet {
866        FaucetOutcome::Failed { error } => Some(error.as_str()),
867        _ => None,
868    };
869    let balance_wei = match client.inner().get_wallet_balance().await {
870        Ok(resp) => parse_wei_hex(resp.into_inner().available_balance.as_deref()),
871        Err(e) => {
872            tracing::warn!(error = %e, "init: balance check unavailable; skipping zero-balance warning");
873            None
874        }
875    };
876    if build_funding_warning(
877        faucet_error,
878        balance_wei,
879        address,
880        None,
881        readiness.checks.funded.funding_hint.as_deref(),
882    )
883    .is_none()
884    {
885        return;
886    }
887    // Warning will fire — resolve the advertised rpc_url for the cast
888    // fallback. Failure just drops the cast line, keeping the web fallback.
889    let rpc_url = client
890        .fetch_network_config()
891        .await
892        .ok()
893        .and_then(|cfg| cfg.entry(ctx.environment.network().as_str()).ok())
894        .map(|entry| entry.rpc_url.clone());
895    if let Some(warning) = build_funding_warning(
896        faucet_error,
897        balance_wei,
898        address,
899        rpc_url.as_deref(),
900        readiness.checks.funded.funding_hint.as_deref(),
901    ) {
902        eprintln!("{warning}");
903    }
904}
905
906/// Outcome of the optional webhook step. `Skipped` is the default when
907/// `--webhook-url` wasn't passed; the remaining variants mirror the
908/// shell-script states (`registered`, `registered + subscribed`,
909/// `would_register`).
910#[cfg_attr(test, derive(Debug))]
911enum WebhookOutcome {
912    Skipped,
913    DryRun {
914        url: String,
915        events: Vec<String>,
916        secret_file: Option<PathBuf>,
917    },
918    Registered {
919        url: String,
920        secret_returned: bool,
921        secret_persisted: bool,
922        secret_file: Option<PathBuf>,
923        subscribed: Option<Vec<String>>,
924    },
925    Failed {
926        error: String,
927    },
928}
929
930/// Resolve the final event subscription list for `taskfast init
931/// --webhook-url`. Precedence: explicit `--webhook-event` flags win
932/// outright; absent-events + `--no-default-events` yields an empty list
933/// (URL-only registration); absent-events + default path fans out to
934/// the 9-event worker default (`webhook::DEFAULT_WORKER_EVENTS`). Shared
935/// between the live subscription path and the `--dry-run` envelope so
936/// the preview never diverges from what would be pushed.
937fn resolve_webhook_events(args: &Args) -> Vec<String> {
938    if !args.webhook_events.is_empty() {
939        return args.webhook_events.clone();
940    }
941    if args.no_default_events {
942        return Vec::new();
943    }
944    crate::cmd::webhook::DEFAULT_WORKER_EVENTS
945        .iter()
946        .map(|s| (*s).to_string())
947        .collect()
948}
949
950async fn maybe_configure_webhook(
951    client: &TaskFastClient,
952    args: &Args,
953    dry_run: bool,
954) -> WebhookOutcome {
955    let Some(url) = args.webhook_url.as_deref().filter(|s| !s.trim().is_empty()) else {
956        return WebhookOutcome::Skipped;
957    };
958    let events = resolve_webhook_events(args);
959    if dry_run {
960        return WebhookOutcome::DryRun {
961            url: url.to_string(),
962            events,
963            secret_file: args.webhook_secret_file.clone(),
964        };
965    }
966    let body = WebhookConfigRequest {
967        url: url.to_string(),
968        secret: None,
969        events: None,
970    };
971    let cfg = match webhooks::configure_webhook(client, &body).await {
972        Ok(c) => c,
973        Err(e) => {
974            return WebhookOutcome::Failed {
975                error: e.to_string(),
976            };
977        }
978    };
979    let secret_persisted = match (cfg.secret.as_deref(), args.webhook_secret_file.as_ref()) {
980        (Some(secret), Some(path)) => match persist_secret(path, secret) {
981            Ok(()) => true,
982            Err(e) => {
983                return WebhookOutcome::Failed {
984                    error: e.to_string(),
985                };
986            }
987        },
988        _ => false,
989    };
990    let subscribed = if events.is_empty() {
991        None
992    } else {
993        match webhooks::update_subscriptions(client, events).await {
994            Ok(subs) => Some(subs.subscribed_event_types),
995            Err(e) => {
996                return WebhookOutcome::Failed {
997                    error: e.to_string(),
998                };
999            }
1000        }
1001    };
1002    WebhookOutcome::Registered {
1003        url: cfg.url,
1004        secret_returned: cfg.secret.is_some(),
1005        secret_persisted,
1006        secret_file: args.webhook_secret_file.clone(),
1007        subscribed,
1008    }
1009}
1010
1011fn build_envelope_data(
1012    cfg_path: &Path,
1013    config_written: bool,
1014    wallet: &WalletOutcome,
1015    agent: &AgentOutcome,
1016    readiness: &AgentReadiness,
1017    faucet: &FaucetOutcome,
1018    webhook: &WebhookOutcome,
1019    dry_run: bool,
1020) -> serde_json::Value {
1021    let mut wallet_obj = json!({
1022        "status": wallet.tag(),
1023    });
1024    if let Some(addr) = wallet.address() {
1025        wallet_obj["address"] = json!(addr);
1026    }
1027    if let Some(path) = wallet.keystore_path() {
1028        wallet_obj["keystore_path"] = json!(path.display().to_string());
1029    }
1030
1031    let mut cfg_obj = json!({
1032        "path": cfg_path.display().to_string(),
1033        "written": config_written,
1034    });
1035    if dry_run && !config_written {
1036        cfg_obj["would_write"] = json!(true);
1037    }
1038
1039    let faucet_obj = match faucet {
1040        FaucetOutcome::Skipped { reason } => {
1041            let mut o = json!({
1042                "status": "skipped",
1043                "reason": reason,
1044            });
1045            // On mainnet, point the caller at the human funding path so
1046            // they don't assume the CLI "just handles it" like it does on
1047            // testnet.
1048            if *reason == "mainnet" {
1049                o["funding_hint"] = json!({
1050                    "url": "https://wallet.tempo.xyz",
1051                    "message": "Production wallets must be funded manually by the owning human at wallet.tempo.xyz before posting or settling.",
1052                });
1053            }
1054            o
1055        }
1056        FaucetOutcome::Requested { drops } => json!({
1057            "status": "requested",
1058            "drops": drops.iter().map(|d| json!({
1059                "token": d.token,
1060                "tx_hash": d.tx_hash,
1061            })).collect::<Vec<_>>(),
1062        }),
1063        FaucetOutcome::Failed { error } => json!({
1064            "status": "failed",
1065            "error": error,
1066        }),
1067    };
1068
1069    let webhook_obj = match webhook {
1070        WebhookOutcome::Skipped => json!({ "status": "skipped" }),
1071        WebhookOutcome::DryRun {
1072            url,
1073            events,
1074            secret_file,
1075        } => {
1076            let mut o = json!({
1077                "status": "would_register",
1078                "url": url,
1079                "events": events,
1080            });
1081            if let Some(p) = secret_file {
1082                o["secret_file"] = json!(p.display().to_string());
1083            }
1084            o
1085        }
1086        WebhookOutcome::Registered {
1087            url,
1088            secret_returned,
1089            secret_persisted,
1090            secret_file,
1091            subscribed,
1092        } => {
1093            let mut o = json!({
1094                "status": "registered",
1095                "url": url,
1096                "secret_returned": secret_returned,
1097                "secret_persisted": secret_persisted,
1098            });
1099            if let Some(p) = secret_file {
1100                o["secret_file"] = json!(p.display().to_string());
1101            }
1102            if let Some(subs) = subscribed {
1103                o["subscribed"] = json!(subs);
1104            }
1105            o
1106        }
1107        WebhookOutcome::Failed { error } => json!({
1108            "status": "failed",
1109            "error": error,
1110        }),
1111    };
1112
1113    let mut out = json!({
1114        "wallet": wallet_obj,
1115        "config_file": cfg_obj,
1116        "faucet": faucet_obj,
1117        "webhook": webhook_obj,
1118        "readiness": readiness,
1119        "ready_to_work": readiness.ready_to_work,
1120    });
1121    if let AgentOutcome::Minted(MintedAgent::Live { id, name, .. }) = agent {
1122        let mut a = json!({ "action": "minted" });
1123        if let Some(id) = id {
1124            a["id"] = json!(id);
1125        }
1126        if let Some(name) = name {
1127            a["name"] = json!(name);
1128        }
1129        out["agent"] = a;
1130    }
1131    out
1132}
1133
1134#[cfg(test)]
1135mod tests {
1136    use super::*;
1137    use crate::Environment;
1138
1139    fn base_args() -> Args {
1140        Args {
1141            wallet_address: None,
1142            generate_wallet: false,
1143            wallet_password_file: None,
1144            keystore_path: None,
1145            skip_wallet: false,
1146            fund: false,
1147            human_api_key: None,
1148            agent_name: "taskfast-agent".into(),
1149            agent_description: "Headless agent registered via taskfast init".into(),
1150            agent_capabilities: Vec::new(),
1151            webhook_url: None,
1152            webhook_secret_file: None,
1153            webhook_events: Vec::new(),
1154            no_default_events: false,
1155            no_interactive: true,
1156            inline_wallet_password: None,
1157        }
1158    }
1159
1160    fn ctx_with_key(key: Option<&str>) -> Ctx {
1161        Ctx {
1162            api_key: key.map(String::from),
1163            environment: Environment::Local,
1164            api_base: None,
1165            config_path: PathBuf::from("/dev/null"),
1166            dry_run: false,
1167            quiet: true,
1168            ..Default::default()
1169        }
1170    }
1171
1172    fn cfg_with_key(key: Option<&str>) -> Config {
1173        Config {
1174            api_key: key.map(str::to_string),
1175            ..Config::default()
1176        }
1177    }
1178
1179    #[test]
1180    fn resolve_api_key_prefers_ctx_over_config() {
1181        let ctx = ctx_with_key(Some("from-flag"));
1182        let cfg = cfg_with_key(Some("from-file"));
1183        assert_eq!(resolve_api_key(&ctx, &cfg).unwrap(), "from-flag");
1184    }
1185
1186    #[test]
1187    fn resolve_api_key_falls_back_to_config() {
1188        let ctx = ctx_with_key(None);
1189        let cfg = cfg_with_key(Some("from-file"));
1190        assert_eq!(resolve_api_key(&ctx, &cfg).unwrap(), "from-file");
1191    }
1192
1193    #[test]
1194    fn resolve_api_key_empty_string_is_treated_as_absent() {
1195        let ctx = ctx_with_key(Some(""));
1196        let cfg = cfg_with_key(Some(""));
1197        match resolve_api_key(&ctx, &cfg) {
1198            Err(CmdError::MissingApiKey) => {}
1199            other => panic!("expected MissingApiKey, got {other:?}"),
1200        }
1201    }
1202
1203    #[test]
1204    fn provision_without_wallet_flag_errors_as_usage() {
1205        // We can't easily drive provision_wallet without a client, but we
1206        // can prove the flag-gate logic: with no flags set, the error is
1207        // Usage, not MissingApiKey.
1208        let args = base_args();
1209        assert!(args.wallet_address.is_none() && !args.generate_wallet);
1210        // The branch that returns Usage lives in provision_wallet — a
1211        // dedicated integration test drives the end-to-end path.
1212    }
1213
1214    #[test]
1215    fn wallet_outcome_tag_is_stable() {
1216        // Pinning the tag strings is intentional: orchestrators branch on
1217        // `data.wallet.status` so changes here are breaking.
1218        assert_eq!(WalletOutcome::AlreadyConfigured.tag(), "already_configured");
1219        assert_eq!(
1220            WalletOutcome::ByoRegistered {
1221                address: "0x00".into()
1222            }
1223            .tag(),
1224            "byo_registered"
1225        );
1226        assert_eq!(
1227            WalletOutcome::Generated {
1228                address: "0x00".into(),
1229                keystore_path: PathBuf::from("/tmp/x")
1230            }
1231            .tag(),
1232            "generated"
1233        );
1234        assert_eq!(
1235            WalletOutcome::DryRunGenerated {
1236                address: "0x00".into()
1237            }
1238            .tag(),
1239            "dry_run_generated"
1240        );
1241        assert_eq!(WalletOutcome::Skipped.tag(), "skipped");
1242    }
1243
1244    #[test]
1245    fn resolve_webhook_events_uses_defaults_when_events_empty() {
1246        // URL set, no explicit events, no opt-out → auto-subscribe to
1247        // the 9-event worker default. Guards PLAN #11: raw `init
1248        // --webhook-url X` must not silently register a zero-event
1249        // endpoint.
1250        let args = Args {
1251            webhook_url: Some("https://h.example/x".into()),
1252            ..base_args()
1253        };
1254        let events = resolve_webhook_events(&args);
1255        assert_eq!(events, crate::cmd::webhook::DEFAULT_WORKER_EVENTS);
1256    }
1257
1258    #[test]
1259    fn resolve_webhook_events_respects_no_default_events_opt_out() {
1260        // Explicit opt-out preserves the legacy URL-only behavior.
1261        let args = Args {
1262            webhook_url: Some("https://h.example/x".into()),
1263            no_default_events: true,
1264            ..base_args()
1265        };
1266        assert!(resolve_webhook_events(&args).is_empty());
1267    }
1268
1269    #[test]
1270    fn resolve_webhook_events_explicit_events_override_defaults() {
1271        // Any `--webhook-event` wins: the defaults are NOT mixed in.
1272        let args = Args {
1273            webhook_url: Some("https://h.example/x".into()),
1274            webhook_events: vec!["task_assigned".into()],
1275            ..base_args()
1276        };
1277        assert_eq!(resolve_webhook_events(&args), vec!["task_assigned"]);
1278    }
1279
1280    #[test]
1281    fn resolve_webhook_events_explicit_events_win_over_no_default_events() {
1282        // Safety: --no-default-events is an opt-out flag for the
1283        // auto-population path; explicit events should still flow.
1284        let args = Args {
1285            webhook_url: Some("https://h.example/x".into()),
1286            webhook_events: vec!["bid_accepted".into()],
1287            no_default_events: true,
1288            ..base_args()
1289        };
1290        assert_eq!(resolve_webhook_events(&args), vec!["bid_accepted"]);
1291    }
1292
1293    // ─── end-of-init funding warning (gh#142) ─────────────────────────────
1294
1295    #[test]
1296    fn funding_warning_faucet_failure_lists_manual_fallback() {
1297        let w = build_funding_warning(
1298            Some("faucet returned status 405: method not allowed"),
1299            Some(0),
1300            "0xabc0000000000000000000000000000000000000",
1301            Some("https://rpc.testnet.example"),
1302            None,
1303        )
1304        .expect("faucet failure must warn");
1305        assert!(w.contains("faucet returned status 405"), "got: {w}");
1306        assert!(w.contains("0xabc0000000000000000000000000000000000000"));
1307        assert!(w.contains(
1308            "cast rpc tempo_fundAddress \
1309             '[\"0xabc0000000000000000000000000000000000000\"]' \
1310             --raw --rpc-url https://rpc.testnet.example"
1311        ));
1312        assert!(w.contains("https://wallet.tempo.xyz"));
1313    }
1314
1315    #[test]
1316    fn funding_warning_zero_balance_without_faucet_failure_still_warns() {
1317        // The issue's second trigger: `--fund` succeeded or was never
1318        // passed, but the wallet balance is zero at the end of init —
1319        // the next on-chain command would fail.
1320        let w = build_funding_warning(
1321            None,
1322            Some(0),
1323            "0xabc0000000000000000000000000000000000000",
1324            Some("https://rpc.testnet.example"),
1325            None,
1326        )
1327        .expect("zero balance must warn");
1328        assert!(w.contains("zero"), "got: {w}");
1329        assert!(w.contains("https://wallet.tempo.xyz"));
1330    }
1331
1332    #[test]
1333    fn funding_warning_silent_when_funded() {
1334        assert!(build_funding_warning(
1335            None,
1336            Some(42),
1337            "0xabc0000000000000000000000000000000000000",
1338            Some("https://rpc.testnet.example"),
1339            None,
1340        )
1341        .is_none());
1342    }
1343
1344    #[test]
1345    fn funding_warning_silent_when_balance_unknown_and_faucet_did_not_fail() {
1346        // Balance endpoint down + faucet didn't fail → no signal, no noise.
1347        assert!(build_funding_warning(
1348            None,
1349            None,
1350            "0xabc0000000000000000000000000000000000000",
1351            Some("https://rpc.testnet.example"),
1352            None,
1353        )
1354        .is_none());
1355    }
1356
1357    #[test]
1358    fn funding_warning_without_rpc_url_omits_cast_line_keeps_web_fallback() {
1359        let w = build_funding_warning(
1360            Some("faucet http request failed"),
1361            Some(0),
1362            "0xabc0000000000000000000000000000000000000",
1363            None,
1364            None,
1365        )
1366        .expect("must still warn");
1367        assert!(!w.contains("cast rpc"), "got: {w}");
1368        assert!(w.contains("https://wallet.tempo.xyz"));
1369    }
1370
1371    #[test]
1372    fn funding_warning_surfaces_server_funding_hint() {
1373        let w = build_funding_warning(
1374            None,
1375            Some(0),
1376            "0xabc0000000000000000000000000000000000000",
1377            None,
1378            Some("https://wallet.tempo.xyz/topup"),
1379        )
1380        .expect("must warn");
1381        assert!(w.contains("https://wallet.tempo.xyz/topup"), "got: {w}");
1382    }
1383
1384    #[test]
1385    fn parse_wei_hex_handles_0x_zero_and_plain_hex_forms() {
1386        assert_eq!(parse_wei_hex(Some("0x0")), Some(0));
1387        assert_eq!(
1388            parse_wei_hex(Some(
1389                "0x000000000000000000000000000000000000000000000000000000000000000a"
1390            )),
1391            Some(10)
1392        );
1393        assert_eq!(parse_wei_hex(None), None);
1394        assert_eq!(parse_wei_hex(Some("0x")), None);
1395    }
1396
1397    #[tokio::test]
1398    async fn maybe_configure_webhook_dry_run_surfaces_default_events() {
1399        // Dry-run envelope must preview what the live path would push —
1400        // otherwise `init --webhook-url X --dry-run` silently differs
1401        // from the real call.
1402        let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
1403        let args = Args {
1404            webhook_url: Some("https://h.example/x".into()),
1405            ..base_args()
1406        };
1407        let outcome = maybe_configure_webhook(&client, &args, true).await;
1408        match outcome {
1409            WebhookOutcome::DryRun { events, url, .. } => {
1410                assert_eq!(url, "https://h.example/x");
1411                assert_eq!(events, crate::cmd::webhook::DEFAULT_WORKER_EVENTS);
1412            }
1413            other => panic!("expected DryRun, got {other:?}"),
1414        }
1415    }
1416
1417    #[tokio::test]
1418    async fn maybe_configure_webhook_dry_run_respects_no_default_events() {
1419        let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
1420        let args = Args {
1421            webhook_url: Some("https://h.example/x".into()),
1422            no_default_events: true,
1423            ..base_args()
1424        };
1425        let outcome = maybe_configure_webhook(&client, &args, true).await;
1426        match outcome {
1427            WebhookOutcome::DryRun { events, .. } => assert!(events.is_empty()),
1428            other => panic!("expected DryRun, got {other:?}"),
1429        }
1430    }
1431
1432    #[tokio::test]
1433    async fn maybe_configure_webhook_no_url_is_skipped() {
1434        // Regression guard: the auto-subscribe branch must not fire
1435        // when the URL is absent — init stays single-purpose.
1436        let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
1437        let outcome = maybe_configure_webhook(&client, &base_args(), true).await;
1438        assert!(matches!(outcome, WebhookOutcome::Skipped));
1439    }
1440}