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    use taskfast_client::api::types::AgentProfileStatus;
598    match profile.status {
599        Some(AgentProfileStatus::Active) => Ok(()),
600        Some(other) => Err(CmdError::Validation {
601            code: "agent_not_active".into(),
602            message: format!("agent status is {other:?}; owner must reactivate"),
603        }),
604        None => Err(CmdError::Server(
605            "GET /agents/me returned no status field".into(),
606        )),
607    }
608}
609
610/// Side-effect summary the CLI envelope surfaces to orchestrators.
611enum WalletOutcome {
612    /// Server already had a wallet on file and the caller didn't override.
613    AlreadyConfigured,
614    /// BYOW path — caller supplied `--wallet-address`.
615    ByoRegistered { address: String },
616    /// Generated keypair, saved to keystore, registered with server.
617    Generated {
618        address: String,
619        keystore_path: PathBuf,
620    },
621    /// Dry-run generate — address is real but keystore wasn't written.
622    DryRunGenerated { address: String },
623    /// `--skip-wallet` or dry-run BYOW without register.
624    Skipped,
625}
626
627impl WalletOutcome {
628    fn address(&self) -> Option<&str> {
629        match self {
630            Self::ByoRegistered { address }
631            | Self::Generated { address, .. }
632            | Self::DryRunGenerated { address } => Some(address),
633            Self::AlreadyConfigured | Self::Skipped => None,
634        }
635    }
636
637    fn keystore_path(&self) -> Option<&Path> {
638        match self {
639            Self::Generated { keystore_path, .. } => Some(keystore_path),
640            _ => None,
641        }
642    }
643
644    fn tag(&self) -> &'static str {
645        match self {
646            Self::AlreadyConfigured => "already_configured",
647            Self::ByoRegistered { .. } => "byo_registered",
648            Self::Generated { .. } => "generated",
649            Self::DryRunGenerated { .. } => "dry_run_generated",
650            Self::Skipped => "skipped",
651        }
652    }
653}
654
655async fn provision_wallet(
656    client: &TaskFastClient,
657    args: &Args,
658    dry_run: bool,
659) -> Result<WalletOutcome, CmdError> {
660    if let Some(addr) = args.wallet_address.as_deref() {
661        if dry_run {
662            return Ok(WalletOutcome::Skipped);
663        }
664        wallet::register_wallet(client, addr)
665            .await
666            .map_err(CmdError::from)?;
667        return Ok(WalletOutcome::ByoRegistered {
668            address: addr.to_string(),
669        });
670    }
671    if !args.generate_wallet {
672        return Err(CmdError::Usage(
673            "pass --wallet-address <0x...> or --generate-wallet (or --skip-wallet to defer)".into(),
674        ));
675    }
676
677    let signer = wallet::generate_signer();
678    let address = format!("0x{}", hex::encode(signer.address().as_slice()));
679
680    if dry_run {
681        // Return the address without resolving the password or persisting;
682        // caller just needs to see what *would* have been generated.
683        return Ok(WalletOutcome::DryRunGenerated { address });
684    }
685
686    let password = resolve_wallet_password(args)?;
687    let keystore_path = persist_keystore(&signer, args, &password)?;
688    wallet::register_wallet(client, &address)
689        .await
690        .map_err(CmdError::from)?;
691    Ok(WalletOutcome::Generated {
692        address,
693        keystore_path,
694    })
695}
696
697fn resolve_wallet_password(args: &Args) -> Result<String, CmdError> {
698    // Interactive prompt populates this; takes precedence so the prompted
699    // value isn't second-guessed by a stale env var from a prior shell.
700    if let Some(pw) = args.inline_wallet_password.as_deref() {
701        if !pw.is_empty() {
702            return Ok(pw.to_string());
703        }
704    }
705    if let Ok(pw) = std::env::var("TASKFAST_WALLET_PASSWORD") {
706        if !pw.is_empty() {
707            return Ok(pw);
708        }
709    }
710    let path = args.wallet_password_file.as_deref().ok_or_else(|| {
711        CmdError::Usage(
712            "--generate-wallet requires --wallet-password-file or TASKFAST_WALLET_PASSWORD".into(),
713        )
714    })?;
715    let raw = std::fs::read_to_string(path).map_err(|e| {
716        CmdError::Usage(format!(
717            "cannot read wallet password file {}: {e}",
718            path.display()
719        ))
720    })?;
721    let trimmed = raw.trim_end_matches(['\n', '\r']);
722    if trimmed.is_empty() {
723        return Err(CmdError::Usage(format!(
724            "wallet password file {} is empty",
725            path.display()
726        )));
727    }
728    Ok(trimmed.to_string())
729}
730
731fn persist_keystore(
732    signer: &PrivateKeySigner,
733    args: &Args,
734    password: &str,
735) -> Result<PathBuf, CmdError> {
736    let path = match &args.keystore_path {
737        Some(p) => p.clone(),
738        None => keystore::default_keyfile_path(signer.address()).map_err(CmdError::from)?,
739    };
740    keystore::save_signer(signer, &path, password).map_err(CmdError::from)
741}
742
743/// Envelope-friendly description of the faucet step. `Skipped` covers the
744/// common cases where no request was warranted (mainnet, BYOW, wallet
745/// already present, dry-run) — the reason is echoed so the caller can tell
746/// *why* we didn't hit the faucet.
747enum FaucetOutcome {
748    Skipped { reason: &'static str },
749    Requested { drops: Vec<FaucetDrop> },
750    Failed { error: String },
751}
752
753async fn maybe_request_faucet(
754    args: &Args,
755    network: crate::Network,
756    wallet: &WalletOutcome,
757    dry_run: bool,
758) -> FaucetOutcome {
759    if dry_run {
760        return FaucetOutcome::Skipped { reason: "dry_run" };
761    }
762    if !args.fund {
763        return FaucetOutcome::Skipped {
764            reason: "fund_flag_not_set",
765        };
766    }
767    if !matches!(network, crate::Network::Testnet) {
768        return FaucetOutcome::Skipped { reason: "mainnet" };
769    }
770    let address = match wallet {
771        WalletOutcome::Generated { address, .. } => address.clone(),
772        WalletOutcome::ByoRegistered { address } => address.clone(),
773        _ => {
774            return FaucetOutcome::Skipped {
775                reason: "no_fresh_wallet",
776            };
777        }
778    };
779    let http = reqwest::Client::new();
780    match request_testnet_funds(&http, &address).await {
781        Ok(drops) => FaucetOutcome::Requested { drops },
782        Err(e) => FaucetOutcome::Failed {
783            error: e.to_string(),
784        },
785    }
786}
787
788/// Parse the server's hex-encoded wei balance string (`"0x0"` = zero,
789/// all-zero hex = zero). Anything unparseable yields `None` = unknown.
790fn parse_wei_hex(s: Option<&str>) -> Option<u128> {
791    let s = s?.trim();
792    let hex = s.strip_prefix("0x").unwrap_or(s);
793    if hex.is_empty() {
794        return None;
795    }
796    u128::from_str_radix(hex, 16).ok()
797}
798
799/// Build the end-of-init funding warning (gh#142). Fires when the faucet
800/// step failed or the wallet balance is zero — a funding gap must not sit
801/// quietly next to a successful init, because the next on-chain command
802/// (post, escrow sign, settle) would fail. Returns `None` on healthy or
803/// unknown states so the warning never becomes noise.
804fn build_funding_warning(
805    faucet_error: Option<&str>,
806    balance_wei: Option<u128>,
807    address: &str,
808    rpc_url: Option<&str>,
809    funding_hint: Option<&str>,
810) -> Option<String> {
811    let zero_balance = balance_wei.is_some_and(|b| b == 0);
812    if faucet_error.is_none() && !zero_balance {
813        return None;
814    }
815    let mut lines = Vec::new();
816    match (faucet_error, zero_balance) {
817        (Some(err), _) => lines.push(format!(
818            "WARNING: testnet faucet funding failed (--fund): {err}"
819        )),
820        (None, true) => lines.push(format!(
821            "WARNING: wallet {address} balance is zero at the end of init"
822        )),
823        (None, false) => return None,
824    }
825    lines.push(
826        "  the next on-chain command will fail until the wallet is funded. \
827         manual fallback:"
828            .to_string(),
829    );
830    if let Some(rpc) = rpc_url {
831        lines.push(format!(
832            "    cast rpc tempo_fundAddress '[\"{address}\"]' --raw --rpc-url {rpc}"
833        ));
834    }
835    lines.push("  or fund at https://wallet.tempo.xyz".to_string());
836    if let Some(hint) = funding_hint {
837        lines.push(format!("  server funding hint: {hint}"));
838    }
839    Some(lines.join("\n"))
840}
841
842/// End-of-init funding sanity check (gh#142). Consults the server's
843/// balance proxy once and, when the wallet looks unfunded, prints the
844/// stderr warning with the manual fallback (Tempo RPC faucet via `cast`,
845/// or the web wallet). Best-effort: any balance/RPC lookup failure stays
846/// silent — the faucet step's own error (if any) still warns, and the
847/// envelope keeps carrying the server's `readiness.checks.funded` gate
848/// for machine consumers. Testnet only; mainnet wallets are the owning
849/// human's to fund and the envelope already points at wallet.tempo.xyz.
850async fn warn_if_unfunded(
851    client: &TaskFastClient,
852    ctx: &Ctx,
853    wallet_address: Option<&str>,
854    faucet: &FaucetOutcome,
855    readiness: &AgentReadiness,
856) {
857    if ctx.dry_run {
858        return;
859    }
860    if !matches!(ctx.environment.network(), crate::Network::Testnet) {
861        return;
862    }
863    let Some(address) = wallet_address else {
864        return;
865    };
866    let faucet_error = match faucet {
867        FaucetOutcome::Failed { error } => Some(error.as_str()),
868        _ => None,
869    };
870    let balance_wei = match client.inner().get_wallet_balance().await {
871        Ok(resp) => parse_wei_hex(resp.into_inner().available_balance.as_deref()),
872        Err(e) => {
873            tracing::warn!(error = %e, "init: balance check unavailable; skipping zero-balance warning");
874            None
875        }
876    };
877    if build_funding_warning(
878        faucet_error,
879        balance_wei,
880        address,
881        None,
882        readiness.checks.funded.funding_hint.as_deref(),
883    )
884    .is_none()
885    {
886        return;
887    }
888    // Warning will fire — resolve the advertised rpc_url for the cast
889    // fallback. Failure just drops the cast line, keeping the web fallback.
890    let rpc_url = client
891        .fetch_network_config()
892        .await
893        .ok()
894        .and_then(|cfg| cfg.entry(ctx.environment.network().as_str()).ok())
895        .map(|entry| entry.rpc_url.clone());
896    if let Some(warning) = build_funding_warning(
897        faucet_error,
898        balance_wei,
899        address,
900        rpc_url.as_deref(),
901        readiness.checks.funded.funding_hint.as_deref(),
902    ) {
903        eprintln!("{warning}");
904    }
905}
906
907/// Outcome of the optional webhook step. `Skipped` is the default when
908/// `--webhook-url` wasn't passed; the remaining variants mirror the
909/// shell-script states (`registered`, `registered + subscribed`,
910/// `would_register`).
911#[cfg_attr(test, derive(Debug))]
912enum WebhookOutcome {
913    Skipped,
914    DryRun {
915        url: String,
916        events: Vec<String>,
917        secret_file: Option<PathBuf>,
918    },
919    Registered {
920        url: String,
921        secret_returned: bool,
922        secret_persisted: bool,
923        secret_file: Option<PathBuf>,
924        subscribed: Option<Vec<String>>,
925    },
926    Failed {
927        error: String,
928    },
929}
930
931/// Resolve the final event subscription list for `taskfast init
932/// --webhook-url`. Precedence: explicit `--webhook-event` flags win
933/// outright; absent-events + `--no-default-events` yields an empty list
934/// (URL-only registration); absent-events + default path fans out to
935/// the 9-event worker default (`webhook::DEFAULT_WORKER_EVENTS`). Shared
936/// between the live subscription path and the `--dry-run` envelope so
937/// the preview never diverges from what would be pushed.
938fn resolve_webhook_events(args: &Args) -> Vec<String> {
939    if !args.webhook_events.is_empty() {
940        return args.webhook_events.clone();
941    }
942    if args.no_default_events {
943        return Vec::new();
944    }
945    crate::cmd::webhook::DEFAULT_WORKER_EVENTS
946        .iter()
947        .map(|s| (*s).to_string())
948        .collect()
949}
950
951async fn maybe_configure_webhook(
952    client: &TaskFastClient,
953    args: &Args,
954    dry_run: bool,
955) -> WebhookOutcome {
956    let Some(url) = args.webhook_url.as_deref().filter(|s| !s.trim().is_empty()) else {
957        return WebhookOutcome::Skipped;
958    };
959    let events = resolve_webhook_events(args);
960    if dry_run {
961        return WebhookOutcome::DryRun {
962            url: url.to_string(),
963            events,
964            secret_file: args.webhook_secret_file.clone(),
965        };
966    }
967    let body = WebhookConfigRequest {
968        url: url.to_string(),
969        secret: None,
970        events: None,
971    };
972    let cfg = match webhooks::configure_webhook(client, &body).await {
973        Ok(c) => c,
974        Err(e) => {
975            return WebhookOutcome::Failed {
976                error: e.to_string(),
977            };
978        }
979    };
980    let secret_persisted = match (cfg.secret.as_deref(), args.webhook_secret_file.as_ref()) {
981        (Some(secret), Some(path)) => match persist_secret(path, secret) {
982            Ok(()) => true,
983            Err(e) => {
984                return WebhookOutcome::Failed {
985                    error: e.to_string(),
986                };
987            }
988        },
989        _ => false,
990    };
991    let subscribed = if events.is_empty() {
992        None
993    } else {
994        match webhooks::update_subscriptions(client, events).await {
995            Ok(subs) => Some(subs.subscribed_event_types),
996            Err(e) => {
997                return WebhookOutcome::Failed {
998                    error: e.to_string(),
999                };
1000            }
1001        }
1002    };
1003    WebhookOutcome::Registered {
1004        url: cfg.url,
1005        secret_returned: cfg.secret.is_some(),
1006        secret_persisted,
1007        secret_file: args.webhook_secret_file.clone(),
1008        subscribed,
1009    }
1010}
1011
1012fn build_envelope_data(
1013    cfg_path: &Path,
1014    config_written: bool,
1015    wallet: &WalletOutcome,
1016    agent: &AgentOutcome,
1017    readiness: &AgentReadiness,
1018    faucet: &FaucetOutcome,
1019    webhook: &WebhookOutcome,
1020    dry_run: bool,
1021) -> serde_json::Value {
1022    let mut wallet_obj = json!({
1023        "status": wallet.tag(),
1024    });
1025    if let Some(addr) = wallet.address() {
1026        wallet_obj["address"] = json!(addr);
1027    }
1028    if let Some(path) = wallet.keystore_path() {
1029        wallet_obj["keystore_path"] = json!(path.display().to_string());
1030    }
1031
1032    let mut cfg_obj = json!({
1033        "path": cfg_path.display().to_string(),
1034        "written": config_written,
1035    });
1036    if dry_run && !config_written {
1037        cfg_obj["would_write"] = json!(true);
1038    }
1039
1040    let faucet_obj = match faucet {
1041        FaucetOutcome::Skipped { reason } => {
1042            let mut o = json!({
1043                "status": "skipped",
1044                "reason": reason,
1045            });
1046            // On mainnet, point the caller at the human funding path so
1047            // they don't assume the CLI "just handles it" like it does on
1048            // testnet.
1049            if *reason == "mainnet" {
1050                o["funding_hint"] = json!({
1051                    "url": "https://wallet.tempo.xyz",
1052                    "message": "Production wallets must be funded manually by the owning human at wallet.tempo.xyz before posting or settling.",
1053                });
1054            }
1055            o
1056        }
1057        FaucetOutcome::Requested { drops } => json!({
1058            "status": "requested",
1059            "drops": drops.iter().map(|d| json!({
1060                "token": d.token,
1061                "tx_hash": d.tx_hash,
1062            })).collect::<Vec<_>>(),
1063        }),
1064        FaucetOutcome::Failed { error } => json!({
1065            "status": "failed",
1066            "error": error,
1067        }),
1068    };
1069
1070    let webhook_obj = match webhook {
1071        WebhookOutcome::Skipped => json!({ "status": "skipped" }),
1072        WebhookOutcome::DryRun {
1073            url,
1074            events,
1075            secret_file,
1076        } => {
1077            let mut o = json!({
1078                "status": "would_register",
1079                "url": url,
1080                "events": events,
1081            });
1082            if let Some(p) = secret_file {
1083                o["secret_file"] = json!(p.display().to_string());
1084            }
1085            o
1086        }
1087        WebhookOutcome::Registered {
1088            url,
1089            secret_returned,
1090            secret_persisted,
1091            secret_file,
1092            subscribed,
1093        } => {
1094            let mut o = json!({
1095                "status": "registered",
1096                "url": url,
1097                "secret_returned": secret_returned,
1098                "secret_persisted": secret_persisted,
1099            });
1100            if let Some(p) = secret_file {
1101                o["secret_file"] = json!(p.display().to_string());
1102            }
1103            if let Some(subs) = subscribed {
1104                o["subscribed"] = json!(subs);
1105            }
1106            o
1107        }
1108        WebhookOutcome::Failed { error } => json!({
1109            "status": "failed",
1110            "error": error,
1111        }),
1112    };
1113
1114    let mut out = json!({
1115        "wallet": wallet_obj,
1116        "config_file": cfg_obj,
1117        "faucet": faucet_obj,
1118        "webhook": webhook_obj,
1119        "readiness": readiness,
1120        "ready_to_work": readiness.ready_to_work,
1121    });
1122    if let AgentOutcome::Minted(MintedAgent::Live { id, name, .. }) = agent {
1123        let mut a = json!({ "action": "minted" });
1124        if let Some(id) = id {
1125            a["id"] = json!(id);
1126        }
1127        if let Some(name) = name {
1128            a["name"] = json!(name);
1129        }
1130        out["agent"] = a;
1131    }
1132    out
1133}
1134
1135#[cfg(test)]
1136mod tests {
1137    use super::*;
1138    use crate::Environment;
1139
1140    fn base_args() -> Args {
1141        Args {
1142            wallet_address: None,
1143            generate_wallet: false,
1144            wallet_password_file: None,
1145            keystore_path: None,
1146            skip_wallet: false,
1147            fund: false,
1148            human_api_key: None,
1149            agent_name: "taskfast-agent".into(),
1150            agent_description: "Headless agent registered via taskfast init".into(),
1151            agent_capabilities: Vec::new(),
1152            webhook_url: None,
1153            webhook_secret_file: None,
1154            webhook_events: Vec::new(),
1155            no_default_events: false,
1156            no_interactive: true,
1157            inline_wallet_password: None,
1158        }
1159    }
1160
1161    fn ctx_with_key(key: Option<&str>) -> Ctx {
1162        Ctx {
1163            api_key: key.map(String::from),
1164            environment: Environment::Local,
1165            api_base: None,
1166            config_path: PathBuf::from("/dev/null"),
1167            dry_run: false,
1168            quiet: true,
1169            ..Default::default()
1170        }
1171    }
1172
1173    fn cfg_with_key(key: Option<&str>) -> Config {
1174        Config {
1175            api_key: key.map(str::to_string),
1176            ..Config::default()
1177        }
1178    }
1179
1180    #[test]
1181    fn resolve_api_key_prefers_ctx_over_config() {
1182        let ctx = ctx_with_key(Some("from-flag"));
1183        let cfg = cfg_with_key(Some("from-file"));
1184        assert_eq!(resolve_api_key(&ctx, &cfg).unwrap(), "from-flag");
1185    }
1186
1187    #[test]
1188    fn resolve_api_key_falls_back_to_config() {
1189        let ctx = ctx_with_key(None);
1190        let cfg = cfg_with_key(Some("from-file"));
1191        assert_eq!(resolve_api_key(&ctx, &cfg).unwrap(), "from-file");
1192    }
1193
1194    #[test]
1195    fn resolve_api_key_empty_string_is_treated_as_absent() {
1196        let ctx = ctx_with_key(Some(""));
1197        let cfg = cfg_with_key(Some(""));
1198        match resolve_api_key(&ctx, &cfg) {
1199            Err(CmdError::MissingApiKey) => {}
1200            other => panic!("expected MissingApiKey, got {other:?}"),
1201        }
1202    }
1203
1204    #[test]
1205    fn provision_without_wallet_flag_errors_as_usage() {
1206        // We can't easily drive provision_wallet without a client, but we
1207        // can prove the flag-gate logic: with no flags set, the error is
1208        // Usage, not MissingApiKey.
1209        let args = base_args();
1210        assert!(args.wallet_address.is_none() && !args.generate_wallet);
1211        // The branch that returns Usage lives in provision_wallet — a
1212        // dedicated integration test drives the end-to-end path.
1213    }
1214
1215    #[test]
1216    fn wallet_outcome_tag_is_stable() {
1217        // Pinning the tag strings is intentional: orchestrators branch on
1218        // `data.wallet.status` so changes here are breaking.
1219        assert_eq!(WalletOutcome::AlreadyConfigured.tag(), "already_configured");
1220        assert_eq!(
1221            WalletOutcome::ByoRegistered {
1222                address: "0x00".into()
1223            }
1224            .tag(),
1225            "byo_registered"
1226        );
1227        assert_eq!(
1228            WalletOutcome::Generated {
1229                address: "0x00".into(),
1230                keystore_path: PathBuf::from("/tmp/x")
1231            }
1232            .tag(),
1233            "generated"
1234        );
1235        assert_eq!(
1236            WalletOutcome::DryRunGenerated {
1237                address: "0x00".into()
1238            }
1239            .tag(),
1240            "dry_run_generated"
1241        );
1242        assert_eq!(WalletOutcome::Skipped.tag(), "skipped");
1243    }
1244
1245    #[test]
1246    fn resolve_webhook_events_uses_defaults_when_events_empty() {
1247        // URL set, no explicit events, no opt-out → auto-subscribe to
1248        // the 9-event worker default. Guards PLAN #11: raw `init
1249        // --webhook-url X` must not silently register a zero-event
1250        // endpoint.
1251        let args = Args {
1252            webhook_url: Some("https://h.example/x".into()),
1253            ..base_args()
1254        };
1255        let events = resolve_webhook_events(&args);
1256        assert_eq!(events, crate::cmd::webhook::DEFAULT_WORKER_EVENTS);
1257    }
1258
1259    #[test]
1260    fn resolve_webhook_events_respects_no_default_events_opt_out() {
1261        // Explicit opt-out preserves the legacy URL-only behavior.
1262        let args = Args {
1263            webhook_url: Some("https://h.example/x".into()),
1264            no_default_events: true,
1265            ..base_args()
1266        };
1267        assert!(resolve_webhook_events(&args).is_empty());
1268    }
1269
1270    #[test]
1271    fn resolve_webhook_events_explicit_events_override_defaults() {
1272        // Any `--webhook-event` wins: the defaults are NOT mixed in.
1273        let args = Args {
1274            webhook_url: Some("https://h.example/x".into()),
1275            webhook_events: vec!["task_assigned".into()],
1276            ..base_args()
1277        };
1278        assert_eq!(resolve_webhook_events(&args), vec!["task_assigned"]);
1279    }
1280
1281    #[test]
1282    fn resolve_webhook_events_explicit_events_win_over_no_default_events() {
1283        // Safety: --no-default-events is an opt-out flag for the
1284        // auto-population path; explicit events should still flow.
1285        let args = Args {
1286            webhook_url: Some("https://h.example/x".into()),
1287            webhook_events: vec!["bid_accepted".into()],
1288            no_default_events: true,
1289            ..base_args()
1290        };
1291        assert_eq!(resolve_webhook_events(&args), vec!["bid_accepted"]);
1292    }
1293
1294    // ─── end-of-init funding warning (gh#142) ─────────────────────────────
1295
1296    #[test]
1297    fn funding_warning_faucet_failure_lists_manual_fallback() {
1298        let w = build_funding_warning(
1299            Some("faucet returned status 405: method not allowed"),
1300            Some(0),
1301            "0xabc0000000000000000000000000000000000000",
1302            Some("https://rpc.testnet.example"),
1303            None,
1304        )
1305        .expect("faucet failure must warn");
1306        assert!(w.contains("faucet returned status 405"), "got: {w}");
1307        assert!(w.contains("0xabc0000000000000000000000000000000000000"));
1308        assert!(w.contains(
1309            "cast rpc tempo_fundAddress \
1310             '[\"0xabc0000000000000000000000000000000000000\"]' \
1311             --raw --rpc-url https://rpc.testnet.example"
1312        ));
1313        assert!(w.contains("https://wallet.tempo.xyz"));
1314    }
1315
1316    #[test]
1317    fn funding_warning_zero_balance_without_faucet_failure_still_warns() {
1318        // The issue's second trigger: `--fund` succeeded or was never
1319        // passed, but the wallet balance is zero at the end of init —
1320        // the next on-chain command would fail.
1321        let w = build_funding_warning(
1322            None,
1323            Some(0),
1324            "0xabc0000000000000000000000000000000000000",
1325            Some("https://rpc.testnet.example"),
1326            None,
1327        )
1328        .expect("zero balance must warn");
1329        assert!(w.contains("zero"), "got: {w}");
1330        assert!(w.contains("https://wallet.tempo.xyz"));
1331    }
1332
1333    #[test]
1334    fn funding_warning_silent_when_funded() {
1335        assert!(build_funding_warning(
1336            None,
1337            Some(42),
1338            "0xabc0000000000000000000000000000000000000",
1339            Some("https://rpc.testnet.example"),
1340            None,
1341        )
1342        .is_none());
1343    }
1344
1345    #[test]
1346    fn funding_warning_silent_when_balance_unknown_and_faucet_did_not_fail() {
1347        // Balance endpoint down + faucet didn't fail → no signal, no noise.
1348        assert!(build_funding_warning(
1349            None,
1350            None,
1351            "0xabc0000000000000000000000000000000000000",
1352            Some("https://rpc.testnet.example"),
1353            None,
1354        )
1355        .is_none());
1356    }
1357
1358    #[test]
1359    fn funding_warning_without_rpc_url_omits_cast_line_keeps_web_fallback() {
1360        let w = build_funding_warning(
1361            Some("faucet http request failed"),
1362            Some(0),
1363            "0xabc0000000000000000000000000000000000000",
1364            None,
1365            None,
1366        )
1367        .expect("must still warn");
1368        assert!(!w.contains("cast rpc"), "got: {w}");
1369        assert!(w.contains("https://wallet.tempo.xyz"));
1370    }
1371
1372    #[test]
1373    fn funding_warning_surfaces_server_funding_hint() {
1374        let w = build_funding_warning(
1375            None,
1376            Some(0),
1377            "0xabc0000000000000000000000000000000000000",
1378            None,
1379            Some("https://wallet.tempo.xyz/topup"),
1380        )
1381        .expect("must warn");
1382        assert!(w.contains("https://wallet.tempo.xyz/topup"), "got: {w}");
1383    }
1384
1385    #[test]
1386    fn parse_wei_hex_handles_0x_zero_and_plain_hex_forms() {
1387        assert_eq!(parse_wei_hex(Some("0x0")), Some(0));
1388        assert_eq!(
1389            parse_wei_hex(Some(
1390                "0x000000000000000000000000000000000000000000000000000000000000000a"
1391            )),
1392            Some(10)
1393        );
1394        assert_eq!(parse_wei_hex(None), None);
1395        assert_eq!(parse_wei_hex(Some("0x")), None);
1396    }
1397
1398    #[tokio::test]
1399    async fn maybe_configure_webhook_dry_run_surfaces_default_events() {
1400        // Dry-run envelope must preview what the live path would push —
1401        // otherwise `init --webhook-url X --dry-run` silently differs
1402        // from the real call.
1403        let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
1404        let args = Args {
1405            webhook_url: Some("https://h.example/x".into()),
1406            ..base_args()
1407        };
1408        let outcome = maybe_configure_webhook(&client, &args, true).await;
1409        match outcome {
1410            WebhookOutcome::DryRun { events, url, .. } => {
1411                assert_eq!(url, "https://h.example/x");
1412                assert_eq!(events, crate::cmd::webhook::DEFAULT_WORKER_EVENTS);
1413            }
1414            other => panic!("expected DryRun, got {other:?}"),
1415        }
1416    }
1417
1418    #[tokio::test]
1419    async fn maybe_configure_webhook_dry_run_respects_no_default_events() {
1420        let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
1421        let args = Args {
1422            webhook_url: Some("https://h.example/x".into()),
1423            no_default_events: true,
1424            ..base_args()
1425        };
1426        let outcome = maybe_configure_webhook(&client, &args, true).await;
1427        match outcome {
1428            WebhookOutcome::DryRun { events, .. } => assert!(events.is_empty()),
1429            other => panic!("expected DryRun, got {other:?}"),
1430        }
1431    }
1432
1433    #[tokio::test]
1434    async fn maybe_configure_webhook_no_url_is_skipped() {
1435        // Regression guard: the auto-subscribe branch must not fire
1436        // when the URL is absent — init stays single-purpose.
1437        let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
1438        let outcome = maybe_configure_webhook(&client, &base_args(), true).await;
1439        assert!(matches!(outcome, WebhookOutcome::Skipped));
1440    }
1441}