Skip to main content

taskfast_cli/cmd/
post.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast post` — two-phase task creation (prepare → sign+broadcast → submit).
3//!
4//! Supersedes the `scripts/post-task` shell flow whose defect chain is tracked
5//! under am-q1m. Server contract (`lib/task_fast/payments/tempo_provider.ex`
6//! `charge_submission_fee/4`) accepts **two voucher forms** on
7//! `POST /api/task_drafts/{id}/submit`:
8//!
9//!   - `0x<64hex>` → already-broadcast tx hash; server polls for confirmation.
10//!   - any other hex → raw RLP-encoded signed tx; server broadcasts via
11//!     `eth_sendRawTransaction`.
12//!
13//! We take the **tx-hash voucher path**: the client signs + broadcasts the
14//! ERC-20 transfer locally, then hands the server just the hash. Rationale:
15//! failures on the broadcast side surface to the agent as a concrete RPC
16//! error before we pollute the server's draft state with a would-be-bad
17//! voucher.
18//!
19//! `payload_to_sign` (despite its historical name) is **not** an ECDSA signing
20//! payload — it's the encoded ERC-20 `transfer` calldata. We wrap it in a
21//! replay-safe legacy tx and sign the transaction hash via
22//! [`taskfast_agent::tempo_rpc::sign_and_broadcast_erc20_transfer`].
23
24use std::path::PathBuf;
25
26use alloy_primitives::{Address, Bytes};
27use clap::Parser;
28use serde_json::json;
29use uuid::Uuid;
30
31use super::{validate_override_rpc_url, CmdError, CmdResult, Ctx};
32use crate::envelope::Envelope;
33
34use taskfast_agent::tempo_rpc::{sign_and_broadcast_erc20_transfer, TempoRpcClient};
35use taskfast_chains::tempo::{is_allowed_fee_token, is_known_network};
36use taskfast_client::api::types::{
37    CompletionCriterionInput, TaskDraftPrepareRequest, TaskDraftPrepareRequestAssignmentType,
38    TaskDraftPrepareRequestPosterWalletAddress, TaskDraftSubmitRequest,
39    TaskDraftSubmitRequestSignature,
40};
41use taskfast_client::{map_api_error, TaskFastClient};
42
43#[derive(Debug, Parser)]
44pub struct Args {
45    /// Task title (required).
46    #[arg(long)]
47    pub title: String,
48
49    /// Task description (required, non-empty). Validated client-side so a
50    /// typoed script fails fast instead of paying for a server 422 round-trip.
51    #[arg(long)]
52    pub description: String,
53
54    /// Max budget the poster will pay, as a decimal string ("2.50"). Passed
55    /// through as `budget_max` on the draft.
56    #[arg(long)]
57    pub budget: Option<String>,
58
59    /// Capability tags required from the assignee. Comma-separated.
60    #[arg(long, value_delimiter = ',')]
61    pub capabilities: Vec<String>,
62
63    /// Completion-criterion payout gate as a JSON object. Repeat `--criterion`
64    /// for multiple gates. Shape matches `CompletionCriterionInput`:
65    /// `{"description":"…","check_type":"json_schema|regex|count|http_status|file_exists",`
66    /// `"check_expression":"…","expected_value":"…","target_artifact_pattern":null}`.
67    /// Missing ⇒ no objective gate; server policy decides payout.
68    #[arg(long = "criterion")]
69    pub criteria: Vec<String>,
70
71    /// Path to a JSON file containing an array of `CompletionCriterionInput`
72    /// objects. Merged before any `--criterion` flags (file entries first).
73    /// Use this when you have many gates or want to keep them in version
74    /// control alongside the task.
75    #[arg(long)]
76    pub criteria_file: Option<PathBuf>,
77
78    /// Pickup deadline (RFC3339 timestamp, e.g. `2026-05-01T00:00:00Z`).
79    #[arg(long)]
80    pub pickup_deadline: Option<String>,
81
82    /// Execution deadline (RFC3339 timestamp).
83    #[arg(long)]
84    pub execution_deadline: Option<String>,
85
86    /// Assignment model: `open` (auction to any qualified bidder) or
87    /// `direct` (assign to a specific agent; requires `--direct-agent-id`).
88    #[arg(long, default_value = "open")]
89    pub assignment_type: AssignmentType,
90
91    /// Direct assignment target. Required when `--assignment-type=direct`.
92    #[arg(long)]
93    pub direct_agent_id: Option<String>,
94
95    /// Poster's on-chain wallet address (0x-prefixed). Matches `TEMPO_WALLET_ADDRESS`
96    /// written by `taskfast init`.
97    #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
98    pub wallet_address: Option<String>,
99
100    /// Keystore reference. Accepts a bare path (`/.../abc.json`) or the
101    /// `file:/path` form `taskfast init` writes to `TEMPO_KEY_SOURCE`.
102    /// Keychain backends will slot in later under the same flag.
103    #[arg(long, env = "TEMPO_KEY_SOURCE")]
104    pub keystore: Option<String>,
105
106    /// Path to a file holding the keystore password (mode-0400 recommended).
107    /// Preferred over `TASKFAST_WALLET_PASSWORD` — files don't leak via
108    /// process args or `/proc/self/environ`.
109    #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
110    pub wallet_password_file: Option<PathBuf>,
111
112    /// Tempo RPC endpoint. Defaults to the canonical proxy URL the
113    /// deployment advertises for the env's network.
114    #[arg(long, env = "TEMPO_RPC_URL")]
115    pub rpc_url: Option<String>,
116
117    /// Acknowledge oversized budgets. Required when the budget exceeds
118    /// `confirm_above_budget` in the config. No-op when the gate is unset
119    /// or when the budget is below it. Fail-closed by design (no TTY
120    /// prompt) so a CI script accident doesn't broadcast a huge approve.
121    #[arg(long)]
122    pub yes: bool,
123}
124
125#[derive(Debug, Clone, Copy, clap::ValueEnum)]
126pub enum AssignmentType {
127    Open,
128    Direct,
129}
130
131impl AssignmentType {
132    fn as_str(self) -> &'static str {
133        match self {
134            Self::Open => "open",
135            Self::Direct => "direct",
136        }
137    }
138}
139
140impl From<AssignmentType> for TaskDraftPrepareRequestAssignmentType {
141    fn from(a: AssignmentType) -> Self {
142        match a {
143            AssignmentType::Open => Self::Open,
144            AssignmentType::Direct => Self::Direct,
145        }
146    }
147}
148
149pub async fn run(ctx: &Ctx, args: Args) -> CmdResult {
150    if args.description.trim().is_empty() {
151        return Err(CmdError::Usage(
152            "--description must not be empty (server requires a non-blank description)".into(),
153        ));
154    }
155    ctx.enforce_budget_gate(args.budget.as_deref(), args.yes, "post a task")?;
156    let wallet_address = args
157        .wallet_address
158        .as_deref()
159        .or(ctx.wallet_address.as_deref())
160        .ok_or_else(|| {
161            CmdError::Usage(
162                "--wallet-address (or TEMPO_WALLET_ADDRESS, or wallet_address in config) required to post a task".into(),
163            )
164        })?;
165    // Validate shape upfront so a typo never makes it to the server.
166    let _: Address = wallet_address.parse().map_err(|e| {
167        CmdError::Usage(format!("--wallet-address is not a valid EVM address: {e}"))
168    })?;
169
170    let direct_agent_id = match (args.assignment_type, args.direct_agent_id.as_deref()) {
171        (AssignmentType::Direct, Some(s)) => Some(
172            Uuid::parse_str(s)
173                .map_err(|e| CmdError::Usage(format!("--direct-agent-id not a UUID: {e}")))?,
174        ),
175        (AssignmentType::Direct, None) => {
176            return Err(CmdError::Usage(
177                "--assignment-type=direct requires --direct-agent-id".into(),
178            ));
179        }
180        (AssignmentType::Open, _) => None,
181    };
182
183    let pickup_deadline = parse_iso_opt(args.pickup_deadline.as_deref(), "--pickup-deadline")?;
184    let execution_deadline =
185        parse_iso_opt(args.execution_deadline.as_deref(), "--execution-deadline")?;
186
187    let poster_wallet: TaskDraftPrepareRequestPosterWalletAddress = wallet_address
188        .parse()
189        .map_err(|e| CmdError::Usage(format!("--wallet-address rejected by schema: {e}")))?;
190
191    let completion_criteria = resolve_criteria(args.criteria_file.as_deref(), &args.criteria)?;
192
193    let prep_body = TaskDraftPrepareRequest {
194        assignment_type: args.assignment_type.into(),
195        budget_max: args.budget.clone(),
196        completion_criteria,
197        description: args.description.clone(),
198        direct_agent_id,
199        execution_deadline,
200        pickup_deadline,
201        poster_wallet_address: poster_wallet,
202        required_capabilities: args.capabilities.clone(),
203        title: args.title.clone(),
204    };
205
206    // Dry-run must perform zero HTTP. Predict the proxy URL locally so the
207    // envelope still reports what the real path would have used.
208    if ctx.dry_run {
209        let network = ctx.environment.network();
210        let rpc_url = if let Some(ref override_url) = args.rpc_url {
211            validate_override_rpc_url(override_url, network, ctx.allow_custom_endpoints)?;
212            override_url.clone()
213        } else {
214            format!(
215                "{}/rpc/{}",
216                ctx.base_url().trim_end_matches('/'),
217                network.as_str()
218            )
219        };
220        return Ok(Envelope::success(
221            ctx.environment,
222            ctx.dry_run,
223            json!({
224                "action": "would_post",
225                "draft_id": serde_json::Value::Null,
226                "title": args.title,
227                "assignment_type": args.assignment_type.as_str(),
228                "budget_max": args.budget,
229                "required_capabilities": args.capabilities,
230                "completion_criteria_count": prep_body.completion_criteria.len(),
231                "rpc_url": rpc_url,
232                "wallet_address": wallet_address,
233            }),
234        ));
235    }
236
237    let client = ctx.client()?;
238
239    // Resolve the RPC URL. Default path: pull it from the deployment's
240    // `GET /config/network` (public). Override path: user supplied
241    // `--rpc-url` / `TEMPO_RPC_URL` and must also pass
242    // `--allow-custom-endpoints`.
243    let (rpc_url, _via_proxy) = resolve_rpc_url(&client, &args, ctx).await?;
244
245    // Phase 1 — prepare. Server returns ERC-20 transfer calldata + draft_id.
246    let prep = match client.inner().prepare_task_draft(&prep_body).await {
247        Ok(r) => r.into_inner(),
248        Err(e) => return Err(map_api_error(e).await.into()),
249    };
250
251    let token_address: Address = prep.token_address.parse().map_err(|e| {
252        CmdError::Server(format!(
253            "server returned invalid token_address `{}`: {e}",
254            prep.token_address
255        ))
256    })?;
257    let calldata = decode_0x_bytes(&prep.payload_to_sign)
258        .map_err(|e| CmdError::Server(format!("server returned invalid payload_to_sign: {e}")))?;
259
260    // Load signer only after prepare succeeds — avoids prompting the user for
261    // a keystore password on a request that never leaves local validation.
262    let keystore_ref = args.keystore.as_deref().map(str::to_string).or_else(|| {
263        ctx.keystore_path
264            .as_deref()
265            .and_then(|p| p.to_str().map(str::to_string))
266    });
267    let signer = super::wallet_args::load_signer(
268        keystore_ref.as_deref(),
269        args.wallet_password_file.as_deref(),
270        "submission fee",
271    )?;
272    // Sanity: the wallet address in the draft must match what we're signing
273    // with. A mismatch means the server recorded a charge on a wallet we
274    // don't control, which would poll forever.
275    let parsed_wallet_address = wallet_address
276        .parse::<Address>()
277        .map_err(|_| CmdError::Usage(format!("invalid wallet address: {}", wallet_address)))?;
278    if signer.address() != parsed_wallet_address {
279        return Err(CmdError::Usage(format!(
280            "keystore address {:#x} does not match --wallet-address {}",
281            signer.address(),
282            wallet_address
283        )));
284    }
285
286    // Pick the http client by URL, not by resolution branch: any URL
287    // landing on `{api_base}/rpc/` is the authenticated proxy and
288    // needs `X-API-Key` (set as a default header on `client.http_client()`).
289    // A `--rpc-url`/`TEMPO_RPC_URL` override that points at the proxy
290    // hit this same path; the prior `via_proxy` flag missed that case
291    // and dropped the header, returning 401 "missing API key".
292    let http = ctx.rpc_http_client(&client, &rpc_url);
293    let rpc = TempoRpcClient::new(http, rpc_url.clone());
294
295    // F1: consult the chain's own `eth_chainId` (not anything the server
296    // claims) and refuse to sign a `transfer` against a token that isn't
297    // on the PathUSD allowlist for that chain. A compromised TaskFast API
298    // returning an attacker `token_address` is the fund-drain vector here.
299    let chain_id = rpc
300        .chain_id()
301        .await
302        .map_err(|e| CmdError::Server(format!("tempo rpc eth_chainId: {e}")))?;
303    if !ctx.allow_custom_endpoints && !is_known_network(chain_id) {
304        return Err(CmdError::Validation {
305            code: "unknown_chain".into(),
306            message: format!(
307                "RPC reports chain_id={chain_id} which is not a known Tempo or \
308                 local-dev network; refusing to sign. Pass --allow-custom-endpoints \
309                 to override."
310            ),
311        });
312    }
313    if !is_allowed_fee_token(chain_id, &prep.token_address) {
314        return Err(CmdError::Validation {
315            code: "fee_token_not_allowed".into(),
316            message: format!(
317                "server returned token_address {} which is not on the PathUSD \
318                 allowlist for chain_id={chain_id}. Refusing to sign — this would \
319                 redirect your fee transfer to an arbitrary ERC-20 contract.",
320                prep.token_address
321            ),
322        });
323    }
324
325    // Audit line — always emitted to stderr so a CI log captures the exact
326    // recipient+token+chain we committed funds to. Not a prompt: CLI stays
327    // non-interactive.
328    eprintln!(
329        "taskfast: signing submission-fee transfer — token={} chain_id={} rpc={}",
330        prep.token_address, chain_id, rpc_url
331    );
332
333    // F9: serialize nonce-consuming sign+broadcast per wallet. `_guard`
334    // holds the exclusive file lock from here until function return,
335    // which scope-covers both eth_getTransactionCount (inside
336    // sign_and_broadcast_erc20_transfer) and eth_sendRawTransaction.
337    // Locked on the keystore path (stripping the optional `file:` prefix
338    // that `taskfast init` writes) so two processes sharing a keystore
339    // can't race, while distinct wallets proceed in parallel.
340    let _guard = if let Some(ref raw) = keystore_ref {
341        let path_str = raw.strip_prefix("file:").unwrap_or(raw);
342        Some(crate::wallet_lock::acquire(std::path::Path::new(path_str))?)
343    } else {
344        None
345    };
346
347    let tx_hash =
348        sign_and_broadcast_erc20_transfer(&rpc, &signer, token_address, Bytes::from(calldata))
349            .await
350            .map_err(|e| CmdError::Server(format!("tempo rpc: {e}")))?;
351    let tx_hash_hex = format!("{tx_hash:#x}");
352
353    // Phase 2 — submit voucher. The field is named `signature` for historical
354    // reasons; semantically it's a voucher (tx hash, in our path).
355    let signature: TaskDraftSubmitRequestSignature = tx_hash_hex
356        .parse()
357        .map_err(|e| CmdError::Server(format!("tx hash rejected by schema pattern: {e}")))?;
358    let submit_body = TaskDraftSubmitRequest { signature };
359    let submitted = match client
360        .inner()
361        .submit_task_draft(&prep.draft_id, &submit_body)
362        .await
363    {
364        Ok(r) => r.into_inner(),
365        Err(e) => return Err(map_api_error(e).await.into()),
366    };
367
368    Ok(Envelope::success(
369        ctx.environment,
370        ctx.dry_run,
371        json!({
372            "task_id": submitted.id,
373            "draft_id": prep.draft_id,
374            "submission_fee_tx_hash": tx_hash_hex,
375            "status": submitted.status,
376            "submission_fee_status": submitted.submission_fee_status,
377        }),
378    ))
379}
380
381/// Resolve the RPC endpoint for a post invocation.
382///
383/// Returns `(url, via_proxy)`:
384///   * `(override, false)` — user supplied `--rpc-url` / `TEMPO_RPC_URL`,
385///     passed the custom-endpoint guard, and will hit a bare upstream RPC.
386///   * `(proxy_url, true)` — default path: the deployment's
387///     `/config/network` entry for the selected network points the CLI
388///     at `{api_base}/rpc/{network}`, which the server proxies to its
389///     own Tempo upstream (Alchemy by default). The caller should carry
390///     the authenticated reqwest::Client through to `TempoRpcClient`.
391async fn resolve_rpc_url(
392    client: &TaskFastClient,
393    args: &Args,
394    ctx: &Ctx,
395) -> Result<(String, bool), CmdError> {
396    let network = ctx.environment.network();
397    if let Some(ref override_url) = args.rpc_url {
398        validate_override_rpc_url(override_url, network, ctx.allow_custom_endpoints)?;
399        return Ok((override_url.clone(), false));
400    }
401    let cfg = client.fetch_network_config().await.map_err(|e| match e {
402        taskfast_client::Error::Auth(_) | taskfast_client::Error::Validation { .. } => {
403            CmdError::Server(format!("fetch network config from {}: {e}", ctx.base_url()))
404        }
405        other => CmdError::from(other),
406    })?;
407    // Runtime invariant — issue #62 (server-side): the env's deployment must
408    // advertise exactly its one network, and nothing else.
409    //
410    // Today's deployments still advertise multiple networks per response;
411    // until #62 lands, a `len != 1` mismatch logs a warn and continues.
412    // Set TASKFAST_STRICT_ENV_NETWORK=1 to fail-closed.
413    // `--allow-custom-endpoints` and `Environment::Local` bypass entirely
414    // (matches `enforce_endpoint_guard`).
415    let name = network.as_str();
416    if !ctx.allow_custom_endpoints
417        && ctx.environment != crate::Environment::Local
418        && cfg.networks.len() != 1
419    {
420        let advertised: Vec<&str> = cfg.networks.keys().map(String::as_str).collect();
421        let strict = std::env::var("TASKFAST_STRICT_ENV_NETWORK")
422            .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
423        if strict {
424            return Err(CmdError::Server(format!(
425                "deployment at {} advertises networks {advertised:?}; env {} requires \
426                 exactly [{name}]. Server-side fix tracked in issue #62. Unset \
427                 TASKFAST_STRICT_ENV_NETWORK or pass --allow-custom-endpoints to bypass.",
428                ctx.base_url(),
429                ctx.environment.as_str(),
430            )));
431        }
432        tracing::warn!(
433            api_base = %ctx.base_url(),
434            env = ctx.environment.as_str(),
435            expected = name,
436            advertised = ?advertised,
437            "deployment advertises additional networks; server-side fix tracked in #62. \
438             Set TASKFAST_STRICT_ENV_NETWORK=1 to fail-closed."
439        );
440    }
441    let entry = cfg.entry(name).map_err(|e| {
442        CmdError::Server(format!(
443            "deployment at {} does not advertise network `{name}`: {e}",
444            ctx.base_url()
445        ))
446    })?;
447    // F2-equivalent guard, minus the static allowlist: the old
448    // WELL_KNOWN_TEMPO_RPCS check trusted exactly two hardcoded URLs. The
449    // replacement says "the proxy must live under the same api_base the
450    // endpoint-guard already approved". Catches (a) a misconfigured
451    // deployment returning an upstream URL instead of its own proxy, and
452    // (b) a compromised backend trying to steer RPC traffic off-host —
453    // minus a full MITM on api_base itself (which has its own F5/F6
454    // defenses).
455    let expected_prefix = format!("{}/rpc/", ctx.base_url().trim_end_matches('/'));
456    if !entry.rpc_url.starts_with(&expected_prefix) {
457        return Err(CmdError::Server(format!(
458            "deployment at {} returned rpc_url {:?} for network `{name}`, \
459             which does not live under `{expected_prefix}…`. Refusing to \
460             route RPC traffic off-host.",
461            ctx.base_url(),
462            entry.rpc_url,
463        )));
464    }
465    Ok((entry.rpc_url.clone(), true))
466}
467
468/// Merge file-sourced and inline `--criterion` payloads into one validated
469/// list of `CompletionCriterionInput`. File entries are prepended so a
470/// shared base file can be augmented with one-off overrides on the command
471/// line. Any shape/parse failure is a `Usage` error — the CLI catches it
472/// before the request ever reaches the server, so the exit-code contract
473/// (Auth=re-credential, Validation=server-rejected payload) stays clean.
474fn resolve_criteria(
475    file: Option<&std::path::Path>,
476    inline: &[String],
477) -> Result<Vec<CompletionCriterionInput>, CmdError> {
478    let mut out = Vec::with_capacity(inline.len());
479    if let Some(path) = file {
480        let raw = std::fs::read_to_string(path).map_err(|e| {
481            CmdError::Usage(format!("read --criteria-file {}: {e}", path.display()))
482        })?;
483        let parsed: Vec<CompletionCriterionInput> = serde_json::from_str(&raw).map_err(|e| {
484            CmdError::Usage(format!(
485                "--criteria-file {} is not a JSON array of CompletionCriterionInput: {e}",
486                path.display()
487            ))
488        })?;
489        out.extend(parsed);
490    }
491    for (i, raw) in inline.iter().enumerate() {
492        let one: CompletionCriterionInput = serde_json::from_str(raw)
493            .map_err(|e| CmdError::Usage(format!("--criterion[{i}] not valid JSON: {e}")))?;
494        out.push(one);
495    }
496    Ok(out)
497}
498
499fn parse_iso_opt(
500    s: Option<&str>,
501    flag: &str,
502) -> Result<Option<chrono::DateTime<chrono::Utc>>, CmdError> {
503    match s {
504        None => Ok(None),
505        Some(raw) => chrono::DateTime::parse_from_rfc3339(raw)
506            .map(|d| Some(d.with_timezone(&chrono::Utc)))
507            .map_err(|e| CmdError::Usage(format!("{flag} not a valid RFC3339 timestamp: {e}"))),
508    }
509}
510
511fn decode_0x_bytes(s: &str) -> Result<Vec<u8>, String> {
512    let stripped = s.strip_prefix("0x").unwrap_or(s);
513    hex::decode(stripped).map_err(|e| e.to_string())
514}
515
516#[cfg(test)]
517mod tests {
518    use super::*;
519    use crate::Network;
520
521    #[test]
522    fn validate_override_rejects_without_opt_in() {
523        let err = validate_override_rpc_url("https://mallory.example", Network::Mainnet, false)
524            .expect_err("override without opt-in must be refused");
525        match err {
526            CmdError::Usage(msg) => {
527                assert!(msg.contains("--allow-custom-endpoints"), "msg: {msg}");
528            }
529            other => panic!("expected Usage, got {other:?}"),
530        }
531    }
532
533    #[test]
534    fn validate_override_accepts_with_opt_in() {
535        validate_override_rpc_url("https://my-node.example", Network::Testnet, true)
536            .expect("opt-in bypasses the guard");
537    }
538
539    #[test]
540    fn validate_override_rejects_plain_http_on_mainnet() {
541        let err = validate_override_rpc_url("http://my-node.example", Network::Mainnet, true)
542            .expect_err("plain-http on mainnet is always refused (except loopback)");
543        assert!(matches!(err, CmdError::Usage(msg) if msg.contains("plain-HTTP")));
544    }
545
546    #[test]
547    fn validate_override_allows_plain_http_loopback_on_mainnet() {
548        validate_override_rpc_url("http://127.0.0.1:8545", Network::Mainnet, true)
549            .expect("loopback bypasses mainnet-HTTPS check");
550        validate_override_rpc_url("http://localhost:8545", Network::Mainnet, true)
551            .expect("loopback bypasses mainnet-HTTPS check");
552    }
553
554    #[test]
555    fn validate_override_allows_plain_http_on_testnet() {
556        validate_override_rpc_url("http://my-testnet.example", Network::Testnet, true)
557            .expect("testnet does not enforce HTTPS");
558    }
559
560    #[test]
561    fn network_name_matches_config_map_keys() {
562        // The lookup key into `GET /config/network`'s `networks` map.
563        // Must stay in sync with what the deployment advertises.
564        assert_eq!(Network::Mainnet.as_str(), "mainnet");
565        assert_eq!(Network::Testnet.as_str(), "testnet");
566    }
567}