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        execution_deadline: pre.execution_deadline,
150        pickup_deadline_hours: pre.pickup_hours,
151        poster_wallet_address: pre
152            .wallet_address
153            .parse()
154            .map_err(|e| CmdError::Usage(format!("--wallet-address rejected by schema: {e}")))?,
155        required_capabilities: args.capabilities.clone(),
156        settlement_venue: args.venue.clone(),
157        title: args.title.clone(),
158    };
159
160    // Dry-run must perform zero HTTP. Predict the proxy URL locally so the
161    // envelope still reports what the real path would have used.
162    if ctx.dry_run {
163        let rpc_url = match pre.rpc_url_override {
164            Some(override_url) => override_url,
165            None => format!(
166                "{}/rpc/{}",
167                ctx.base_url().trim_end_matches('/'),
168                ctx.environment.network().as_str()
169            ),
170        };
171        return Ok(Envelope::success(
172            ctx.environment,
173            ctx.dry_run,
174            json!({
175                "action": "would_post",
176                "draft_id": serde_json::Value::Null,
177                "title": args.title,
178                "budget_max": args.budget,
179                "settlement_venue": args.venue,
180                "required_capabilities": args.capabilities,
181                "completion_criteria_count": prep_body.completion_criteria.len(),
182                "rpc_url": rpc_url,
183                "wallet_address": pre.wallet_address,
184            }),
185        ));
186    }
187
188    let client = ctx.client()?;
189
190    // Resolve the RPC URL. Default path: pull it from the deployment's
191    // `GET /config/network` (public). Override path: user supplied
192    // `--rpc-url` / `TEMPO_RPC_URL` and must also pass
193    // `--allow-custom-endpoints` (already checked in preflight).
194    let rpc_url = match pre.rpc_url_override {
195        Some(override_url) => override_url,
196        None => resolve_proxy_rpc_url(&client, ctx).await?,
197    };
198
199    // Phase 1 — prepare. Server returns ERC-20 transfer calldata + draft_id.
200    let prep = match client.inner().prepare_task_draft(&prep_body).await {
201        Ok(r) => r.into_inner(),
202        Err(e) => return Err(map_api_error(e).await.into()),
203    };
204
205    let calldata = decode_0x_bytes(&prep.payload_to_sign)
206        .map_err(|e| CmdError::Server(format!("server returned invalid payload_to_sign: {e}")))?;
207
208    // Load signer only after prepare succeeds — avoids prompting the user for
209    // a keystore password on a request that never leaves local validation.
210    let keystore_path = super::wallet_args::resolve_keystore_path(
211        args.keystore.as_deref(),
212        ctx.keystore_path.as_deref(),
213    );
214    let signer = super::wallet_args::load_signer_and_validate(
215        keystore_path.as_deref(),
216        args.wallet_password_file.as_deref(),
217        Some(&pre.wallet_address),
218        "submission fee",
219    )?;
220
221    let tx_hash = sign_and_send_submission_fee(
222        ctx,
223        &client,
224        &rpc_url,
225        keystore_path,
226        signer,
227        &prep.token_address,
228        Bytes::from(calldata),
229    )
230    .await?;
231    let tx_hash_hex = format!("{tx_hash:#x}");
232
233    // Phase 2 — submit voucher. The field is named `signature` for historical
234    // reasons; semantically it's a voucher (tx hash, in our path).
235    let signature: TaskDraftSubmitRequestSignature = tx_hash_hex
236        .parse()
237        .map_err(|e| CmdError::Server(format!("tx hash rejected by schema pattern: {e}")))?;
238    let submit_body = TaskDraftSubmitRequest { signature };
239    let submitted = match client
240        .inner()
241        .submit_task_draft(&prep.draft_id, &submit_body)
242        .await
243    {
244        Ok(r) => r.into_inner(),
245        Err(e) => return Err(map_api_error(e).await.into()),
246    };
247
248    // gh#156: a task created at `blocked_on_submission_fee_debt` looks like a
249    // stalled post unless the envelope says otherwise. The draft-submit
250    // response carries no server `message` (the server's message exists only
251    // on the direct `POST /tasks` create view), so when the task lands
252    // blocked we mirror the server's canonical create message — the envelope
253    // then distinguishes "waiting for the fee tx to confirm" from "post
254    // failed". `submission_fee_status` above carries the machine state.
255    let blocked = submitted.status == "blocked_on_submission_fee_debt";
256    if blocked {
257        // stderr audit line, same contract as the signing line above — a CI
258        // log must show WHY the task is not `open` yet and how to watch it.
259        eprintln!(
260            "taskfast: task {} parked at blocked_on_submission_fee_debt — \
261             submission-fee transfer confirming on-chain; it opens automatically \
262             once confirmed. Poll `taskfast task get {}`.",
263            submitted.id, submitted.id
264        );
265    }
266    let message = blocked.then(|| {
267        "Task created. Submission fee transaction is pending on-chain \
268         confirmation before the task becomes actionable."
269            .to_string()
270    });
271
272    Ok(Envelope::success(
273        ctx.environment,
274        ctx.dry_run,
275        json!({
276            "task_id": submitted.id,
277            "draft_id": prep.draft_id,
278            "submission_fee_tx_hash": tx_hash_hex,
279            "status": submitted.status,
280            "submission_fee_status": submitted.submission_fee_status,
281            "message": message,
282        }),
283    ))
284}
285
286/// Everything [`run`] needs from local validation, parsed once by
287/// [`preflight`] so the runtime path never re-validates (gh#144).
288struct Preflight {
289    wallet_address: String,
290    execution_deadline: Option<jiff::Timestamp>,
291    completion_criteria: Vec<CompletionCriterionInput>,
292    pickup_hours: TaskDraftPrepareRequestPickupDeadlineHours,
293    /// User-supplied `--rpc-url` / `TEMPO_RPC_URL`, already through the
294    /// custom-endpoint guard. `None` = resolve the deployment's proxy URL.
295    rpc_url_override: Option<String>,
296}
297
298/// Bare problem text for the preflight list — `Display` on these variants
299/// carries an `usage:` / `validation [code]:` prefix that reads as noise
300/// inside an enumerated list (the envelope's `error.code` already classifies).
301fn problem_text(e: &CmdError) -> String {
302    match e {
303        CmdError::Usage(m) => m.clone(),
304        CmdError::Validation { message, .. } => message.clone(),
305        other => other.to_string(),
306    }
307}
308
309/// gh#144 one-pass input validation. Every locally-checkable problem with
310/// the invocation — missing/blank required values, malformed addresses and
311/// UUIDs, bad timestamps, unparseable criteria, out-of-contract pickup
312/// windows, endpoint-guard conflicts, the budget gate — is collected and
313/// reported in a single enumerated `Usage` error, so fixing one problem
314/// never reveals exactly one more. Runs before any HTTP, keystore prompt,
315/// or signing, and short-circuits `--dry-run` the same way.
316///
317/// Error message texts are unchanged from the former sequential checks —
318/// orchestrators scraping them see the same strings, just together.
319fn preflight(ctx: &Ctx, args: &Args) -> Result<Preflight, CmdError> {
320    let mut problems: Vec<String> = Vec::new();
321    // Each check stores one validated field as `Option`; `None` marks
322    // "check failed, problem already recorded" so every later check still
323    // runs and reports too.
324
325    if args.description.trim().is_empty() {
326        problems.push(
327            "--description must not be empty (server requires a non-blank description)".into(),
328        );
329    }
330
331    if let Err(e) = ctx.enforce_budget_gate(args.budget.as_deref(), args.yes, "post a task") {
332        problems.push(problem_text(&e));
333    }
334
335    let wallet_address = match args
336        .wallet_address
337        .as_deref()
338        .or(ctx.wallet_address.as_deref())
339    {
340        Some(w) => match w.parse::<Address>() {
341            Ok(_) => Some(w.to_string()),
342            Err(e) => {
343                problems.push(format!("--wallet-address is not a valid EVM address: {e}"));
344                None
345            }
346        },
347        None => {
348            problems.push(
349                "--wallet-address (or TEMPO_WALLET_ADDRESS, or wallet_address in config) required to post a task".into(),
350            );
351            None
352        }
353    };
354
355    let execution_deadline =
356        match parse_iso_opt(args.execution_deadline.as_deref(), "--execution-deadline") {
357            Ok(v) => Some(v),
358            Err(e) => {
359                problems.push(problem_text(&e));
360                None
361            }
362        };
363
364    let completion_criteria = match resolve_criteria(args.criteria_file.as_deref(), &args.criteria)
365    {
366        Ok(v) => Some(v),
367        Err(e) => {
368            problems.push(problem_text(&e));
369            None
370        }
371    };
372
373    let pickup_hours = match pickup_hours_to_wire(args.pickup_deadline_hours) {
374        Ok(w) => Some(w),
375        Err(e) => {
376            problems.push(problem_text(&e));
377            None
378        }
379    };
380
381    let rpc_url_override = match args.rpc_url.as_deref() {
382        Some(u) => match validate_override_rpc_url(
383            u,
384            ctx.environment.network(),
385            ctx.allow_custom_endpoints,
386        ) {
387            Ok(u) => Some(Some(u.to_string())),
388            Err(e) => {
389                problems.push(problem_text(&e));
390                None
391            }
392        },
393        None => Some(None),
394    };
395
396    if !problems.is_empty() {
397        let n = problems.len();
398        let list = problems
399            .iter()
400            .enumerate()
401            .map(|(i, p)| format!("  {}. {p}", i + 1))
402            .collect::<Vec<_>>()
403            .join("\n");
404        return Err(CmdError::Usage(format!(
405            "post preflight found {n} problem{}:\n{list}",
406            if n == 1 { "" } else { "s" }
407        )));
408    }
409
410    Ok(Preflight {
411        wallet_address: wallet_address.expect("no problems ⇒ wallet present"),
412        execution_deadline: execution_deadline.expect("no problems ⇒ deadline resolved"),
413        completion_criteria: completion_criteria.expect("no problems ⇒ criteria resolved"),
414        pickup_hours: pickup_hours.expect("no problems ⇒ pickup hours valid"),
415        rpc_url_override: rpc_url_override.expect("no problems ⇒ rpc override resolved"),
416    })
417}
418
419/// Merge file-sourced and inline `--criterion` payloads into one validated
420/// list of `CompletionCriterionInput`. File entries are prepended so a
421/// shared base file can be augmented with one-off overrides on the command
422/// line. Any shape/parse failure is a `Usage` error — the CLI catches it
423/// before the request ever reaches the server, so the exit-code contract
424/// (Auth=re-credential, Validation=server-rejected payload) stays clean.
425fn resolve_criteria(
426    file: Option<&std::path::Path>,
427    inline: &[String],
428) -> Result<Vec<CompletionCriterionInput>, CmdError> {
429    let mut out = Vec::with_capacity(inline.len());
430    if let Some(path) = file {
431        let raw = std::fs::read_to_string(path).map_err(|e| {
432            CmdError::Usage(format!("read --criteria-file {}: {e}", path.display()))
433        })?;
434        let parsed: Vec<CompletionCriterionInput> = serde_json::from_str(&raw).map_err(|e| {
435            CmdError::Usage(format!(
436                "--criteria-file {} is not a JSON array of CompletionCriterionInput: {e}",
437                path.display()
438            ))
439        })?;
440        out.extend(parsed);
441    }
442    for (i, raw) in inline.iter().enumerate() {
443        let one: CompletionCriterionInput = serde_json::from_str(raw)
444            .map_err(|e| CmdError::Usage(format!("--criterion[{i}] not valid JSON: {e}")))?;
445        out.push(one);
446    }
447    Ok(out)
448}
449
450fn parse_iso_opt(s: Option<&str>, flag: &str) -> Result<Option<jiff::Timestamp>, CmdError> {
451    match s {
452        None => Ok(None),
453        Some(raw) => raw
454            .parse::<jiff::Timestamp>()
455            .map(Some)
456            .map_err(|e| CmdError::Usage(format!("{flag} not a valid RFC3339 timestamp: {e}"))),
457    }
458}
459
460#[cfg(test)]
461mod tests {
462    use super::*;
463    use crate::Network;
464
465    #[test]
466    fn validate_override_rejects_without_opt_in() {
467        let err = validate_override_rpc_url("https://mallory.example", Network::Mainnet, false)
468            .expect_err("override without opt-in must be refused");
469        match err {
470            CmdError::Usage(msg) => {
471                assert!(msg.contains("--allow-custom-endpoints"), "msg: {msg}");
472            }
473            other => panic!("expected Usage, got {other:?}"),
474        }
475    }
476
477    #[test]
478    fn validate_override_accepts_with_opt_in() {
479        validate_override_rpc_url("https://my-node.example", Network::Testnet, true)
480            .expect("opt-in bypasses the guard");
481    }
482
483    #[test]
484    fn validate_override_rejects_plain_http_on_mainnet() {
485        let err = validate_override_rpc_url("http://my-node.example", Network::Mainnet, true)
486            .expect_err("plain-http on mainnet is always refused (except loopback)");
487        assert!(matches!(err, CmdError::Usage(msg) if msg.contains("plain-HTTP")));
488    }
489
490    #[test]
491    fn validate_override_allows_plain_http_loopback_on_mainnet() {
492        validate_override_rpc_url("http://127.0.0.1:8545", Network::Mainnet, true)
493            .expect("loopback bypasses mainnet-HTTPS check");
494        validate_override_rpc_url("http://localhost:8545", Network::Mainnet, true)
495            .expect("loopback bypasses mainnet-HTTPS check");
496    }
497
498    #[test]
499    fn validate_override_allows_plain_http_on_testnet() {
500        validate_override_rpc_url("http://my-testnet.example", Network::Testnet, true)
501            .expect("testnet does not enforce HTTPS");
502    }
503
504    #[test]
505    fn parse_iso_accepts_rfc3339_deadline() {
506        let got = parse_iso_opt(Some("2026-03-01T12:00:00Z"), "--execution-deadline").unwrap();
507        assert_eq!(
508            got.map(|d| d.to_string()),
509            Some("2026-03-01T12:00:00Z".into())
510        );
511    }
512
513    #[test]
514    fn parse_iso_rejects_non_rfc3339_and_passes_none_through() {
515        assert!(parse_iso_opt(Some("tomorrow"), "--execution-deadline").is_err());
516        assert!(parse_iso_opt(None, "--execution-deadline")
517            .unwrap()
518            .is_none());
519    }
520
521    #[test]
522    fn pickup_hours_conversion_follows_api_contract() {
523        // The allowed set lives only in the vendored spec (via the generated
524        // newtype) — an out-of-set value maps to a validation error without
525        // the CLI restating the list anywhere.
526        let err = pickup_hours_to_wire(3).expect_err("3 is outside the contract set");
527        assert!(matches!(err, CmdError::Validation { .. }));
528        // A contract-valid choice converts to the exact wire integer.
529        let wire = pickup_hours_to_wire(24).expect("24 is contract-valid");
530        assert_eq!(i64::from(wire), 24);
531    }
532
533    #[test]
534    fn network_name_matches_config_map_keys() {
535        // The lookup key into `GET /config/network`'s `networks` map.
536        // Must stay in sync with what the deployment advertises.
537        assert_eq!(Network::Mainnet.as_str(), "mainnet");
538        assert_eq!(Network::Testnet.as_str(), "testnet");
539    }
540}