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