Skip to main content

taskfast_cli/cmd/
artifact.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast artifact` — list / get / upload / delete artifacts on a task,
3//! plus non-custodial CID submission (`cid` / `cid-status`).
4//!
5//! Upload is also available via `taskfast task submit --artifact` (the
6//! workflow verb), but a standalone verb is needed for:
7//!   * Out-of-band uploads during dispute remedy.
8//!   * Direct file-management workflows (curator attaching reference assets).
9//!   * Deletion of a mistakenly uploaded artifact.
10//!
11//! The delete endpoint returns 204 (no body); we surface an empty success
12//! envelope with the task/artifact IDs echoed for orchestrator ergonomics.
13//!
14//! `cid` records an externally-pinned CIDv1 as the delivery artifact —
15//! TaskFast never transits the bytes. `cid-status` is the buyer-side verdict
16//! (`witnessed` / `unverifiable`); only the task's poster may write it.
17
18use std::path::PathBuf;
19
20use clap::{Parser, Subcommand, ValueEnum};
21use serde_json::json;
22use uuid::Uuid;
23
24use super::{CmdError, CmdResult, Ctx};
25use crate::envelope::Envelope;
26
27use taskfast_client::api::types::{
28    SubmitArtifactCidBody, UpdateArtifactCidStatusBody, UpdateArtifactCidStatusBodyCidStatus,
29};
30use taskfast_client::map_api_error;
31
32#[derive(Debug, Subcommand)]
33pub enum Command {
34    /// List artifacts attached to a task.
35    List(ListArgs),
36    /// Get a single artifact's metadata by ID.
37    Get(GetArgs),
38    /// Upload an artifact file. Content type is inferred from extension.
39    Upload(UploadArgs),
40    /// Delete an artifact by ID.
41    Delete(GetArgs),
42    /// Register an externally-pinned CIDv1 as the delivery artifact.
43    Cid(CidArgs),
44    /// Set a CID artifact's buyer-verifier verdict (poster only).
45    CidStatus(CidStatusArgs),
46}
47
48#[derive(Debug, Parser)]
49pub struct ListArgs {
50    pub task_id: String,
51
52    #[arg(long)]
53    pub cursor: Option<String>,
54
55    #[arg(long)]
56    pub limit: Option<i64>,
57}
58
59#[derive(Debug, Parser)]
60pub struct GetArgs {
61    pub task_id: String,
62
63    pub artifact_id: String,
64}
65
66#[derive(Debug, Parser)]
67pub struct UploadArgs {
68    pub task_id: String,
69
70    /// Path to the file to upload.
71    pub file: PathBuf,
72}
73
74#[derive(Debug, Parser)]
75pub struct CidArgs {
76    pub task_id: String,
77
78    /// CIDv1 base32 lowercase using sha2-256 (`bafy…` / `bafk…`). The server
79    /// rejects CIDv0 (`Qm…`), non-sha256 multihashes, and non-canonical forms.
80    pub output_cid: String,
81}
82
83/// CLI mirror of the generated [`UpdateArtifactCidStatusBodyCidStatus`] enum.
84/// Defined locally so clap's `ValueEnum` validates the verdict at parse time
85/// (with the allowed values in `--help`) before any network call.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
87pub enum CidStatusArg {
88    /// Default verdict written by the operator's submission.
89    Witnessed,
90    /// Buyer-verifier verdict after a failed off-system fetch.
91    Unverifiable,
92}
93
94impl From<CidStatusArg> for UpdateArtifactCidStatusBodyCidStatus {
95    fn from(v: CidStatusArg) -> Self {
96        match v {
97            CidStatusArg::Witnessed => Self::Witnessed,
98            CidStatusArg::Unverifiable => Self::Unverifiable,
99        }
100    }
101}
102
103#[derive(Debug, Parser)]
104pub struct CidStatusArgs {
105    pub task_id: String,
106
107    pub artifact_id: String,
108
109    /// Verdict to persist.
110    pub status: CidStatusArg,
111}
112
113pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
114    match cmd {
115        Command::List(a) => list(ctx, a).await,
116        Command::Get(a) => get(ctx, a).await,
117        Command::Upload(a) => upload(ctx, a).await,
118        Command::Delete(a) => delete(ctx, a).await,
119        Command::Cid(a) => submit_cid(ctx, a).await,
120        Command::CidStatus(a) => update_cid_status(ctx, a).await,
121    }
122}
123
124async fn list(ctx: &Ctx, args: ListArgs) -> CmdResult {
125    let task_id = parse_uuid(&args.task_id, "task id")?;
126    let client = ctx.client()?;
127    let resp = match client
128        .inner()
129        .list_artifacts(
130            &task_id,
131            args.cursor.as_deref(),
132            args.limit.and_then(taskfast_client::page_limit),
133        )
134        .await
135    {
136        Ok(v) => v.into_inner(),
137        Err(e) => return Err(map_api_error(e).await.into()),
138    };
139    Ok(Envelope::success(
140        ctx.environment,
141        ctx.dry_run,
142        json!({
143            "task_id": task_id.to_string(),
144            "artifacts": resp.data,
145            "meta": resp.meta,
146        }),
147    ))
148}
149
150async fn get(ctx: &Ctx, args: GetArgs) -> CmdResult {
151    let task_id = parse_uuid(&args.task_id, "task id")?;
152    let artifact_id = parse_uuid(&args.artifact_id, "artifact id")?;
153    let client = ctx.client()?;
154    let resp = match client.inner().get_artifact(&task_id, &artifact_id).await {
155        Ok(v) => v.into_inner(),
156        Err(e) => return Err(map_api_error(e).await.into()),
157    };
158    Ok(Envelope::success(
159        ctx.environment,
160        ctx.dry_run,
161        json!({ "artifact": resp }),
162    ))
163}
164
165async fn upload(ctx: &Ctx, args: UploadArgs) -> CmdResult {
166    let task_id = parse_uuid(&args.task_id, "task id")?;
167    if !args.file.exists() {
168        return Err(CmdError::Usage(format!(
169            "artifact file not found: {}",
170            args.file.display()
171        )));
172    }
173    let filename = args
174        .file
175        .file_name()
176        .and_then(|s| s.to_str())
177        .ok_or_else(|| CmdError::Usage(format!("no filename in {}", args.file.display())))?
178        .to_string();
179    let ext = args
180        .file
181        .extension()
182        .and_then(|s| s.to_str())
183        .map(|s| s.to_ascii_lowercase())
184        .unwrap_or_default();
185    let content_type = super::task::content_type_for_ext(&ext).to_string();
186
187    if ctx.dry_run {
188        return Ok(Envelope::success(
189            ctx.environment,
190            ctx.dry_run,
191            json!({
192                "action": "would_upload_artifact",
193                "task_id": task_id.to_string(),
194                "filename": filename,
195                "content_type": content_type,
196                "path": args.file.display().to_string(),
197            }),
198        ));
199    }
200
201    let client = ctx.client()?;
202    let bytes = std::fs::read(&args.file)
203        .map_err(|e| CmdError::Usage(format!("read {}: {e}", args.file.display())))?;
204    let artifact = client
205        .upload_artifact(&task_id, filename, content_type, bytes)
206        .await
207        .map_err(CmdError::from)?;
208    Ok(Envelope::success(
209        ctx.environment,
210        ctx.dry_run,
211        json!({
212            "task_id": task_id.to_string(),
213            "artifact": {
214                "id": artifact.id,
215                "filename": artifact.filename,
216                "content_type": artifact.content_type,
217                "size_bytes": artifact.size_bytes,
218            },
219        }),
220    ))
221}
222
223async fn delete(ctx: &Ctx, args: GetArgs) -> CmdResult {
224    let task_id = parse_uuid(&args.task_id, "task id")?;
225    let artifact_id = parse_uuid(&args.artifact_id, "artifact id")?;
226    if ctx.dry_run {
227        return Ok(Envelope::success(
228            ctx.environment,
229            ctx.dry_run,
230            json!({
231                "action": "would_delete_artifact",
232                "task_id": task_id.to_string(),
233                "artifact_id": artifact_id.to_string(),
234            }),
235        ));
236    }
237    let client = ctx.client()?;
238    match client.inner().delete_artifact(&task_id, &artifact_id).await {
239        Ok(_) => {}
240        Err(e) => return Err(map_api_error(e).await.into()),
241    }
242    Ok(Envelope::success(
243        ctx.environment,
244        ctx.dry_run,
245        json!({
246            "task_id": task_id.to_string(),
247            "artifact_id": artifact_id.to_string(),
248            "deleted": true,
249        }),
250    ))
251}
252
253async fn submit_cid(ctx: &Ctx, args: CidArgs) -> CmdResult {
254    let task_id = parse_uuid(&args.task_id, "task id")?;
255    // Reject an empty CID pre-HTTP so orchestrators see a never-retry Usage
256    // error rather than a server-side 422. The server enforces the full
257    // CIDv1/sha2-256 subset; we only guard the trivial empty case here.
258    let output_cid = args.output_cid.trim();
259    if output_cid.is_empty() {
260        return Err(CmdError::Usage("output_cid must not be empty".into()));
261    }
262    if ctx.dry_run {
263        return Ok(Envelope::success(
264            ctx.environment,
265            ctx.dry_run,
266            json!({
267                "action": "would_submit_cid",
268                "task_id": task_id.to_string(),
269                "output_cid": output_cid,
270            }),
271        ));
272    }
273    let client = ctx.client()?;
274    let body = SubmitArtifactCidBody {
275        output_cid: output_cid.to_string(),
276    };
277    let resp = match client.inner().submit_artifact_cid(&task_id, &body).await {
278        Ok(v) => v.into_inner(),
279        Err(e) => return Err(map_api_error(e).await.into()),
280    };
281    Ok(Envelope::success(
282        ctx.environment,
283        ctx.dry_run,
284        json!({
285            "task_id": task_id.to_string(),
286            "artifact": resp,
287        }),
288    ))
289}
290
291async fn update_cid_status(ctx: &Ctx, args: CidStatusArgs) -> CmdResult {
292    let task_id = parse_uuid(&args.task_id, "task id")?;
293    let artifact_id = parse_uuid(&args.artifact_id, "artifact id")?;
294    let cid_status: UpdateArtifactCidStatusBodyCidStatus = args.status.into();
295    if ctx.dry_run {
296        return Ok(Envelope::success(
297            ctx.environment,
298            ctx.dry_run,
299            json!({
300                "action": "would_update_cid_status",
301                "task_id": task_id.to_string(),
302                "artifact_id": artifact_id.to_string(),
303                "cid_status": cid_status.to_string(),
304            }),
305        ));
306    }
307    let client = ctx.client()?;
308    let body = UpdateArtifactCidStatusBody { cid_status };
309    let resp = match client
310        .inner()
311        .update_artifact_cid_status(&task_id, &artifact_id, &body)
312        .await
313    {
314        Ok(v) => v.into_inner(),
315        Err(e) => return Err(map_api_error(e).await.into()),
316    };
317    Ok(Envelope::success(
318        ctx.environment,
319        ctx.dry_run,
320        json!({
321            "task_id": task_id.to_string(),
322            "artifact": resp,
323        }),
324    ))
325}
326
327fn parse_uuid(raw: &str, label: &str) -> Result<Uuid, CmdError> {
328    Uuid::parse_str(raw).map_err(|e| CmdError::Usage(format!("{label} must be a UUID: {e}")))
329}