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 broadcast via [`crate::tempo_session::TempoSession::send_transaction`].
22
23use std::path::PathBuf;
24
25use alloy_primitives::{Address, Bytes};
26use clap::Parser;
27use serde_json::json;
28
29use super::wallet_args::{decode_0x_bytes, resolve_proxy_rpc_url, sign_and_send_submission_fee};
30use super::{validate_override_rpc_url, CmdError, CmdResult, Ctx};
31use crate::envelope::Envelope;
32
33use taskfast_client::api::types::{
34    CompletionCriterionInput, TaskDraftPrepareRequest, TaskDraftPrepareRequestAssignmentType,
35    TaskDraftPrepareRequestPickupDeadlineHours, TaskDraftSubmitRequest,
36    TaskDraftSubmitRequestSignature,
37};
38use taskfast_client::map_api_error;
39
40#[derive(Debug, Parser)]
41pub struct Args {
42    /// Task title (required).
43    #[arg(long)]
44    pub title: String,
45
46    /// Task description (required, non-empty). Validated client-side so a
47    /// typoed script fails fast instead of paying for a server 422 round-trip.
48    #[arg(long)]
49    pub description: String,
50
51    /// Max budget the poster will pay, as a decimal string ("2.50"). Passed
52    /// through as `budget_max` on the draft.
53    #[arg(long)]
54    pub budget: Option<String>,
55
56    /// Capability tags required from the assignee. Comma-separated.
57    #[arg(long, value_delimiter = ',')]
58    pub capabilities: Vec<String>,
59
60    /// Completion-criterion payout gate as a JSON object. Repeat `--criterion`
61    /// for multiple gates. Shape matches `CompletionCriterionInput`:
62    /// `{"description":"…","check_type":"json_schema|regex|count|http_status|file_exists",`
63    /// `"check_expression":"…","expected_value":"…","target_artifact_pattern":null}`.
64    /// Missing ⇒ no objective gate; server policy decides payout.
65    #[arg(long = "criterion")]
66    pub criteria: Vec<String>,
67
68    /// Path to a JSON file containing an array of `CompletionCriterionInput`
69    /// objects. Merged before any `--criterion` flags (file entries first).
70    /// Use this when you have many gates or want to keep them in version
71    /// control alongside the task.
72    #[arg(long)]
73    pub criteria_file: Option<PathBuf>,
74
75    /// Pickup window in hours: how long the task stays open for bidding
76    /// before closing. Required. The server owns the set of allowed windows
77    /// (`422 pickup_deadline_required` on an invalid choice).
78    #[arg(long)]
79    pub pickup_deadline_hours: i64,
80
81    /// Execution deadline (RFC3339 timestamp).
82    #[arg(long)]
83    pub execution_deadline: Option<String>,
84
85    /// Settlement venue `chain_key` (e.g. `tempo-zone-moderato`) electing the
86    /// settlement rail/chain for this task (ADR 0011 §5). Omit to settle on the
87    /// deployment's default venue (L1). The server validates the key (must
88    /// reference an active venue) and binds it once at creation, immutably.
89    #[arg(long)]
90    pub venue: Option<String>,
91
92    /// Poster's on-chain wallet address (0x-prefixed). Matches `TEMPO_WALLET_ADDRESS`
93    /// written by `taskfast init`.
94    #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
95    pub wallet_address: Option<String>,
96
97    /// Keystore reference. Accepts a bare path (`/.../abc.json`) or the
98    /// `file:/path` form `taskfast init` writes to `TEMPO_KEY_SOURCE`.
99    /// Keychain backends will slot in later under the same flag.
100    #[arg(long, env = "TEMPO_KEY_SOURCE")]
101    pub keystore: Option<String>,
102
103    /// Path to a file holding the keystore password (mode-0400 recommended).
104    /// Preferred over `TASKFAST_WALLET_PASSWORD` — files don't leak via
105    /// process args or `/proc/self/environ`.
106    #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
107    pub wallet_password_file: Option<PathBuf>,
108
109    /// Tempo RPC endpoint. Defaults to the canonical proxy URL the
110    /// deployment advertises for the env's network.
111    #[arg(long, env = "TEMPO_RPC_URL")]
112    pub rpc_url: Option<String>,
113
114    /// Acknowledge oversized budgets. Required when the budget exceeds
115    /// `confirm_above_budget` in the config. No-op when the gate is unset
116    /// or when the budget is below it. Fail-closed by design (no TTY
117    /// prompt) so a CI script accident doesn't broadcast a huge approve.
118    #[arg(long)]
119    pub yes: bool,
120}
121
122/// Convert `--pickup-deadline-hours` to the wire type generated from the
123/// vendored spec. The generated newtype is the only encoding of the allowed
124/// set — the CLI never restates it, so a server policy change flows in via a
125/// spec re-vendor with no code edit here.
126fn pickup_hours_to_wire(
127    hours: i64,
128) -> Result<TaskDraftPrepareRequestPickupDeadlineHours, CmdError> {
129    TaskDraftPrepareRequestPickupDeadlineHours::try_from(hours).map_err(|_| CmdError::Validation {
130        code: "pickup_deadline_invalid".into(),
131        message: format!(
132            "pickup window of {hours}h is not an allowed bidding window per the \
133             API contract; the server owns the valid set (422 pickup_deadline_required)"
134        ),
135    })
136}
137
138pub async fn run(ctx: &Ctx, args: Args) -> CmdResult {
139    // gh#144: validate every local input in ONE pass before any HTTP,
140    // keystore prompt, or signing — the old sequential early-returns cost an
141    // agent one full retry cycle per missing flag / guard conflict.
142    let pre = preflight(ctx, &args)?;
143
144    let prep_body = TaskDraftPrepareRequest {
145        assignment_type: TaskDraftPrepareRequestAssignmentType::default(),
146        budget_max: args.budget.clone(),
147        completion_criteria: pre.completion_criteria,
148        description: args.description.clone(),
149        direct_agent_id: None,
150        execution_deadline: pre.execution_deadline,
151        pickup_deadline_hours: pre.pickup_hours,
152        poster_wallet_address: pre
153            .wallet_address
154            .parse()
155            .map_err(|e| CmdError::Usage(format!("--wallet-address rejected by schema: {e}")))?,
156        required_capabilities: args.capabilities.clone(),
157        settlement_venue: args.venue.clone(),
158        title: args.title.clone(),
159    };
160
161    // Dry-run must perform zero HTTP. Predict the proxy URL locally so the
162    // envelope still reports what the real path would have used.
163    if ctx.dry_run {
164        let rpc_url = match pre.rpc_url_override {
165            Some(override_url) => override_url,
166            None => format!(
167                "{}/rpc/{}",
168                ctx.base_url().trim_end_matches('/'),
169                ctx.environment.network().as_str()
170            ),
171        };
172        return Ok(Envelope::success(
173            ctx.environment,
174            ctx.dry_run,
175            json!({
176                "action": "would_post",
177                "draft_id": serde_json::Value::Null,
178                "title": args.title,
179                "budget_max": args.budget,
180                "settlement_venue": args.venue,
181                "required_capabilities": args.capabilities,
182                "completion_criteria_count": prep_body.completion_criteria.len(),
183                "rpc_url": rpc_url,
184                "wallet_address": pre.wallet_address,
185            }),
186        ));
187    }
188
189    let client = ctx.client()?;
190
191    // Resolve the RPC URL. Default path: pull it from the deployment's
192    // `GET /config/network` (public). Override path: user supplied
193    // `--rpc-url` / `TEMPO_RPC_URL` and must also pass
194    // `--allow-custom-endpoints` (already checked in preflight).
195    let rpc_url = match pre.rpc_url_override {
196        Some(override_url) => override_url,
197        None => resolve_proxy_rpc_url(&client, ctx).await?,
198    };
199
200    // Phase 1 — prepare. Server returns ERC-20 transfer calldata + draft_id.
201    let prep = match client.inner().prepare_task_draft(&prep_body).await {
202        Ok(r) => r.into_inner(),
203        Err(e) => return Err(map_api_error(e).await.into()),
204    };
205
206    let calldata = decode_0x_bytes(&prep.payload_to_sign)
207        .map_err(|e| CmdError::Server(format!("server returned invalid payload_to_sign: {e}")))?;
208
209    // Load signer only after prepare succeeds — avoids prompting the user for
210    // a keystore password on a request that never leaves local validation.
211    let keystore_path = super::wallet_args::resolve_keystore_path(
212        args.keystore.as_deref(),
213        ctx.keystore_path.as_deref(),
214    );
215    let signer = super::wallet_args::load_signer_and_validate(
216        keystore_path.as_deref(),
217        args.wallet_password_file.as_deref(),
218        Some(&pre.wallet_address),
219        "submission fee",
220    )?;
221
222    let tx_hash = sign_and_send_submission_fee(
223        ctx,
224        &client,
225        &rpc_url,
226        keystore_path,
227        signer,
228        &prep.token_address,
229        Bytes::from(calldata),
230    )
231    .await?;
232    let tx_hash_hex = format!("{tx_hash:#x}");
233
234    // Phase 2 — submit voucher. The field is named `signature` for historical
235    // reasons; semantically it's a voucher (tx hash, in our path).
236    let signature: TaskDraftSubmitRequestSignature = tx_hash_hex
237        .parse()
238        .map_err(|e| CmdError::Server(format!("tx hash rejected by schema pattern: {e}")))?;
239    let submit_body = TaskDraftSubmitRequest { signature };
240    let submitted = match client
241        .inner()
242        .submit_task_draft(&prep.draft_id, &submit_body)
243        .await
244    {
245        Ok(r) => r.into_inner(),
246        Err(e) => return Err(map_api_error(e).await.into()),
247    };
248
249    // gh#156: a task created at `blocked_on_submission_fee_debt` looks like a
250    // stalled post unless the envelope says otherwise. The draft-submit
251    // response carries no server `message` (the server's message exists only
252    // on the direct `POST /tasks` create view), so when the task lands
253    // blocked we mirror the server's canonical create message — the envelope
254    // then distinguishes "waiting for the fee tx to confirm" from "post
255    // failed". `submission_fee_status` above carries the machine state.
256    let blocked = submitted.status == "blocked_on_submission_fee_debt";
257    if blocked {
258        // stderr audit line, same contract as the signing line above — a CI
259        // log must show WHY the task is not `open` yet and how to watch it.
260        eprintln!(
261            "taskfast: task {} parked at blocked_on_submission_fee_debt — \
262             submission-fee transfer confirming on-chain; it opens automatically \
263             once confirmed. Poll `taskfast task get {}`.",
264            submitted.id, submitted.id
265        );
266    }
267    let message = blocked.then(|| {
268        "Task created. Submission fee transaction is pending on-chain \
269         confirmation before the task becomes actionable."
270            .to_string()
271    });
272
273    Ok(Envelope::success(
274        ctx.environment,
275        ctx.dry_run,
276        json!({
277            "task_id": submitted.id,
278            "draft_id": prep.draft_id,
279            "submission_fee_tx_hash": tx_hash_hex,
280            "status": submitted.status,
281            "submission_fee_status": submitted.submission_fee_status,
282            "message": message,
283        }),
284    ))
285}
286
287/// Everything [`run`] needs from local validation, parsed once by
288/// [`preflight`] so the runtime path never re-validates (gh#144).
289struct Preflight {
290    wallet_address: String,
291    execution_deadline: Option<jiff::Timestamp>,
292    completion_criteria: Vec<CompletionCriterionInput>,
293    pickup_hours: TaskDraftPrepareRequestPickupDeadlineHours,
294    /// User-supplied `--rpc-url` / `TEMPO_RPC_URL`, already through the
295    /// custom-endpoint guard. `None` = resolve the deployment's proxy URL.
296    rpc_url_override: Option<String>,
297}
298
299/// Bare problem text for the preflight list — `Display` on these variants
300/// carries an `usage:` / `validation [code]:` prefix that reads as noise
301/// inside an enumerated list (the envelope's `error.code` already classifies).
302fn problem_text(e: &CmdError) -> String {
303    match e {
304        CmdError::Usage(m) => m.clone(),
305        CmdError::Validation { message, .. } => message.clone(),
306        other => other.to_string(),
307    }
308}
309
310/// gh#144 one-pass input validation. Every locally-checkable problem with
311/// the invocation — missing/blank required values, malformed addresses and
312/// UUIDs, bad timestamps, unparseable criteria, out-of-contract pickup
313/// windows, endpoint-guard conflicts, the budget gate — is collected and
314/// reported in a single enumerated `Usage` error, so fixing one problem
315/// never reveals exactly one more. Runs before any HTTP, keystore prompt,
316/// or signing, and short-circuits `--dry-run` the same way.
317///
318/// Error message texts are unchanged from the former sequential checks —
319/// orchestrators scraping them see the same strings, just together.
320fn preflight(ctx: &Ctx, args: &Args) -> Result<Preflight, CmdError> {
321    let mut problems: Vec<String> = Vec::new();
322    // Each check stores one validated field as `Option`; `None` marks
323    // "check failed, problem already recorded" so every later check still
324    // runs and reports too.
325
326    if args.description.trim().is_empty() {
327        problems.push(
328            "--description must not be empty (server requires a non-blank description)".into(),
329        );
330    }
331
332    if let Err(e) = ctx.enforce_budget_gate(args.budget.as_deref(), args.yes, "post a task") {
333        problems.push(problem_text(&e));
334    }
335
336    let wallet_address = match args
337        .wallet_address
338        .as_deref()
339        .or(ctx.wallet_address.as_deref())
340    {
341        Some(w) => match w.parse::<Address>() {
342            Ok(_) => Some(w.to_string()),
343            Err(e) => {
344                problems.push(format!("--wallet-address is not a valid EVM address: {e}"));
345                None
346            }
347        },
348        None => {
349            problems.push(
350                "--wallet-address (or TEMPO_WALLET_ADDRESS, or wallet_address in config) required to post a task".into(),
351            );
352            None
353        }
354    };
355
356    let execution_deadline =
357        match parse_iso_opt(args.execution_deadline.as_deref(), "--execution-deadline") {
358            Ok(v) => Some(v),
359            Err(e) => {
360                problems.push(problem_text(&e));
361                None
362            }
363        };
364
365    let completion_criteria = match resolve_criteria(args.criteria_file.as_deref(), &args.criteria)
366    {
367        Ok(v) => Some(v),
368        Err(e) => {
369            problems.push(problem_text(&e));
370            None
371        }
372    };
373
374    let pickup_hours = match pickup_hours_to_wire(args.pickup_deadline_hours) {
375        Ok(w) => Some(w),
376        Err(e) => {
377            problems.push(problem_text(&e));
378            None
379        }
380    };
381
382    let rpc_url_override = match args.rpc_url.as_deref() {
383        Some(u) => match validate_override_rpc_url(
384            u,
385            ctx.environment.network(),
386            ctx.allow_custom_endpoints,
387        ) {
388            Ok(u) => Some(Some(u.to_string())),
389            Err(e) => {
390                problems.push(problem_text(&e));
391                None
392            }
393        },
394        None => Some(None),
395    };
396
397    if !problems.is_empty() {
398        let n = problems.len();
399        let list = problems
400            .iter()
401            .enumerate()
402            .map(|(i, p)| format!("  {}. {p}", i + 1))
403            .collect::<Vec<_>>()
404            .join("\n");
405        return Err(CmdError::Usage(format!(
406            "post preflight found {n} problem{}:\n{list}",
407            if n == 1 { "" } else { "s" }
408        )));
409    }
410
411    Ok(Preflight {
412        wallet_address: wallet_address.expect("no problems ⇒ wallet present"),
413        execution_deadline: execution_deadline.expect("no problems ⇒ deadline resolved"),
414        completion_criteria: completion_criteria.expect("no problems ⇒ criteria resolved"),
415        pickup_hours: pickup_hours.expect("no problems ⇒ pickup hours valid"),
416        rpc_url_override: rpc_url_override.expect("no problems ⇒ rpc override resolved"),
417    })
418}
419
420/// Merge file-sourced and inline `--criterion` payloads into one validated
421/// list of `CompletionCriterionInput`. File entries are prepended so a
422/// shared base file can be augmented with one-off overrides on the command
423/// line. Any shape/parse failure is a `Usage` error — the CLI catches it
424/// before the request ever reaches the server, so the exit-code contract
425/// (Auth=re-credential, Validation=server-rejected payload) stays clean.
426fn resolve_criteria(
427    file: Option<&std::path::Path>,
428    inline: &[String],
429) -> Result<Vec<CompletionCriterionInput>, CmdError> {
430    let mut out = Vec::with_capacity(inline.len());
431    if let Some(path) = file {
432        let raw = std::fs::read_to_string(path).map_err(|e| {
433            CmdError::Usage(format!("read --criteria-file {}: {e}", path.display()))
434        })?;
435        let parsed: Vec<CompletionCriterionInput> = serde_json::from_str(&raw).map_err(|e| {
436            CmdError::Usage(format!(
437                "--criteria-file {} is not a JSON array of CompletionCriterionInput: {e}",
438                path.display()
439            ))
440        })?;
441        out.extend(parsed);
442    }
443    for (i, raw) in inline.iter().enumerate() {
444        let one: CompletionCriterionInput = serde_json::from_str(raw)
445            .map_err(|e| CmdError::Usage(format!("--criterion[{i}] not valid JSON: {e}")))?;
446        out.push(one);
447    }
448    Ok(out)
449}
450
451fn parse_iso_opt(s: Option<&str>, flag: &str) -> Result<Option<jiff::Timestamp>, CmdError> {
452    match s {
453        None => Ok(None),
454        Some(raw) => raw
455            .parse::<jiff::Timestamp>()
456            .map(Some)
457            .map_err(|e| CmdError::Usage(format!("{flag} not a valid RFC3339 timestamp: {e}"))),
458    }
459}
460
461#[cfg(test)]
462mod tests {
463    use super::*;
464    use crate::Network;
465
466    #[test]
467    fn validate_override_rejects_without_opt_in() {
468        let err = validate_override_rpc_url("https://mallory.example", Network::Mainnet, false)
469            .expect_err("override without opt-in must be refused");
470        match err {
471            CmdError::Usage(msg) => {
472                assert!(msg.contains("--allow-custom-endpoints"), "msg: {msg}");
473            }
474            other => panic!("expected Usage, got {other:?}"),
475        }
476    }
477
478    #[test]
479    fn validate_override_accepts_with_opt_in() {
480        validate_override_rpc_url("https://my-node.example", Network::Testnet, true)
481            .expect("opt-in bypasses the guard");
482    }
483
484    #[test]
485    fn validate_override_rejects_plain_http_on_mainnet() {
486        let err = validate_override_rpc_url("http://my-node.example", Network::Mainnet, true)
487            .expect_err("plain-http on mainnet is always refused (except loopback)");
488        assert!(matches!(err, CmdError::Usage(msg) if msg.contains("plain-HTTP")));
489    }
490
491    #[test]
492    fn validate_override_allows_plain_http_loopback_on_mainnet() {
493        validate_override_rpc_url("http://127.0.0.1:8545", Network::Mainnet, true)
494            .expect("loopback bypasses mainnet-HTTPS check");
495        validate_override_rpc_url("http://localhost:8545", Network::Mainnet, true)
496            .expect("loopback bypasses mainnet-HTTPS check");
497    }
498
499    #[test]
500    fn validate_override_allows_plain_http_on_testnet() {
501        validate_override_rpc_url("http://my-testnet.example", Network::Testnet, true)
502            .expect("testnet does not enforce HTTPS");
503    }
504
505    #[test]
506    fn parse_iso_accepts_rfc3339_deadline() {
507        let got = parse_iso_opt(Some("2026-03-01T12:00:00Z"), "--execution-deadline").unwrap();
508        assert_eq!(
509            got.map(|d| d.to_string()),
510            Some("2026-03-01T12:00:00Z".into())
511        );
512    }
513
514    #[test]
515    fn parse_iso_rejects_non_rfc3339_and_passes_none_through() {
516        assert!(parse_iso_opt(Some("tomorrow"), "--execution-deadline").is_err());
517        assert!(parse_iso_opt(None, "--execution-deadline")
518            .unwrap()
519            .is_none());
520    }
521
522    #[test]
523    fn pickup_hours_conversion_follows_api_contract() {
524        // The allowed set lives only in the vendored spec (via the generated
525        // newtype) — an out-of-set value maps to a validation error without
526        // the CLI restating the list anywhere.
527        let err = pickup_hours_to_wire(3).expect_err("3 is outside the contract set");
528        assert!(matches!(err, CmdError::Validation { .. }));
529        // A contract-valid choice converts to the exact wire integer.
530        let wire = pickup_hours_to_wire(24).expect("24 is contract-valid");
531        assert_eq!(i64::from(wire), 24);
532    }
533
534    #[test]
535    fn network_name_matches_config_map_keys() {
536        // The lookup key into `GET /config/network`'s `networks` map.
537        // Must stay in sync with what the deployment advertises.
538        assert_eq!(Network::Mainnet.as_str(), "mainnet");
539        assert_eq!(Network::Testnet.as_str(), "testnet");
540    }
541}