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